Microsoft SDK for Java Version 2.5

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Java Logo

Welcome! | Index
Presenting Java! | Microsoft Technologies for Java Home

Microsoft SDK for Java Version 2.5

The Microsoft SDK for Java version 2.5 provides the tools, information, and samples to help you develop Java programs and applets based on JDK 1.1 and the Microsoft Win32 Virtual Machine for Java (Microsoft VM). All previous versions of the Microsoft SDK for Java are replaced by this SDK. It contains the retail version of the Microsoft VM, the Application Foundation Classes (AFC), and many other packages, tools, and samples. The Microsoft SDK for Java version 2.5 is fully redistributable.

This documentation package provides up-to-date reference and overview information on the class libraries, application programming interfaces (APIs), and tools in the Microsoft SDK for Java. To locate the areas you are interested in, select from the topics that are listed in the left margin and described below. For access to specific elements, use the Index button at the top of the main topic pages.

To download the Microsoft SDK for Java, visit our Web site at http://www.microsoft.com/Java/.

For information on support policies for this SDK, see SDK for Java Support Options.

Microsoft SDK for Java Topics

Welcome
Provides an introduction to the SDK for Java and describes the major topics in the documentation.
Release Notes
Provides a link to the latest release notes posted at http://www.microsoft.com/Java/sdk/relnotes.
Articles
Provides an index of all articles in this SDK. Most of these articles can also be accessed from their specific topic areas.
Packages
Provides an alphabetic listing of all the packages provided in this SDK. Each package contains detailed information about its classes.
Tools
Describes the Java tools included in this SDK. A quick reference table provides the command-line syntax for each tool, and several articles describe how and when to use many of these tools.
Microsoft VM
Describes APIs that give programs direct access to features of the Microsoft Win32 Virtual Machine for Java, such as the Just-In-Time compiler. This information can help tool vendors develop tools for Java.
AFC
Explains how to use the Microsoft Application Foundation Classes (AFC) in your Java applets and applications, and provides links to the AFC reference documentation.
J/Direct
Explains how your Java programs and applets can make direct calls to Windows DLLs and Windows APIs.
Java and Native Code
Provides an overview of the various ways that the Microsoft Win32 Virtual Machine for Java enables code written in Java to work with code written for the Win32 platform.
Package Manager
Provides an introduction to the Java Language Package Manager and the tools in this SDK that can be used with it.
Security
Provides an introduction to the Microsoft trust-based security for Java security model and links to the packages in this SDK that affect security.
Internationalization
Explains how to take advantage of the Microsoft internationalization support provided for Java applications.

Note: The icon External Link indicates that the link takes you to a URL that is outside the Microsoft SDK for Java site; you can return to the SDK for Java site by using the Back button. Note that some of these external links may point to servers that are not under the control of Microsoft. Please read the official statement from Microsoft External Link regarding other servers.


SDK for Java 2.5 License Agreement

Other Release Notes

* Installation Instructions

* Redistribution Components

* Microsoft Virtual Machine

* J/Direct
* Security Model
* Known Issues

* Class Libraries

* DirectX3J

* Microsoft AFC

* Tools and Utilities

* Developer Support

* Bug Reporting

Release Notes | Java Home
Introduction | Java Home

END-USER LICENSE AGREEMENT FOR MICROSOFT SOFTWARE

IMPORTANT—READ CAREFULLY: This Microsoft End-User License Agreement ("EULA") is a legal agreement between you (either an individual or a single entity) and Microsoft Corporation for the Microsoft software product identified above, which includes computer software and may include associated media, printed materials, and "online" or electronic documentation ("SOFTWARE PRODUCT"). By installing, copying, or otherwise using the SOFTWARE PRODUCT, you agree to be bound by the terms of this EULA. If you do not agree to the terms of this EULA, do not install or use the SOFTWARE PRODUCT.

Microsoft SOFTWARE DEVELOPMENT KIT FOR JAVA VERSION 2.5

The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.

1. GRANT OF LICENSE. This EULA grants you the following rights

a. Software Product. Microsoft grants to you as an individual, a personal, nonexclusive license to make and use copies of the SOFTWARE for the sole purposes of designing, developing, and testing your software product(s). You may install copies of the SOFTWARE PRODUCT on an unlimited number of computers provided that you are the only individual using the SOFTWARE PRODUCT. If you are an entity, Microsoft grants you the right to designate one individual within your organization to have the right to use the SOFTWARE PRODUCT in the manner provided above.

b. Electronic Documents. Solely with respect to electronic documents included with the SOFTWARE PRODUCT, you may make an unlimited number of copies (either in hardcopy or electronic form), provided that such copies shall be used only for internal purposes and are not republished or distributed to any third party.

c. Storage/Network Use. You may also store or install a copy of the SOFTWARE PRODUCT on a storage device, such as a network server, used only to install or run the SOFTWARE PRODUCT on your other computers over an internal network; however, you must acquire and dedicate a license for each separate computer on which the SOFTWARE PRODUCT is installed or run from the storage device. A license for the SOFTWARE PRODUCT may not be shared or used concurrently on different computers.

d. Sample Code. In addition to the rights granted in Section 1(a), Microsoft grants you a non-exclusive, royalty-free right to modify the source code version of those portions of the SOFTWARE PRODUCT that are identified as sample code in the REDIST.HTM file in the SOFTWARE PRODUCT ("SAMPLE CODE"), for the sole purposes of designing, developing, and testing your software product(s), provided that you comply with Section 1(f), below.

e. Redistributable Files. In addition to the rights granted in Section 1(a), Microsoft grants you a nonexclusive, royalty-free right to reproduce and distribute in object code form only the SAMPLE CODE and all the other files identified in the REDIST.HTM file located in the SOFTWARE PRODUCT (the "REDISTRIBUTABLES"), provided that you comply with Section 1(f), below.

f. Redistribution Requirements. If you wish to distribute the REDISTRIBUTABLES, you agree to: (i) distribute the REDISTRIBUTABLES in object code only in conjunction with and as a part of a software product developed by you that adds significant and primary functionality to the REDISTRIBUTABLES ("Licensed Product"); (ii) not use Microsoft’s name, logo, or trademarks to market your Licensed Product; (iii) include a valid copyright notice on your Licensed Product; (iv) indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorney’s fees, that arise or result from the use or distribution of your Licensed Product; (v) distribute all of the files listed under each of the headings in the REDIST.HTM file (e.g., "Tool Files"); (vi) not permit further distribution of the REDISTRIBUTABLES.

The following exceptions apply to subsection (f)(vi), above:

(A) you may permit further redistribution of the REDISTRIBUTABLES by your distributors to your end-user customers if your distributors only distribute the REDISTRIBUTABLES in conjunction with, and as part of, your Licensed Product and you and your distributors comply with all other terms of this EULA;

(B) you may permit your end users to reproduce and distribute the object code version of the files listed below ("Limited-Use Redistributable Files") for use in development of an application created by your end user ("End User Application"), provided that your end user agrees to: (i) distribute the Limited-Use Redistributable Files in object code only in conjunction with and as a part of a software application product developed by them that adds significant and primary functionality to the Limited-Use Redistributable Files ("End User Application"); (ii) not use Microsoft’s name, logo, or trademarks to market the End User Application; (iii) include a valid copyright notice on the End User Application; (iv) indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorney’s fees, that arise or result from the use or distribution of the End User Application; (v) not distribute less than all of the files listed under each of the headings in the REDIST. HTM file if your end user distributes any one or more of such files in an End User Application; and (vi) not permit further distribution of the Limited-Use Redistributable Files by the user of the End User Application. Limited-Use Redistributable Files: the Limited-Use Redistributable Files are all of the files listed in the REDIST.HTM file of the SOFTWARE PRODUCT, except those in Section 3.

g. Special Requirements for AFC.

The following also applies to the Microsoft Application Foundation Classes ("AFC"):

Microsoft grants you the right (i) to install AFC in object code form on an unlimited number of Web server computers and allow users to access and download AFC via an HTTP connection into their client-side Web browser cache in order to run applets that rely on AFC functionality, provided that you (A) not use Microsoft's name, logo, or trademarks to market your applet; (B) indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorney's fees, that arise or result from the use or distribution of your applets; and (C) load all the files included in AFC onto such server computers; OR (ii) to download and install copies of the SOFTWARE PRODUCT in object code form on your client-side computer for use in conjunction with validly licensed copies of Microsoft Internet Explorer versions 3.0.2 and 4.0 for Microsoft Windows 95 and Windows NT 4.0, Netscape Navigator 3.0.4 for Microsoft Windows 95 and Windows NT 4.0 and Sun Solaris, and Netscape Navigator/Communicator 4.0.3 for Microsoft Windows 95 and Windows NT 4.0 and Sun Solaris; OR (iii) to upload a copy of AFC onto an unlimited number of server computers and allow users to download and install AFC in object code form, provided that you require such users prior to download to agree to the terms of this EULA or another license that is at least as restrictive as this EULA. If you wish to redistribute AFC with a standalone Java application program, you must redistribute the Microsoft virtual machine for Java, which includes AFC. The redistribution rights and obligations associated with the Microsoft virtual machine for Java are described in Section 1(f) above. Development Tool vendors must obtain a separate license from Microsoft for the right to distribute AFC with their tool products.

2. UPGRADES. If the SOFTWARE PRODUCT is labeled as an upgrade, you must be properly licensed to use a product identified by Microsoft as being eligible for the upgrade in order to use the SOFTWARE PRODUCT. A SOFTWARE PRODUCT labeled as an upgrade replaces and/or supplements the product that formed the basis for your eligibility for the upgrade. You may use the resulting upgraded product only in accordance with the terms of this EULA. If the SOFTWARE PRODUCT is an upgrade of a component of a package of software programs that you licensed as a single product, the SOFTWARE PRODUCT may be used and transferred only as part of that single product package and may not be separated for use on more than one computer.

3. COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, photographs, animations, video, audio, music, text, and "applets" incorporated into the SOFTWARE PRODUCT), the accompanying printed materials, and any copies of the SOFTWARE PRODUCT are owned by Microsoft or its suppliers. The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, you must treat the SOFTWARE PRODUCT like any other copyrighted material except that you may install the SOFTWARE PRODUCT on a single computer provided you keep the original solely for backup or archival purposes. You may not copy the printed materials accompanying the SOFTWARE PRODUCT.

4. PRERELEASE CODE. The SOFTWARE PRODUCT may contain PRERELEASE CODE that is not at the level of performance and compatibility of the final, generally available, product offering. These portions of the SOFTWARE PRODUCT may not operate correctly and may be substantially modified prior to first commercial shipment. Microsoft is not obligated to make this or any later version of the SOFTWARE PRODUCT commercially available. Microsoft grants you the right to distribute test versions of your Licensed Product created using the PRERELEASE CODE provided you comply with the license terms described in Section 1 and the following additional provisions: (a) you must mark the test version of your Licensed Product "BETA" and (b) you are solely responsible for updating your customers with versions of your Licensed Product that operate satisfactorily with the final commercial release of the PRERELEASE CODE. In order to determine what constitutes PRERELEASE CODE, consult the REDIST.HTM file located in the SOFTWARE PRODUCT.

5. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS

a. Limitations on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation.

b. Separation of Components. The SOFTWARE PRODUCT is licensed as a single product. Its component parts may not be separated for use on more than one computer.

c. Rental. You may not rent, lease, or lend the SOFTWARE PRODUCT.

d. Support Services. Microsoft provides no support for this SOFTWARE PRODUCT.

e. Software Transfer. You may permanently transfer all of your rights under this EULA, provided you retain no copies, you transfer all of the SOFTWARE PRODUCT (including all component parts, the media and printed materials, any upgrades, this EULA, and, if applicable, the Certificate of Authenticity), and the recipient agrees to the terms of this EULA. If the SOFTWARE PRODUCT is an upgrade, any transfer must include all prior versions of the SOFTWARE PRODUCT.

f. Termination. Without prejudice to any other rights, Microsoft may terminate this EULA if you fail to comply with the terms and conditions of this EULA. In such event, you must destroy all copies of the SOFTWARE PRODUCT and all of its component parts.

6. U.S. GOVERNMENT RESTRICTED RIGHTS. The SOFTWARE PRODUCT and documentation are provided with RESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software—Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation/One Microsoft Way/Redmond, WA 98052-6399.

7. EXPORT RESTRICTIONS. You agree that neither you nor your customers intend to or will, directly or indirectly, export or transmit (i) the SOFTWARE or related documentation and technical data or (ii) your software product as described in Section 1(f) of this License (or any part thereof), or process, or service that is the direct product of the SOFTWARE, to any country to which such export or transmission is restricted by any applicable U.S. regulation or statute, without the prior written consent, if required, of the Bureau of Export Administration of the U.S. Department of Commerce, or such other governmental entity as may have jurisdiction over such export or transmission.

8. NOTE ON JAVA SUPPORT. THE SOFTWARE PRODUCT CONTAINS SUPPORT FOR PROGRAMS WRITTEN IN JAVA. JAVA TECHNOLOGY IS NOT FAULT TOLERANT AND IS NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR RESALE AS ONLINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATIONS SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF JAVA TECHNOLOGY COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE.

MISCELLANEOUS

If you acquired this product in the United States, this EULA is governed by the laws of the State of Washington.

If you acquired this product in Canada, this EULA is governed by the laws of the Province of Ontario, Canada. Each of the parties hereto irrevocably attorns to the jurisdiction of the courts of the Province of Ontario and further agrees to commence any litigation which may arise hereunder in the courts located in the Judicial District of York, Province of Ontario.

If this product was acquired outside the United States, then local law may apply.

Should you have any questions concerning this EULA, or if you desire to contact Microsoft for any reason, please contact the Microsoft subsidiary serving your country, or write: Microsoft Sales Information Center/One Microsoft Way/Redmond, WA 98052-6399.

If you have a specific question regarding the licensing of redistributables, you may call the Microsoft Technical Sales Information Team at (800) 426-9400 (United States only) or send inquiries via fax to Microsoft SDK for Java Licensing Administrator, (206) 936-7329 (United States only).

LIMITED WARRANTY

LIMITED WARRANTY. To the maximum extent permitted by applicable law, Microsoft and its suppliers disclaim all other warranties, either express or implied, including, but not limited to, implied warranties of merchantability AND fitness for a particular purpose, with regard to the SOFTWARE PRODUCT, and any accompanying hardware. This limited warranty gives you specific legal rights. You may have others, which vary from state/jurisdiction to state/jurisdiction. NOTWITHSTANDING THE FOREGOING, MICROSOFT WARRANTS THAT IT HAS ALL THIRD PARTY LICENSE RIGHTS THAT ARE NECESSARY TO GRANT THE LICENSE RIGHTS SET FORTH HEREIN.

LIMITATION OF LIABILITY. EXCEPT WITH RESPECT TO THE WARRANTY SET FORTH IN THE LAST SENTENCE OF THE "LIMITED WARRANTY" SECTION ABOVE, MICROSOFT’S ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY UNDER THIS EULA SHALL NOT EXCEED ONE HUNDRED DOLLARS (US$100.00).

NO LIABILITY FOR CONSEQUENTIAL DAMAGES. To the maximum extent permitted by applicable law, in no event shall Microsoft or its suppliers be liable for any special, incidental, indirect, or consequential damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use thE software product, even if Microsoft has been advised of the possibility of such damages. Because some states and jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.

Si vous avez acquis votre produit Microsoft au CANADA, la garantie limitée suivante vous concerne :

GARANTIE LIMITEE

GARANTIE LIMITEE — Sauf pour celles du REDISTRIBUTABLES, qui sont fournies "comme telles", sans aucune garantie quelle qu’elle soit, Microsoft garantit que (a) la performance du LOGICIEL sera substantiellement en conformité avec le(s) manuel(s) de produits qui accompagne(nt) le LOGICIEL pour une période de quatre-vingt-dix (90) jours à compter de la date de réception ; et (b) tout matériel fourni par Microsoft accompagnant le LOGICIEL sera exempt de défaut de matière première ou de vice de fabrication dans des conditions normales d’utilisation et d’entretien pour une période d’un an à compter de la date de réception. Toute garantie implicite concernant le LOGICIEL et le matériel est limitée à quatre-vingt-dix (90) jours et un (1) an, respectivement.

RECOURS DU CLIENT — La seule obligation de Microsoft et votre recours exclusif seront, au choix de Microsoft, soit (a) le remboursement du prix payé ou (b) la réparation ou le remplacement du LOGICIEL ou du matériel qui n’est pas conforme à la Garantie Limitée de Microsoft et qui est retourné à Microsoft avec une copie de votre reçu. Cette Garantie Limitée est nulle si le défaut du LOGICIEL ou du matériel est causé par un accident, un traitement abusif ou une mauvaise application. Tout LOGICIEL de remplacement sera garanti pour le reste de la période de garantie initiale ou pour trente (30) jours, selon laquelle de ces deux périodes est la plus longue.

AUCUNE AUTRE GARANTIE — MICROSOFT DESAVOUE TOUTE AUTRE GARANTIE, EXPRESSE OU IMPLICITE, Y COMPRIS MAIS NE SE LIMITANT PAS AUX GARANTIES IMPLICITES DU CARACTERE ADEQUAT POUR LA COMMERCIALISATION OU UN USAGE PARTICULIER EN CE QUI CONCERNE LE LOGICIEL, LE(S) MANUEL(S) DE PRODUITS, LA DOCUMENTATION ECRITE ET TOUT MATERIEL QUI L’ACCOMPAGNENT. CETTE GARANTIE LIMITEE VOUS ACCORDE DES DROITS JURIDIQUES SPECIFIQUES.

PAS D’OBLIGATION POUR LES DOMMAGES INDIRECTS — MICROSOFT OU SES FOURNISSEURS N’AURONT D’OBLIGATION EN AUCUNE CIRCONSTANCE POUR TOUT AUTRE DOMMAGE QUEL QU’IL SOIT (Y COMPRIS, SANS LIMITATION, LES DOMMAGES ENTRAINES PAR LA PERTE DE BENEFICES, L’INTERRUPTION DES AFFAIRES, LA PERTE D’INFORMATION COMMERCIALE OU TOUTE AUTRE PERTE PECUNIAIRE) DECOULANT DE L’UTILISATION OU DE L’IMPOSSIBILITE D’UTILISATION DE CE PRODUIT MICROSOFT, ET CE, MEME SI MICROSOFT A ETE AVISE DE LA POSSIBILITE DE TELS DOMMAGES. EN TOUT CAS, LA SEULE OBLIGATION DE MICROSOFT EN VERTU DE TOUTE DISPOSITION DE CETTE CONVENTION SE LIMITERA AU MONTANT EN FAIT PAYE PAR VOUS POUR LE LOGICIEL.

La présente Convention est régie par les lois de la province d’Ontario, Canada. Chacune des parties à la présente reconnaît irrévocablement la compétence des tribunaux de la province d’Ontario et consent à instituer tout litige qui pourrait découler de la présente auprès des tribunaux situés dans le district judiciaire de York, province d’Ontario.

Au cas où vous auriez des questions concernant cette licence ou que vous désiriez vous mettre en rapport avec Microsoft pour quelque raison que ce soit, veuillez contacter la succursale Microsoft desservant votre pays, dont l’adresse est fournie dans ce produit, ou écrire à : Microsoft Sales Information Center, One Microsoft Way, Redmond, Washington 98052-6399.


Support

Support | Support
Support | SDK for Java

Developer Support for the Microsoft SDK for Java Version 2.5

Pay-Per-Incident Support
For after-hours support or to supplement Standard No-Charge Support that has been exhausted or expired. Submit questions via telephone or Web Response.

In the U.S.: $95US per incident 800-936-5800 or 900-555-2300
In Canada: $95US per incident, 800-936-5800

Priority Annual Support
For small- to medium-sized businesses that require 24 hour-a-day, 7 day-a-week priority access to support engineers, and anticipate high-volume support needs.

Priority Annual Developer Account
In the U.S. and Canada: $895US per 10 incidents, 800-936-4800

Priority Plus
For large businesses that need business-critical support and access to specialized, information for planning for smoother product deployment.

Includes:
Incident Resolution:
Base of 100 incidents covering all Microsoft products; priority access 24 hours a day, 7 days a week; server down support; Early Assist support for selected Beta products.
Specialized Technical Information:
Exclusive access to the online Priority Plus Service Desk, which contains technical information and resources created especially for Priority Plus information technology and help desk professionals.
Account Administration
Account Administration by a designated Account Administration Team to coordinate support services.
Total Costs in the U.S. and Canada: $20,000US
For more information, in the U.S. and Canada, call 800-936-3500. To submit an incident or access the Priority Plus Account Administration Team, call 800-936-5400.

Priority Consult Line
For information technology professionals who need hourly consultation on specialized support planning, including software development, code design review, and implementation planning.

Phone-based, hourly consulting with technical specialist focused on designing, planning, code design review, or implementation planning around Microsoft products or technologies. Covers all released Microsoft products. $195 US per hour (One hour minimum). In the U.S. and Canada, call 800-936-5200.

Premier Support
For large enterprise businesses that require a direct relationship with Microsoft.

Highest level of mission-critical support that includes:
Technical Account Management:
Personal account management to ensure Premier Support meets the unique needs of each individual business.
Technical Services:
Proactive information and planning services aimed at reducing systems management and support costs by planning to avoid problems before they occur.
Technical Support:
Fast, accurate solutions to operational problems around the clock.
In the U.S. and Canada, call 800-936-3200 to reach a representative to discuss pricing and information.

For No Charge, Peer to Peer Support
You will find a valuable resource in the Microsoft sponsored public newsgroups.

Peer-to-peer newsgroups are available to help you interact with other users of our products. You can use any newsreader software to access these newsgroups. However, we suggest downloading Internet Mail and News from the Microsoft Internet Explorer Home page. With Microsoft Internet Mail and News installed, after you click on a newsgroup link, you'll be prompted for different configuration information. When prompted for News Server, specify "msnews.microsoft.com" without the quotation marks.

NOTE: You do not need to enter an account name or password.

If you are using an NNTP newsreader (sometimes called a news client) other than Internet Mail and News, don't forget to configure it to read the newsgroups. The Microsoft news server name is msnews.microsoft.com.

  • ActiveX and Java (microsoft.public.java.activex)
  • Application Foundation Classes (AFC) and Java (microsoft.public.java.afc)
  • CAB and Java (microsoft.public.java.cab)
  • DirectX and Java (microsoft.public.java.directxj)
  • J/Direct (access to Win32 DLL's from Java) (microsoft.public.java.jdirect)
  • Java virtual machine for the Macintosh (microsoft.public.java.macvm)
  • SDK for Java (microsoft.public.java.sdk)
  • Security and Java (microsoft.public.java.security)
  • Visual J++ specific issues (microsoft.public.java.visualj++)
  • Java virtual machine (microsoft.public.java.vm)
  • Java virtual machine for Windows 16-bit (microsoft.public.java.win16vm)
  • Non-Developer Java Discussion (microsoft.public.internetexplorer.java)

Bug Reporting
Please use the on-line bug report provided on our http://www.microsoft.com/java/misc/sdkbug.htm page.


Changes in class libraries from 2133 to current release

In this topic

Release Notes | Release Notes
Changes in class libraries from beta 2 release to final release | Introduction

AFC Class library changes: A list of class library changes between beta 2 and final release is provided on http://www.microsoft.com/java/afc


Development Tools and Utilities

Here is the list of the tools and utilities that are provided in this SDK. In order for you to use the tools under SDK\Bin, you need to set the relative path to the directory. For usage details, please refer to the SDK documentation under the Tools section.

Compiling and Debugging Utilities

Classr.exe: A utility that installs retail version of the system classes to be package managed and onto the CLASSPATH.

Classd.exe: A utility that installs debugging version of the system classes to be package managed and onto the CLASSPATH.

Javasrc.exe: A utility that extracts source code out of the debugging version of the system classes.

Jexegen.exe: A tool that wraps stand-alone Java applications with a thin native executable binary.

AWT2AFC: A tool that helps developers convert Java code from using AWT to AFC. The classes considered for conversion come from java.awt and java.applet binary. Detailed information is available under the \Bin\awt2afc directory.

Jntsvc.exe: You will find the NT service classes and the tool that converts the Java classes to the NT service executable in the SDK\Bin\Jntsvc directory.

Jvc.exe: The latest beta version of the Java Language Compiler with full JDK 1.1 support including:

  • Inner Classes
  • Anonymous Classes
  • Instance Initializers
  • Anonymous Array Expressions
  • Class Literals
  • Blank Finals and Final Locals
  • The @deprecated Tag
  • Uncompressed JAR File Support
  • Support @COM syntax for JActiveX users

For detailed release information, please refer to the JVC release note and the SDK documentation.

JView.exe: Java Application Viewer. By using -a, it serves as AppletViewer.

NMake.exe: The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file, "makefile". See NMAKE.TXT for more information.

Native Code, COM Tools and Header Files

Guidgen.exe: Generates globally unique identifiers (GUIDs).

JActiveX: A new powerful COM, ActiveX/Bean integration support tool which can be used in conjunction with the latest Jvc provided in this SDK only. For detailed information, please refer to the JActiveX documentation under Tools.

Msjavah.exe: Updated Microsoft version of C header file generator; refer to the documentation for usage.

Nativcom.h: This header contains public COM APIs exposed by the Microsoft VM.

Native.h: This header file exposes structures and functions used in the Microsoft Raw Native Interface. Please refer to the SDK documentation on Java & Native Code for detailed information.

ResMerge: A new tool which can be used in conjunction with the Win32ResourceDecoder class for localization of resources. It merges multiple .res files into a single .res file. Please refer to the SDK documentation under the Tools section for usage information.

Software Distribution

Cabarc: Updated compression tool which will help developers make compressed self-extracting Java programs for downloading. Both carbarc and master.inf is provided in the \Bin\PackSign directory for creating CABs as well.

DUBuild.exe: A utility for packaging Java classes into Distribution Units, to be installed into the package manager through a signed CAB file with an OSD manifest.

JavaSign.dll: A DLL that can be used with SignCode to add Java privilege information to CAB files.

ChkJava: A tool used to display the Java privilege information signed in a CAB file.

MakeCert: A tool to generate test X.509 certificates for use with SignCode.

Cert2SPC: A tool to create a test SPC file for use with SignCode.

ChkTrust: A tool to display the Java privilege information signed in a CAB file.

CertMgr.exe: A utility that displays the contents of a certificate.

SignCode: A tool to digitally sign files.

SetReg: A tool to change registry settings.

CPRMEDIT: Permission Editor (cprmedit) tool allows users to edit Java permissions for specific security zones using a graphical user interface.

PIniEdit.exe:The Permission INI File Editor tool provides a quick way to create .ini files that are used with the signcode tool.

Package Manager tools

clspack: Clspack is used to create a ZIP set of packages. This tool converts packages that are currently installed via the package manager, and writes their contents into a ZIP file.

Known Issues for Tools

Note for Visual J++ users: Please be aware that the SDK contains the latest pre-release version of Jvc for use with JDK1.1 development. JavaTLB has been removed, but you can use JActiveX and JVC to produce the same output. If you are doing commercial Java development and are not dependent on any of the new JDK 1.1 features, you should use the retail version of JVC that is released with Visual J++.


DirectAnimation Release Notes

In this topic

* Overview

* Requirements, Dependencies, and Installation

* Additional Information

* Known Bugs

* Contact Information

Release Notes | Release Notes
DirectAnimation Release Notes | Introduction

This document provides late-breaking or other information that supplements the Microsoft DirectAnimation documentation.

Overview

DirectAnimation is released as an integrated component of Internet Explorer 4.0 minimal install. This provides unprecedented animation and multimedia capabilities built into a major Internet browser (no special download is needed). Furthermore, DirectAnimation is integrated with DHTML, and hence is especially suitable for adding compact and lightweight animation effects to web pages.

DirectAnimation is the component of the DirectX family of APIs that provides rich animation and integrated media support for Web pages, CD-ROM titles, and multimedia applications. DirectAnimation provides a unified and comprehensive support for the different media types, including: 2D vector graphics, 3D graphics, sprites, audio, video, and a rich time and event model that applies uniformly across the different media types. DirectAnimation is a COM API and an underlying engine/runtime whose functionally can be accessed in different ways by different user groups:

  • HTML authors can integrate animation using the DirectAnimation controls.
  • Microsoft® Visual Basic® Scripting Edition (VBScript), JScript users, and Java applet writers can program animation for web pages with integration with DHTML.
  • Finally, Java, Visual Basic, and C++ programmers can develop ActiveX Controls or full applications with rich media and interactivity.

The supported media types are as follows:

  • 2-D images (.bmp, .gif, .png, and .jpeg files)
  • 3-D models (.x and VRML files)
  • Sounds (.wav and .midi files)
  • Movies (.avi, .mpeg, and .mov files)
  • Text

In the case of movies and sounds, additional media formats can be supported by suplying DirectShow CODECs for those formats.

One of the key DirectAnimation classes is the Behavior class. Different types of media are incorporated into the animation by encapsulating them as DirectAnimation Behavior objects. Behavior objects can be used interchangeably, and have a number of methods applied to them, independent of the media type they are encapsulating. Of course, you can still access methods that are specific to the different types of behaviors, based on the type of media.

Requirements, Dependencies, and Installation

The minimum requirements in order to run DirectAnimation applications and content are as follows:

  • Pentium-based computer
  • Windows 95 or NT 4.0
  • DirectX, including Direct3D (for NT users, we recommend SP3)
  • Internet Explorer 4.0 (Netscape Navigator can also be used for Java applets; see Additional Information )

The DirectAnimation runtime comes as part of IE4 minimal install . DirectAnimation will also be part of Windows 98 and future releases of Windows NT.

The DirectAnimation SDK includes an extensive set of documents and samples that illustrate the breadth and depth of functionality, it is available for download , and for browsing .

For a white paper on DirectAnimation, check the "Getting Started" document.

Additional Information

Significant enhancements since the beta release have been the addition of support for scripting languages (JScript and VBScript), as well as the integration of the multimedia controls (in Internet Explorer 4.0) with the DirectAnimation runtime. In addition to the multimedia controls, a windowed control is provided which can be used with IE 3.02 and with Visual Basic. With the addition of the multimedia controls, content developers can now access DirectAnimation functionality through different levels, from PARAM tags at the control level, to scripting, to raw COM.

The DirectAnimation Java classes are dependent on the version of the Microsoft VM that ships with the Microsoft SDK for Java and Internet Explorer 4.0. We used Microsoft Visual J++ 1.1 to author the Java samples.

In order to use DirectAnimation Java-based content within Netscape's Navigator, follow these instructions:

Microsoft has made a plug-in available to users of Netscape Navigator 2.02 and 3.0 that allows them to make use of the Microsoft VM. Netscape Communicator is not yet supported because of changes made to the plug-in interface. Note that this plug-in does not replace the Netscape Java VM, but it does provide access to the Microsoft VM through the use of the <embed> tag. To get an applet up and running under Netscape, follow these simple steps.

  1. Get the plug-in from the SDK for Java 2.5 and place it in your Navigator\Program\Plugins directory.
  2. Install the required Microsoft VM, if you haven't already.
  3. Change the applet tag in your source html from this:

<applet code="foo.class" width=100 height=100></applet>

To this:

<embed src="foo.class" width=100 height=100></embed>

In general, we recommend that you upgrade to the DirectX 5 set of video drivers. Several visual artifacts that appear under older versions of video drivers disappear with the newer set.

Known Bugs

The following is a list of current known problems. We strongly encourage you to send us mail if you find a problem ( dxmbug@microsoft.com ). There are newsgroups set up to allow DirectAnimation content developers to discuss issues and ideas, however mailing a bug description is the only sure way to get a fix for a bug.

General

  • For Java content, all initialization of DirectAnimation behaviors and events needs to happen in methods (cannot happen in classes outside of methods); however, you can have declarations of behaviors outside methods to make them accessible from other classes and throughout the methods of a class.
  • There are some small memory leaks, most notably when using 3-D, sounds, or notifiers. To fix this in Java, implement public void cleanup() to the class that extends Model. In this method, call super.cleanup() and set all behaviors that are suspected of leaking memory to NULL. If you have other classes which contain DA behaviors, implement public void cleanup() and only set suspect behaviors to NULL. Also, add the public void destroy() to the class that extends DXMApplet. In this method, call super.destroy() and set the model to null.
  • For Java content, sometimes the LeftButtonPress events miss.
  • The cursor is considered to be in the middle of the window when DirectAnimation first comes up.
  • TextPath and TextImage are now obsolete, please use StringPath and StringImage instead.
  • Notifiers can only be inplemented in Java.
  • AnimateControlPosition takes parameters in meters, even if you are using the pixel library.
  • Only DirectDraw surfaces created through DirectDrawEx can be imported.

Graphics

  • Shearing movies and lines does not work properly.
  • Color palette is not correct for 256 colors displays under NT.
  • SubstituteTime does not work right when applied to Splines.
  • FollowPathAngleUpright isn't doing the uprightness.
  • Although class browsers or Visual Basic show the parameters to arc and roundedrect as radius, they are really the diameter.
  • Using Java, time-varying opacity may cause the whole object to become solid after some time.
  • TextMatte isn't allowing enough of the image to be drawn through.
  • Knot duplicity for splines is not handled.
  • Bounding box of a sheared behavior is incorrect.
  • Overlaying an image on a solidColorImage, cropping it, and then adding a rotation transform, results in the solidColorImage disappearing. The workaround is to crop the solidColorImage into a matte.
  • Underline and strikethrough don't work on NT.

Audio

  • Sound does not turn off all the time.
  • SinSynth plays at 440Hz no matter what rate is specified..
  • Dynamic phasing isn't enabled.
  • Loop causes the leaf sounds to loop, not the combined sound behavior (this is the intended behavior).
  • SinSynth mixed with static sound gives a choppy sin sound.
  • Audio time substitutions not accumulating

3-D

  • Textures are not propagating down the leaf geometries for .X-files-based 3-D objects.

Movies

  • To use a movie as a texture, you have to use the following workaround (code snippet in JScript):

movieImport
        = m.ImportMovie("http://movie.avi");
movieImg = movieImport .Image;

// This is the workaround
movieBBox = movieImg.BoundingBox;
solidImg = m.SolidColorImage(m.White);
solidImg = solidImg.Crop(movieBBox.Min,movieBBox.Max);

movieImg = m.Overlay(movieImg,solidImg);

Controls

  • When using the Sprite multimedia control, source .bmp images over 2048 pixels long have to be broken into arrays of images (rows and columns of images, instead of just one long row or column).
  • Under some video drivers, filtered transparent pixels render as black.
  • For the Path control, TimeMarker persistence parameter "-1" works like FALSE in JScript.

Contact Information

We've set public news groups on the msnews-gw NNTP server, as a forum for the DirectAnimation user community. We encourage you to post all questions related to the use of DirectAnimation on the appropriate news group:

  • microsoft.public.multimedia.directx.danimation.controls is for users of the DirectAnimation controls.
  • microsoft.public.multimedia.directx.danimation.programming is for programmers of the DirectAnimation API.

For reporting bugs against the preview version, send mail to dxmbug@microsoft.com . When you do so, make sure to be specific about the OS, PC/graphics card, version of Internet Explorer 4, and specific host language/control that you're using to access DirectAnimation.

For other issues or comments that are not appropriate for the forums above, send mail to dxmbeta@microsoft.com .


Release Notes

Other Release Notes

* Installation Instructions

* Redistribution Components

* Microsoft Virtual Machine

* J/Direct
* Security Model
* Known Issues

* Class Libraries

* DirectX3J

* Microsoft AFC

* Tools and Utilities

* Developer Support

* Bug Reporting

Release Notes | Java Home
Introduction | Java Home

Microsoft SDK for Java

This version of the SDK includes:

  • The Microsoft Win32 Virtual Machine for Java: This release supports many new features including continued industry performance leadership, JDK 1.1 support, automatic and bi-directional integration between Microsoft® ActiveX® components and JavaBeans, Microsoft® J/Direct™, permissions-based security, package management, console to view debug output and expanded internationalization (i18n) support.
  • Application Foundation Classes (AFC): AFC provides a suite of user interface components and graphics effects classes for building richer user interfaces that will work with a number of popular browsers.
  • Other featured packages include DirectX™ 3 for Java, DirectAnimation™, XML, Win32 API classes for J/Direct, and a comprehensive set of samples.
  • Development tools and utilities: These are located in the SDK \Bin directory and its subdirectories. In order to use the tools, please set the path accordingly. The SDK for Java includes the latest pre-release version of the Microsoft Compiler for Java with JDK1.1 support (jvc) (which will not automatically replace the VJ++ compiler if a developer has VJ++ installed), AWT2AFC for migrating AWT applets to AFC, NT Service conversion utility, packaging and signing tools, Javareg, JActiveX (a new COM support conversion tool), and many others.
  • The SDK also includes the Microsoft JDBC-ODBC Bridge.

Please read the license before using the SDK.

Developer Support

Developer support information is updated regularly at our web site: http://www.microsoft.com/java/sdk/20/support.htm.

Bug Report

Please use the online bug report provided on our http://www.microsoft.com/java/misc/sdkbug.htm page.


Installation Notes

In this topic

Release Notes | Release Notes
Installation | Introduction

Platform Support

With the exception of AFC, this SDK requires Windows 95 or Windows NT 4.0. Please install the latest retail version of Internet Explorer for development before you install the SDK on your machine. The latest version of Internet Explorer with the Authenticode 2 update may be installed from http://www.microsoft.com/ie/ . If you have Internet Explorer 3.02, you can download the Authenticode 2 update from http://www.microsoft.com/ie/security/authent2.htm .

SDK Installation

The steps to install the SDK for Java are as follows:

  1. Make sure the target machine you are using satisfies the platform requirements for Internet Explorer.
  2. If you have Internet Explorer 3.02, make sure the Security settings are enabled to allow downloading of active content (from the browser's View menu, choose Options, and then check "Allow downloading of Active Content" in the Security tab).
  3. Go to http://www.microsoft.com/java/download.htm and follow the links to download the SDK for Java.
  4. When you reach the Microsoft SDK for Java Version 2.5 page, choose Microsoft SDK for Java from the drop-down list box and click "Go to Download."
  5. Choose the SDK Setup executable SDKSetup.exe from one of the servers presented.

    The SDK Setup wizard is used to install all the SDK components including the Microsoft VM (x86 version). Once you run this, the wizard will be installed on your Start Menu. It is recommended that you then download the SDK components in step 3 below so that you can later run SDKSetup and install different components without revisiting the download web site.

    Tip: If you are using a modem and do not want to continually accept certificates for SDK components, you can check "Always trust software from Microsoft Corporation" on the first Security Warning dialog you see. This adds Microsoft Corporation to the Trusted Publishers list. To remove Microsoft from this list, follow one of these procedures:

    • Internet Explorer 3.02: From the View menu, choose Options, click the Security tab, click on the Publishers button, select Microsoft Corporation, and click on Remove.
    • Internet Explorer 4.0: From the View menu, choose Internet Options, click the Content tab, click on the Publishers button, select Microsoft Corporation, and click on Remove.

Running the SDK Setup wizard

If you are installing for the first time, follow these steps.

  1. If you have downloaded the SDK Setup wizard in step 4 above, choose Microsoft SDK for Java Active Setup from the Start Menu. Otherwise, follow steps 1 through 4 above, and then open SDKSetup.exe.
  2. Read and accept the license.
  3. Select the installation/download option you want.

    You can choose to install now (Online installation), download the components to your hard disk for later installation (Save to disk for later installation), or install and download at the same time (Install and save to disk).

    If you are downloading files to disk for later installation, you can define your destination directory or use the default directory provided at this time.

  4. Click Install.
  5. Click Yes when asked if it is OK to determine what Internet components are installed on your computer.
  6. Check the components you want to download or install. The latest Microsoft VM for Java (x86) must be installed with the SDK unless you are running Internet Explorer 4.0. The Microsoft VM for Java and the Core SDK 2.5 components are checked by default.
  7. Click Install.
  8. Choose the download server. The files will be downloaded and/or installed.

After installing the first time, you can run the SDK Setup Wizard from the Start Menu. To install any components that you have downloaded but not installed, follow these steps:

  1. From the Start Menu, choose Microsoft SDK for Java Active Setup.
  2. Accept the license.
  3. Choose the "Install from local files" option and click the Install button.
  4. Click Yes when asked if it is OK to determine what internet components are installed on your computer.
  5. Check the components you want to install.
  6. Optionally change the destination directory for the installed SDK components (you cannot change the destination of the runtime components).
  7. Click Install.

This SDK includes both retail and developer versions (with debugging information)of the system classes. There are two utilities in the SDK \Bin directory classr.exe (retail) and classd.exe (debugging) to be used to create a stand-alone classes.zip on your classpath respectively. The debugging version of classes.zip will contain java sources used by the compiler (jvc.exe).

The Win32 API Classes for Microsoft® J/Direct™ are installed with the core SDK installation. DirectAnimation classes are installed on IE4.0. For IE3.02 users, DirectAnimation classes can also be installed along with the DirectAnimation runtime by using the SDK setup wizard.

AFC Installation on Additional Platforms

AFC is implemented in Java and designed to run on multiple platforms. Please note that in this release, AFC is part of the system classes that support JDK 1.1, and a JDK 1.0.2-compatible, redistributable version of AFC is also provided. For the latest information on AFC, see the AFC web page (http://www.microsoft.com/java/afc).

Installing JDK 1.0.2-compatible AFC for Internet Explorer Version 3.0.2 and higher, Navigator 3.0.4 and Navigator 4.0.3 on Windows 95 and Windows NT 4.0:

The SDK contains a setup program that enables you to seamlessly install JDK 1.0.2-compatible AFC on whichever browser is the default browser on your client machine. Please ensure you have set the browser in which you wish to run JDK 1.0.2-compatible AFC as default before proceeding with the installation. The SDK also contains AFCDetect, a useful program that enables you to determine whether or not AFC is installed on your client machine. If AFC is not present, it is installed in the correct location.

Installing JDK 1.0.2-compatible AFC for Navigator 3.0.4 or 4.0.3 on Solaris:

  1. Copy AFC102.ZIP to an appropriate location on your computer (such as $HOME/classes). If you are unsure where this directory is, use the following to locate it:

    2. public static void main(String args [])
    {
    System.out.println( "java.home = " + System.getProperty( "java.home" ) );
    }
  2. Next, add this location to your CLASSPATH - for example: set CLASSPATH = $HOME/classes/afc102.zip:$CLASSPATH.

Uninstalling Previous Versions of the Microsoft SDK for Java:

Please remove any pre-release version of the SDK before installing this version.

To remove the beta 2 release:

  1. From the Control Panel folder under Settings on the Start menu, select Add/Remove Programs.
  2. Select "Microsoft SDK for Java".
  3. Select the "Add/Remove" button.

To remove the Preview Release, delete the SDK-Java.20 directory and subdirectories from your hard disk.


Redistributable Components

Release Notes

Release Notes | Release Notes
Redistributable Components | Introduction

Redistributable File List for Microsoft SDK for Java Version 2.5

This document identifies the files that you may redistribute with your application developed using the Microsoft SDK for Java. The conditions under which you may redistribute these files are described in the separate License Agreement under Redistribution Requirements.

The redistributable files are located inside SDK directories, unless otherwise noted. When you redistribute any of these files, you must ensure you are using the correct version of the files.

If you have installed the Microsoft SDK for Java version 2.5, you will notice that this release no longer provides a stand-alone Win32API package for redistribution. It is now part of the default classes installed with the Microsoft VM for Java. The JDK 1.0.2-compatible AFC files are also included and can be redistributed with your applications. Please review the license agreement before you redistribute these AFC files.

Categories of Redistributable Files

The following categories of redistributable files are described in this document.

1. Microsoft Virtual Machine for Java (x86 and Alpha)

2. SDK tools, Header and Lib files

3. SDK Samples

4. SDK Documentation

5. Microsoft Application Foundation Classes (AFC)

6. DirectX® 3 Runtime

7. DirectAnimation™ Package, Runtime, Samples and Documentation

8. General Redistribution Information

1. Virtual machines for x86 and Alpha systems

You may redistribute MSJavx86.exe (a self-extracting executable for x86 systems) and MSJavAxP.exe (a self-extracting executable for Alpha systems) with the SDK 2.5. To obtain the VM(x86), please select the Save to Disk option or the Install and Save to Disk option via the SDK Setup Wizard, you will find the MSJavx86.exe in your SDK download directory or the default directory C:\sdk-java.201\Components. MSJavAxP.exe can be downloaded via the pull down box of the SDK download page.

Individual files in the redistributable executables cannot be redistributed separately. The retail version of the stand alone VM for x86 (MSJavx86.exe) can be used with retail versions of Internet Explorer (IE4.0\IE4.01 or IE3.02); beta versions of Internet Explorer are not supported.

For information on the most recent version of the Microsoft VM for Java, see our web site: http://www.microsoft.com/java/

2. SDK tools, Header and Lib files

Most of the files provided with the SDK in the \Bin directory and the subdirectories are redistributable along with Microsoft VM redistribution.
The redistributable components in the \Bin directory are:

  • awt2afc.bat
  • classd.exe
  • classr.exe
  • Jexegen.exe
  • JView.exe
  • Guidgen.exe
  • JActiveX.exe
  • MSJavah.exe
  • Resmerge.exe
  • clspack.exe
  • javasrc.exe
  • javasrc.txt
  • javareg.exe
  • qvue.exe

    • The redistributable files under the \Bin\awt2afc directory are:

  • applet.htm
  • awt2afc.cab
  • awt2afc.ini
  • default.htm
  • all HTML files in the \awt2afc\docs subdirectory

    The redistributable files under the \Bin\JNtsvc directory are:

  • Jntsvc.exe
  • service.zip
  • TestService.java
  • makefile

    • The redistributable files under the \Bin\Packsign directory are:

  • cabarc.exe
  • master.inf
  • DuBuild.exe
  • DUReadme.txt

    • The redistributable files under the \Include directory are:

  • JavaDbg.h
  • Javaexec.h
  • JDbgGuid.h
  • nativcom.h
  • native.h

    • The redistributable files under the \Lib\i386 directory are:

  • javadbg.lib
  • msjava.lib

    • The pre-release version of the Java Language Compiler files in the \Bin directory are not redistributable with the SDK: JVC.exe, msjvc.dll, and jps.dll. Nmake.exe was released with Microsoft Visual C++ and is not for redistribution with this SDK.

    The following security/signing tools are not for redistribution with this SDK:

  • JavaSign.dll
  • ChkJava.exe
  • MakeCert.exe
  • Cert2SPC.exe
  • ChkTrust.exe
  • setreg.exe
  • CerMgr.exe
  • SignCode.exe
  • Signer.dll
  • CPrmEdit.exe
  • CPrmEdit.txt
  • javazone.hlp
  • PIniEdit.exe
  • PIniEdit.txt

    • 3. SDK Sample Files

    Please refer to the terms and conditions defined by the SDK license agreement under 1(d) Sample Code when redistributing the following files under the \Sample directory and its subdirectories:

  • \ActiveXBeans
  • \AFC
  • \CAB
  • \i18n
  • \CTOJParser
  • \CustDoc
  • \DirecX3
  • \Invocation
  • \JDBC
  • \JDirect
  • \Debugger
  • \Scripting
  • \JExegen
  • \JView
  • \Native
  • \Native_com
  • \Native_raw
  • \Script Debugger
  • \Security
  • \PkgMgmt
  • \xmldso

    • 4. SDK Documentation

    SDK_Docs.exe can be redistributed with the Microsoft VM and SDK components redistribution.

    5. Microsoft Application Foundation Classes (AFC)

    The JDK 1.1 compatible AFC class libraries are installed by default with the latest Microsoft VM for Java.

    The JDK 1.0.2-compatible AFC files that follow are redistributable together under the terms of the SDK License Agreement:

  • afc102.zip
  • afcsetup.exe
  • all samples under \AFC102\Samples

    • AFC102.zip is the zip file that contains JDK 1.0.2-compatible AFC components (Application Fundation Classes). This file can be downloaded from the AFC web site or downloaded with the core SDK 2.5. afcsetup.exe is the setup program used to install the AFC packages on various platforms (please refer to the AFC release notes). All files can be redistributed according to the SDK license terms under AFC. These files are located in the SDK installation directory (C:\sdk-java.20\AFC102).

    6. DirectX® File

    DirectX.exe is the self extracting executable that includes the DirectX3a runtime. It can be downloaded from the SDK web site, and can be redistributed with the Microsoft virtual machine which includes DirectX for Java package in the system class library. To obtain the above file, please choose the Download (or Install and Download) option via SDK Setup Wizard, and the file will be copied into the chosen SDK download directory or the default directory C:\sdk-java.20\Components.

    7. DirectAnimation™ Package, Runtime, Samples and Runtime

    Dxmedia.exe is the self extracting executable that provides DirectAnimation runtime, which also comes with Internet Explorer 4.0. Dajavcls.cab is the CAB file that contains the Java package to be used with the DirectAnimation runtime. These can be downloaded from the SDK web site, and can be redistributed with the Microsoft VM. To obtain the above files, please choose the Download (or Install and Download) option via SDK Setup Wizard, and the files will be copied into the chosen SDK download directory or the default directory C:\sdk-java.20\Components.

    8. General Redistribution Information

    Version Checking of Redistributable Files

    Please make sure that you provide the correct version checking in your setup program for any redistributed file that may be updated, including the VM for Java. To manually verify the VM for Java version that you are running, check the version of msjava.dll under your \windows\system directory. This release of the VM should be 2339; it is the version that is included with the Microsoft SDK for Java 2.5 and Internet Explorer 4.0.


Release Notes Win32 Virtual Machine

In this topic

Release Notes | Release Notes
Win32® Virtual Machine | Introduction

Microsoft Win32® Virtual Machine for Java

The Microsoft VM for Java (build 2339) ships with the retail version of the Internet Explorer 4.01. This release of the SDK for Java provides this VM in a stand-alone form, to be installed on the retail version of the Internet Explorer 3.02 (or later). It supports the following:

  • Enhanced JIT performance and reduced working set requirements

  • Enhanced interpreter loop performance

  • JDK 1.1 Support

    The Microsoft Virtual Machine for Java supports a number of JDK 1.1 defined enhancements, including Serialization, Reflection and Inner classes.

  • Java and COM

    The SafeArray class now has public methods to access array data.

    COM custom marshalling provides better control of how data is passed in and out of the virtual machine.

  • ActiveX and Java Beans Support

    Any Bean is exposed as an ActiveX control and any ActiveX control is exposed as a Bean.

    Auto-IDispatch now uses introspection to expose the necessary public classes and variables.

    ITypeInfo is provided on a class automatically and a type library can be persisted for a class.

    Event sourcing and sinking is supported.

  • Package Management Features

    The Java Language Package Manager is used by the VM to efficiently organize Java packages. For more information on this feature, please read the SDK documentation on Package Management.

    The current method of installing and using Java packages consists of storing all the classes in a zip file and then appending this file to the CLASSPATH registry key. When the VM needs a class, it searches each CLASSPATH entry. The CLASSPATH can become filled with references to packages that are old or unused, or different versions of the same package. It is also difficult to know which packages are needed and which are not. To address these and other concerns, the Java Language Package Manager is used to organize Java packages. The Java Package Manager offers:

    • Version Control. Package version numbers are tracked, allowing Java programs and installers to intelligently update the system.
    • Namespaces. Entire applets and applications can be installed in namespaces to avoid conflicting with identically named packages and classes from other vendors.
    • Improved Security. Instead of having to fully trust all installed classes, the package manager stores the allowed permissions of each package, as verified by Authenticode.
    • Signing. Through Authenticode signing, the package manager can ensure that only the vendor that installed a package can update it.
    • ActiveX Bean Support. ActiveX Beans in Java packages can be automatically registered by the package manager.
    • Ease of Use. Web pages can install packages without having to alter the CLASSPATH or require a reboot.

    When a Java package is installed in the Package Manager, the original archive file is removed and the classes are stored internally. Thus, developers need to use the clspack command (described in the tools section) to generate the ZIP files used by Java compilers. All of the standard Java packages shipped with this version of the VM are installed in the Package Manager, including the AFC classes.


Release Notes J/Direct

In this topic

Release Notes | Release Notes
J/Direct | Introduction

J/Direct Information

Microsoft® J/Direct™ is a very powerful mechanism that allows Java code to call functions exported from any Windows DLLs. The code in the DLLs need not be aware of the Java environment. The most obvious use of this scheme is to call Win32 APIs or APIs in third party DLLs. This mechanism automatically translates common data types, such as strings and structures to forms typically expected by C functions. This dramatically reduces any glue code or wrapper DLLs that need to be written. In short J/Direct exposes the richness of the Windows platform to the Java programmer. It also makes calling functions in DLLs as simple as possible.

Any class that uses J/Direct calls requires permissions for maximum trust from the system. This is best explained by looking at the various scenarios:

  • An applet can use J/Direct calls only if it is signed and has "fully trusted" permissions.
  • An untrusted applet cannot resolve to a class that uses J/Direct calls, unless that class has been appropriately marked as a class that can protect itself from malicious use. Please see the "Security Issues" section of the "About J/Direct" article for more information on how to mark your class as safe for use from an untrusted applet.
  • A class on the CLASSPATH, or a package managed class with the "fully trusted" permission, can be a wrapper class that protects another class that uses J/Direct calls from malicious use. Such a wrapper or proxy class can be called from an applet.

A J/Direct call should be treated as a native call. Do not expose access to J/Direct functionality any more freely than access to native code. Security checks should be made through the security manager when exposing J/Direct functionally to untrusted code.

Please refer to the articles "Mixing Java and Native Code" and "About J/Direct" in the SDK for Java documentation for more information.

Win32 API Classes for J/Direct

The Win32 API Classes for J/Direct (the com.ms.win32.* package) provide direct, low-overhead access to commonly used Windows APIs. These classes use the new J/Direct feature and therefore require either Internet Explorer 4.0, or the Microsoft SDK for Java 2.0.

The Win32 API Classes for J/Direct are an optional component in the SDK install. When these classes are installed the com.ms.win32 package is copied into the %windir%\java\classes directory. The sources (.java files) for these classes are also provided as part of the Microsoft SDK for Java 2.0.

If your application requires an api not covered in these classes, J/Direct makes it very easy to write declarations on your own. Complete documentation and samples on using J/Direct can be found in the Microsoft SDK for Java 2.0.

Packages included in this CAB:

com.ms.win32 J/Direct declarations for common Win32 APIs and constants

Classes included in this CAB:

The classes included in com.ms.win32 package fall into three main categories:

Constants

The win class contains the numeric constants used in Win32. For example, the system path length limit (MAX_PATH) can be accessed from Java as follows:

import com.ms.win32.*;

System.out.println("MAX_PATH = " + win.MAX_PATH);

Performance tip:

Do not include the win class in the extends or implements clause of your application's classes. This trick is commonly used to avoid having to type the class name in front of each constant usage. The price for this convenience is that the win class will need to be loaded at runtime, which can significantly impact application start up time. To avoid this overhead, use the qualified name for each constant reference. The Microsoft compiler for Java will inline constant references and will not create a runtime dependency on the win class.

Functions

The Win32 APIs are divided into classes according to the DLL they are exported from.

Kernel32.java | KERNEL32.DLL | (base API)
Gdi32.java | GDI32.DLL | (graphics)
User32.java | USER32.DLL | (user interface)
Advapi32.java | ADVAPI32.DLL | (crypto API, event logging)
Shell32.java | SHELL32.DLL | (interface to the Windows Explorer)
Winmm.java | WINMM.DLL | (multimedia)
Spoolss.java | SPOOLSS.DLL | (spooling)

Structures

Win32 structures are represented by Java classes that bear the same name as the structure.

Known Issues

If the Win32 API classes for J/Direct were installed as part of the SDK for Java 2.0, they would reside in %windir%\java\classes\com\ms\win32. The SDK setup does not delete these older classes. Please feel free to delete them with a command of the form:

    c:
    cd %windir%\java\classes
    deltree com


Security Model

In this topic

Release Notes | Release Notes
Security Model | Introduction

The previous version of the Microsoft VM (shipped in Internet Explorer 3.02) allowed signed code to be treated as trusted. Essentially, classes were placed in a cab file and signed. When downloaded onto the user's machine, the user was presented with a certificate dialog specifying the publisher of the code and other information. If the user granted permission to the trusted code, the code was allowed access to system resources.

The permissions-based security model in Internet Explorer 4.0 extends this security model by providing a granular approach to allowing applets out of the "sandbox." The Java code may be signed with default permissions of High, Medium and Low safety settings.

In addition to the default settings of High, Medium, and Low, developers may sign their code with a fine-grained set of custom permissions by specifying them in a .ini file. For example, developers may sign their code requesting permission to access only a particular file on the user's hard drive.

The High safety setting is a restrictive set of permissions that are the equivalent of "sandboxed" Java code. This set of permissions enables the applet to:

  • Have thread access in the current execution context.
  • Create a top-level popup Window with a warning banner.
  • Access Reflection API’s for classes from the same loader.
  • Read system properties with the applet suffix.
  • Open network connections to the host machine.

The Medium safety setting consists of the following set of permissions (in addition to the permissions in the High setting):

  • Scratch Space
  • User Directed File I/O

The Low safety setting enables all permissions (in addition to the permissions in the High and Medium settings). This enables the applet to:

  • Execute other applications on the client.
  • Perform file I/O.
  • Perform multimedia operations.
  • Open network connections to machines other than the host.
  • Perform printing operations.
  • Read system properties.
  • Access Reflection API's.
  • Perform registry operations.
  • Redirect system streams.
  • Provide thread group access in the current execution context.
  • Create a top-level popup window without a warning banner.
  • Implement user-interface dialogs.

Signing Tools

Tools for signing code are available in the BIN\PACKSIGN directory of this release of the SDK for Java. These tools provide developers the capability to sign their Java code with the default settings and with the fine-grained custom permission settings.

The general-purpose signing tools MakeCert.exe, Cert2SPC.exe, signcode.exe, ChkTrust.exe, setreg.exe, and CertMgr.exe are included in this release of the SDK for Java. The Java specific tools JavaSign.dll and ChkJava.exe are also included.

Two new tools have been added to the Microsoft SDK for Java v2.01. These are the Permission Editor (cprmedit.exe) and the Permission INI File Editor (piniedit).

The Permission Editor (CPrmEdit.exe) tool allows users to edit Java permissions for specific security zones using a graphical user interface. The user interface presented by the cprmedit tool is similar to the dialog boxes in Internet Explorer 4.01 that allow administrators to set security options. These options are normally allowed only in the Internet Explorer Administrators Kit (IEAK) or by running the zonedon.reg file. The Permission Editor allows power users and advanced java users to set their own fine grained Java permission settings.

The Permission INI File Editor tool(PIniEdit.exe) provides a quick way to create .ini files that are used with the signcode tool. The signcode tool uses .ini files to provide descriptions of the permission settings that Java applets need. Using an .ini file with the signcode tool allows you to digitally sign your applet with the permissions encoded within the digital signature. The other way to create .ini files requires manually creating the file and setting the value of each variable in the file. The Permission INI File Editor creates and edits .ini files quickly and easily by allowing you to specify the permissions using a graphical user interface.

For a short description of these tools, please see the Tools topic. For more detailed instructions on using the tools, see the SDK documentation.

To get more information on working with the Microsoft VM, please check out the SDK documentation on this subject.


Known Issues for the Microsoft Virtual Machine

In this topic

Release Notes | Release Notes
Known Issues | Introduction

Known Issues for the Microsoft VM for Java

  • This release of the Microsoft VM strictly enforces the following requirement: for a class to access methods of a class in another package, the second class must be declared public. Previous releases did not enforce this requirement. Hence some applets that worked before may display errors with the new virtual machine. It is advisable to make the packages conform to this Java requirement.

  • For ActiveX-Beans integration, certain functionality (such as persistence and OC96 windowless support) is not yet present. The ActiveX control hosting does not support all ambient properties. Code download will be provided in future releases.

  • VM uninstall option is provided in this release. Be aware of the following issues:

    If you want use the VM uninstall option, go to Control Panel, Add/Remove Software and uninstall the VM. If you uninstall the VM yet still plan to use Internet Explorer 4.0, this may cause potential problems with the downloading ability of the browser.

    Internet Explorer 4.0 uninstall includes an option to remove the Microsoft VM for Java. If you uninstall Internet Explorer 4.0 yet plan to use the VM and the SDK, the VM may not function properly. You must reinstall the stand-alone VM, by using the "Download" or the "Install and Download" option offered by SDKsetup.exe (the SDK download wizard). You can obtain the stand alone VM (msjavx86.exe) from the download directory you define or use the default directory C:\SDK-Java.20\Components. You can then double click on the msjavx86.exe to reinstall the VM at any time.

  • Using package-managed classes with existing tools:

    A tool called clspack creates all the ZIP files that are usually included in %WINDIR%\Java\Classes, and are now stored in the package manager. It is provided in the SDK\bin directory. You can use it by setting the path to the SDK\bin (set path=c:\sdk-java.20\bin;%path%) or copying it into %windir% directory.

    In addition, the value of the CLASSPATH registry setting is prepended with a reference to this generated classes.zip file (if one is not currently there). The compiler provided with the SDK (jvc.exe) checks this location by default for classes, so there is no need to set the CLASSPATH environment variable.

    For other compilers that do not check this location by default, set the CLASSPATH environment variable with:

    set CLASSPATH=%WINDIR%\Java\Classes\Classes.zip

    before running the compiler. It's a good idea to place this command in a batch file for easy use.

  • Raw Native Interface Enhancements:

    The Raw Native Interface (RNI) has been extended as a result of feedback and performance enhancements. The enhancements made to RNI are in four primary areas:

  • Additional APIs to enable reflection from native code
  • Changes to support future garbage collection performance enhancements
  • RNIGetCompatibleVersion requirement for RNI DLLs
  • RNI invocation APIs

For a more detailed description of the new and updated APIs, see the SDK documentation.

  • Any class calling the ActiveXControl class needs to be trusted. If an applet intends to host an ActiveX Control using the ActiveXControl class, it needs to be signed with the "fully trusted" permission. Any class calling the ActiveXControl class needs to be on the CLASSPATH or have the right permissions ascribed to it through package management. If the jactivex tool is used to host an ActiveX Control, the classes output by the tool end up using the ActiveXControl class. So any code using the classes output by jactivex needs to be trusted.
  • Some of the XML Data Source Object (DSO) functionality requires Internet Explorer version 4.0 or higher.
  • The following components of the XML specification have not yet been implemented:
    • Conditional sections in the DTD (INCLUDE & IGNORE keywords).
    • Some aspects of character encoding.
    For more information and an updated version of the Microsoft® XML parser please refer to the XML website.


Release Notes Class libraries

In this topic

Release Notes | Release Notes
Class libraries | Introduction

The Microsoft SDK for Java provides a rich set of class libraries. Please read the SDK documents related to Package Management and the SDK Tools documentation on DUBuild and Signcode. For converting AWT-based source code to use AFC, please read the documentation provided in the \bin\awt2afc directory.

Most new JDK 1.1 classes - java.net.* enhancements are integrated into this release.

AWT

We have completely reimplemented AWT for the Win32 platform. During this process we have removed AWT's dependency on the Microsoft Foundation Classes (MFC), and worked to eliminate overhead, bugs and performance problems. ActiveX Controls can now also be hosted as JavaBeans.

Application Foundation Classes (AFC)

  • com.ms.ui: A rich suite of UI controls, written in Java. UI controls will run in a number of popular browsers.
  • com.ms.fx: A suite of classes for graphics and effects, written in Java. Fx classes will run in a number of popular browsers.
  • Active Accessibility for Java: a compact suite of standard interfaces that gives Java developers access to accessibility aids for the disabled where appropriate platform services exist.
  • CAB: A suite of Java APIs for creating and extracting cabinet files on any virtual machine.
  • An updated list of class name changes is provided on http://www.microsoft.com/java/afc.
  • AFC is written in Java and is both JDK 1.1 and 1.0.2-compatible. This SDK contains JDK 1.1-compatible AFC and a JDK 1.0.2-compatible, redistributable version of AFC, along with samples, release notes, and additional documents.

Win32 API Classes for J/Direct

The Win32 API Classes for Microsoft® J/Direct™ provide access to core Win32 API using the J/Direct technology. For more information on J/Direct and the Win32 API classes for J/Direct, please see the J/Direct release notes.

JDBC

The JDBC-ODBC bridge is part of the core set of classes shipped with the Microsoft VM for Java. Please see the JDBC release notes for more information.

DirectX 3 for Java

Included are Java classes for the following DirectX multimedia APIs:

  • DirectDraw(r) - provides 2-D graphics services and bitmap composition.
  • Direct3D(tm) Retained Mode and Immediate Mode - high and low-level 3D graphics APIs, providing comprehensive 3-D graphics services.
  • DirectSound(r) - provides sound-mixing and playback services.
  • DirectPlay(r) - provides multiplayer game connectivity over the Internet.
  • DirectInput(tm) - provides services for joysticks and other input devices.

Please see DirectX3 release notes for known issues and further information.

DirectAnimation

DirectAnimation is a new Java API that enables different types of multimedia content to be tightly integrated and deployed, associating the media pieces with a timeline and user events. See the DirectAnimation release notes for further information.

Java Internationalization Support

Unicode

Unlike most other virtual machines, Unicode support was implemented correctly in previous releases of the Microsoft VM and SDK. getLocalizedInput and getOutputStream calls are still valid. All UI methods and paths are Unicode-enabled. Due to size of the JDK1.1 Unicode code pages (over 4 megabytes), only the Windows local code pages data (classes) have been included for this release.

Resource format

AFC includes a set of resource decoder classes that enable users to load Win32 resources. These resources are used to:

  • Leverage existing Win32 resources in Java in a cross-platform manner.
  • Allow easy, safe business application non-compile localization.
  • Offer a solution for software gloablization on the web without reinventing the internationalization process.
  • Support multilingual resource handling for Java development using existing Win32 programming tools.

The Win32 Resource Loading sample in the \Samples\AFC\Win32ResSupport directory of the SDK for Java demonstrates the use of the supported Win32 resource styles and controls included with the com.ms.ui.resource.Win32ResourceDecoder class.

Note that in that directory, the Sample.html file that describes this sample mentions that you can see an example of how to merge files by looking at the merge.bat file. This file is not present in the SDK. However, merge.bat only contains the following single line, which shows using the resmerge utility:

resmerge strtable.res strtable_en.res strtable_ja.res strtable_de.res

Multilingual Input Method APIs

Java IME support is provided for use with Java applications and applets written for Chinese, Japanese and Korean users. APIs and sample code are included in the SDK to allow developers to:

  • Create pure Java IMEs with self-defined UI.
  • Enable a Java applet or application to access any system IMEs as a Java IME on any Chinese/Japanese/Korean (CJK) systems. Please note, you should switch system IME to direct input mode or disable your system IME before you use Java IMEs.

Multilingual VM

Microsoft provides the first multilingual VM on the market today, including 26 languages for both runtime messages and system class library resources, to meet the global demand. Dialogs, strings and other resources are loaded and displayed based on the default system locale, using system default fonts.

Vertical Writing Support

Vertical writing is supported as part of the continuing effort to meet the special requirements of international developers and web publishers. For those who like to use vertical writing for text displays, Microsoft AFC includes vertical writing APIs that can be used in Java applet/application development. This feature enhances programming for CJK languages that uses vertical writing in text, in addition to all degree text rotation features in AFC.

To use the classes that come with the VM with a command line utilities such as the Microsoft compiler (jvc.exe), please run the clspack.exe utility with the -auto option in the SDK\bin directory to generate a single classes.zip on the classpath.


DirectX 3 for Java

In this topic

Release Notes | Release Notes
DirectX 3 for Java | Introduction

Untitled Normal Page

Introduction

Welcome to the Microsoft® DirectX™ 3 for Java class libraries. DirectX 3 for Java contains Java classes for the following DirectX multimedia APIs:

  • DirectDraw® - provides 2-D graphics services and bitmap composition.
  • Direct3D® Retained Mode and Immediate Mode - high and low-level 3D graphics APIs that provide comprehensive 3D graphics services.
  • DirectSound® - provides sound-mixing and playback services.
  • DirectPlay® - provides multiplayer game connectivity over the Internet.
  • DirectInput® - provides services for joysticks and other input devices.
For further information about the DirectX multimedia APIs, see http://www.microsoft.com/directx/.

Redistribution Components

Please refer to redist.htm and the license for redistribution of the DirectX 3 runtime. The DirectX 3 for Java package is part of the retail system class library that ships with the Microsoft VM for Java.

Please read the license agreement before using the SDK. You can submit comments using the public forum news:msnews.microsoft.com/microsoft.public.java.sdk or news:msnews.microsoft.com/microsoft.public.java.directxj. Please send bug reports with repro steps following the instructions included in the support section of the main release note.

Runtime Installation:

The DirectX 3a run time can be downloaded from the Web by running the SDK sdksetup.exe. You will need to install the DirectX 3a runtime of DirectX to use DirectX 3 for Java class libraries, view the samples, and so on. The DirectX 3a runtime is also required if you run any of the DirectAnimation samples.

If you are using Microsoft Internet Explorer 4.0, you already have some DirectX runtime components installed on your machine. Internet Explorer 4.0 contains the DDrawEx and DirectX subset run-time components, which are the most widely used elements of DirectX. Note that these components do not include DirectPlay, DirectInput or support for ramp (256-color palettized mode) in Direct3D, and therefore, unless the full DirectX 3a runtime (or a later DirectX runtime) is installed as described previously, you will not be able to run the corresponding elements of DirectX 3 for Java.

Known Issues

  • Windows NT: DirectX 3 for Java depends on the DirectX 3a runtime. Some elements of DirectX 3a (for example, DirectSound) work on Windows NT in emulation only. Direct3D, which will also remain in emulation only until Windows NT 5.0, must be downloaded separately from the runtimes included here if needed for Windows NT. Direct3D for Windows NT is available with the Windows NT 4.0 Service Pack 3 (SP3), which can be found at http://www.microsoft.com/msdownload/.
  • Rasterizers: When using the default Dxmini runtimes included with the Internet Explorer 4.0 minimum install, rather than installing the DirectX 3a runtime included with the SDK, you will only be able to use RGB (true color) software rasterizers, as Dxmini supports RGB rendering modes only. It does not support ramp (256 palettized) rendering modes. To take advantage of DirectX 3 for Java's ramp mode rasterizers, please install the full DirectX 3a or later runtime as described previously.
  • Palettes: (Only relevant to 8-bit mode) - DirectX 3 for Java reflects exactly the palette management techniques employed by DirectX itself. This means that, unless care is taken to reflect the system palette when running in a windowed browser in 8-bit mode, palette artifacts will be seen. All the DirectX 3 for Java graphics samples included in the SDK have been created to demonstrate how to effectively use the system palette and avoid these problems.
  • Object Management: DirectX's reference counting requires that developers specifically release some high-level 'master' objects (for example, Direct3DDevice) before an applet or application is terminated. This is due to an ordering dependency where high-level DirectX "master" objects automatically destroy their children. While DirectX 3 for Java does not require you to release these objects, you may wish to do so to be entirely confident that all object have been released when terminating the application. All the DirectX samples included in this SDK demonstrate how to free the appropriate high level object before terminating the application or applet.
  • Specific Hardware: The ATI Rage++ OEM driver, shipped with new Gateway Pentium IIs, fails on most DirectX applications. The fix is to install the latest ATI Rage drivers from the ATI web site, http://www.atitech.com/.
  • Direct3D Immediate Mode: The Direct3D for Java Immediate Mode ramp driver does not work in 8-bit mode with a z-buffer; it works with a z-buffer on the newer DirectX 5 runtime, available from http://www.microsoft.com/directx. The workaround is to stay in 16-bit mode.

© 1998 Microsoft Corporation. All rights reserved. Terms of use. cpyright.htm


Overview Articles

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Articles | Welcome!
 | Welcome!

Overview Articles

Using Features of the Microsoft Virtual Machine for Java

The Microsoft® Virtual Machine for Java (Microsoft VM) allows code written in Java to access native code written for the Win32® platform. This includes support for ActiveX/JavaBeans integration, Microsoft® J/Direct™ technologies for calling dynamic-link libraries, and the lower-level support for the Raw Native Interface (RNI) and accessing COM interfaces directly. Also, the Microsoft VM supports Internationalization classes and special Java applet scripting capabilities. The following articles discuss these concepts and explain how to use them.

  • Mixing Java and Native Code
  • About J/Direct
  • Low-Level Java/COM Integration
  • Using Jactivex to Create a User-Defined Type for Java/COM Marshaling
  • Native Code Interface Specification
  • Controlling an Applet Using Scripting
  • Internationalization
  • Trust-Based Security for Java
  • Java Package Management and Code Download

Microsoft Application Foundation Classes (AFC)

The AFC class library provides cross-platform support for user-interface controls, graphics calls, and other features. These classes are written completely in Java. The following articles describe how to use the AFC packages and classes.

  • Introduction to AFC
  • Overview of AFC User Interface Controls
  • Using Static, Button, Menu, and Choice Controls
  • The com.ms.fx Package


Mixing Java and Native Code

Controlling an Applet Using Scripting
In this topic

* J/Direct

* ActiveX/Beans Integration

* Raw Native Interface

* Low-Level Java/COM Integration

* Summary

Articles | Welcome!
Mixing Java and Native Code | Welcome!

Mixing Java and Native Code

Java is a powerful and sophisticated language that is taking its place alongside other widely used software development languages. Because few developers have the time to rewrite much of the useful code available in libraries written in other languages, it makes sense to understand how Java can access this code. Like any other programming language, Java embodies a set of tradeoffs, making it a good solution for some problems and a poor solution for others. The ability to mix and match code written in different languages lets developers achieve the maximum benefit from the tools at their disposal.

There are many scenarios that require Java code to call code that is written in some other language. For example, a Java developer may want to do any of the following:

  • Provide efficient algorithms where performance is an issue.
  • Take advantage of the hardware present on the host computer.
  • Take advantage of the full richness of the operating environment on the host computer.
  • Utilize the rich set of components available through other component technologies, such as COM (Component Object Model) that underlies Microsoft® ActiveX®.

Almost all class libraries, including the ones from JavaSoft's JDK, call code written in other languages to exploit some of these scenarios.

In the context of Java, any code that is not written in Java is called native code. This document does not dwell on the pros and cons of using native code versus Java code. Rather, it attempts to give the spectrum of options available to a Java programmer who wants to call native code from Java for any number of reasons.

The Microsoft Win32 VM for Java (Microsoft VM) provides many ways for Java code to call native code, as shown in the following list:

  • J/Direct, which is used primarily to call into existing dynamic-link libraries (DLLs), including the entire set of Win32 API.
  • ActiveX/Beans Integration, which automatically exposes JavaBeans components as ActiveX controls and allows ActiveX controls to be hosted as JavaBeans components. This integration is seamless and bidirectional.
  • Raw Native Interface, which allows the most efficient interaction between native code and Java code, but imposes programming requirements on the native code.
  • Low-Level Java/COM Integration, which provides Java access to dual-interface COM objects and provides access to custom marshaling of user data types between the object and Java using vtable access.

The remainder of this document discusses these interfaces between Java and native code in more detail.

J/Direct

Microsoft® J/Direct™ is a powerful mechanism that enables Java code to call application programming interfaces (APIs) in DLLs in the most straightforward manner possible. The code in DLLs called through J/Direct has no additional interfacing responsibility imposed on it, which makes J/Direct an excellent vehicle for calling previously developed native code. (The RNI or JNI programmer typically must write wrapper DLLs around existing native code to interface between the Java environment and the native code.)

The most obvious use of J/Direct is to call Win32 APIs or APIs in third-party Dynamic-link libraries. The Microsoft VM automatically translates common Java data types to those expected by C functions. Compared to RNI, J/Direct dramatically reduces the amount of extra code and the number of wrapper Dynamic-link libraries that would need to be written.

J/Direct is best illustrated with an example, as follows:

class ShowMsgBox
{
  public static void main(String args[])
  {
     MessageBox(0, "Hello World!", "Message box using Win32 API from Java", 0);
  }

  /** @dll.import("USER32") */
  private static native int MessageBox(int hwnd, String text, String title, int fuStyle);
}

If you know both Java and Microsoft® Windows® programming, the only line that might be new is:

/** @dll.import("USER32") */

In the example, this line is a directive to the compiler to link MessageBox to the Win32 API in USER32.DLL using the J/Direct protocol. The Microsoft VM provides the necessary support to make this happen. For example, the String Java class is marshaled into a null-terminated string, expected by the C language calling convention for a string. The support provided by the Microsoft VM makes it possible to call more than 95 percent of the Win32 API functions in a simple manner, similar to the previous example. Helper classes, source code, and samples provided as part of the Microsoft SDK for Java will help Java programmers who want to exploit the richness of the Win32 platform from their Java applications.

For a detailed description of how to use J/Direct, see About J/Direct. Also, see the J/Direct samples that are available in the SDK for Java.

ActiveX/Beans Integration

JavaBeans provides the component model for Java. JavaBeans, while still in its infancy, is gaining popularity with Java developers. It is likely there will be a variety of JavaBeans components in the marketplace in the near future. ActiveX is a language-neutral component model that uses COM as its base. In terms of the marketplace, ActiveX is a much more mature component model, supported by a whole set of power tools, such as Microsoft® Visual Basic®, Microsoft® Visual C++®, Borland Delphi, and Powersoft PowerBuilder, as well as thousands of commercially available ActiveX components. The integration of ActiveX and Beans provided by the Microsoft VM enables a Java programmer to take advantage of the vast array of rich ActiveX controls available. Similarly, ActiveX control programmers can make use of compelling JavaBeans components as they begin to appear in the marketplace.

The integration provided by the Microsoft VM is such that an ActiveX control appears as just another Bean to the Java programmer. Likewise, the JavaBeans component appears as just another ActiveX control to the ActiveX control programmer or control container. This enables programmers to work in the environment they are most familiar with, while exploiting the richness of the available components and controls on the platform, no matter what language was used to develop the control or component.

Thus, the two main features of the integration provided by the Microsoft VM enable a programmer to:

  • Host a Bean in an ActiveX container.
  • Host an ActiveX control in Java.

The following sections describe how a developer can utilize the Microsoft VM and SDK tools to accomplish these objectives.

Hosting a Bean in an ActiveX Container

In JavaBeans architecture, a Bean is a reusable Java component, which is usually meant to be used in the context of other Beans or components in some container. The Microsoft VM provides the bridge necessary to host a Bean in an ActiveX container. The ActiveX container cannot differentiate the Bean from an ActiveX control; it treats it like any other ActiveX control. So, for example, Microsoft® Visual Basic® 5.0 can use the Bean exactly as it would use a control.

Hosting a Bean in an ActiveX container is essentially a two-step process: write the Bean and run a tool called javareg. The following example shows a typical javareg command line registering a Bean called JChart:

javareg /register /control /class:JChart /codebase:.
/clsid:{177cf4a0-e7e0-11d0-b8e7-0000f81ecce7} /typelib:JChart.tlb

The javareg tool introspects the JavaBeans component to gather information about its properties, events, and methods, and then outputs this information in the form of a type library. A type library is the file that an ActiveX container uses to find information about an ActiveX control. The tool also registers the Bean, which allows an ActiveX container to find the Bean, like it would any other ActiveX control.

For more information about the javareg tool, see Using Javareg. The Microsoft SDK for Java also provides samples of this technique that a developer will find useful.

After running javareg, the Bean can be hosted in any ActiveX container, appearing there as an ActiveX control. When the JavaBeans component is invoked as an ActiveX control, the Microsoft VM is loaded and makes the appropriate mapping between the methods, properties, and events of the JavaBeans and the interfaces, methods, properties, and events of the ActiveX control. Examples of some popular ActiveX containers include Visual Basic, Microsoft® Office, Borland Delphi, and Corel WordPerfect, among others.

It should be noted at this point that Microsoft® Internet Explorer is itself an ActiveX container, and when a JavaBeans component is wrapped as an ActiveX control by the VM in Internet Explorer, the component exposes the same COM interfaces as any ActiveX control in the browser. To enable this mode of use, however, you must use the OBJECT tag to load your Java applet. When you use the OBJECT tag, you do not need to run javareg. See Using the HTML 4.0 OBJECT Tag below for more information on using this tag.

Java Monikers

ActiveX containers, such as Visual Basic 5.0, are able to find a Bean through a "Java Moniker," which uses a URL syntax similar to the one used in the HTML OBJECT tag. So for example, in Visual Basic 5.0, you can use the command GetObject("java:java.util.Date") to create an instance of the Date object, and then invoke methods on it.

This is possible because DCOM introduced an extensible moniker namespace, so if you pass a string like "java:some.class" to MkParseDisplayName, OLE32 will load the Microsoft VM and let it provide the class moniker to bind to the object (it looks up "java" as a progid in the registry and gets the CLSID of a handler implemented by the VM).

Furthermore, ActiveX containers that host a Bean can find information about the Bean through a COM interface called ITypeInfo. This allows access to interfaces such as IDispatch and permits all the usual operations represented through ActiveX interfaces, such as calling QueryInterface, and so on.

To help illustrate how moniker binding works, here is an example C++ program that uses monikers to bind to a simple Java object called TestObject, whose source code follows this example:

TEST.CPP

#include <windows.h>
#include <olectl.h>
#include <stdio.h>

HRESULT BindToObject(LPOLESTR pwszDisplayName, REFIID riid, LPVOID *ppunk)
{
    HRESULT hr;
    IBindCtx *pbc;
    ULONG chEaten;
    IMoniker *pmk;

    *ppunk = NULL;

    hr = CreateBindCtx(0, &pbc);

    if (hr == S_OK) {

        hr = MkParseDisplayName(pbc, pwszDisplayName, &chEaten, &pmk);

        if (hr == S_OK) {
            hr = pmk->BindToObject(pbc, NULL, riid, ppunk);
            pmk->Release();
        }

        pbc->Release();
    }

    return hr;
}

void main(int argc, char *argv[])
{
    HRESULT hr;
    IUnknown *punk;

    hr = CoInitialize(NULL);

    if (hr == S_OK) {

        hr = BindToObject(L"java:TestObject", IID_IUnknown, (LPVOID *) &punk);

        if (hr == S_OK) {

            punk->Release();

        } else {
            printf("failed to bind to java object (hr=%08x)\n", hr);
        }

        CoUninitialize();
    }
}

TestObject.java

import java.io.*;
import java.net.*;
import com.ms.com.*;

public class TestObject
{
    public TestObject() {
        System.out.println("created java object!");
    }
}
Using the HTML 4.0 OBJECT Tag

If you want to treat the Bean as an ActiveX control in Internet Explorer 4.0, to gain access to COM interfaces on that object for example, you can skip the javareg process and just use the HTML 4.0 OBJECT tag (Internet Explorer 4.0 queries the object directly for its Typeinfo data rather than having to rely on the Typelib information generated by javareg).

The HTML 4.0 OBJECT tag specification is supported by the Microsoft VM in Internet Explorer 4.0 so that you can use the OBJECT tag instead of the APPLET tag to run Java applets from a local or remote codebase. For example, the following code fragment could be used to load the Java class myprogram.one from http://www.one.come/two/three/.

<OBJECT classid="java:myprogram.one">
        codebase="http://www.one.come/two/three/">
</OBJECT>

Note that the Microsoft VM only provides access to COM interfaces for Java classes loaded using the OBJECT tag. The APPLET tag is handled in a different manner internally. For more information on HTML 4.0 and the OBJECT tag, see http://www.w3.org/TR/WD-object.

Exposing JavaBeans Methods through IDispatch

By default, the Microsoft VM for Java uses JavaBeans introspection to enumerate the methods and properties that are exposed through IDispatch. Unless a Bean provides its own BeanInfo, all public methods are exposed, as well as properties discovered using standard design patterns (such as setText and getText).

Mapping JavaBeans Events to ActiveX

In addition to exposing event interfaces, ActiveX controls have the concept of a default, outgoing set of events. A control developer defines this default event set, which is often the only event source connected to by ActiveX containers. To provide the greatest flexibility to Java developers, the ActiveX control framework allows use of design patterns to define this default event interface.

Since the JavaBeans eventing model is sufficient for many eventing needs and maps well to the ActiveX IConnectionPointContainer model, Microsoft recommends that events be exposed using the JavaBeans eventing specification.

When an ActiveX component attempts to connect to the default event interface of an ActiveX control for Java, the Microsoft VM introspects that control and looks for event listener interfaces. Unless a Bean provides its own BeanInfo, all outgoing events are in the default event set. For example, a developer could define the following interfaces in Java to define its outgoing default event set.

interface mouseListener
{
    public void mouseEvent( int ButtonState, int x, int y );
}

interface buttonListener
{
    public void clickEvent( Object ButtonSource );
}

interface keyListener
{
    public void keyEvent( int shiftState, int key );
}

These interfaces define events that could be sourced from three different JavaBeans event connections in a Java control. The Microsoft VM will combine them into one interface that is exposed through ActiveX. Be aware that the methods in the interface freely define parameters that are not event objects. The JavaBeans specification states that this free-form method specification is fully supported, but not necessary. Microsoft encourages its use because it can improve performance in passing events in and out of Java.

To attach an event sink to the Java control, the Microsoft VM calls the addListener methods of the outgoing event sources and passes the instance of an object, which implements the appropriate interface.

Mapping JavaBeans Properties to ActiveX

Properties allow control developers to expose state variables that can be queried, set, and monitored by other controls or control containers. Again, the JavaBeans model provides a one-for-one mapping with ActiveX property concepts and change notifications. The Microsoft VM exposes ActiveX properties based on design patterns and BeanInfo information as detailed in the JavaBeans specification.

To source property change events (equivalent to ActiveX OnChanged events) a developer can simply support the JavaBeans addPropertyChangeListener and removePropertyChangeListener methods, which accept the propertyChangeListener interface as a parameter. Likewise, to source vetoable property change events (equivalent to OnRequestEdit events), a developer just supports addVetoableChangeListener and removeVetoableChangeListener methods, which accept the vetoableChangeListener interface as parameters. The Microsoft VM will automatically connect to these property change event sources and handle them appropriately. To ActiveX clients of the object, these events will map to IPropertySinkNotify and IPropertySinkNotify::OnRequestEdit.

Hosting an ActiveX Control in Java

ActiveX controls are Automation-enabled controls that support the IDispatch COM interface, which enables the control to be scripted. These controls can also be dropped into containers, such as Visual Basic.

Hosting an ActiveX control in Java is a four-step process:

  1. Develop or obtain an ActiveX control and its associated type library.
  2. Run a tool called jactivex on the ActiveX control or its type library.

    This tool will emit Java source code wrappers for the IDispatch interface implemented by the ActiveX control. The emitted Java code will include Bean-like code for adding and removing listeners for the events originating from the ActiveX control. Also, the tool produces code to appropriately manage the lifetime of the ActiveX control.

    The source code will contain compiler directive code, similar to that used by J/Direct, of the form:

/** @com */
  3. Compile this Java source code using a compiler, such as jvc, that can interpret the @com syntax. The compiler will add some attributes to the class file.
  4. Import these classes and use the ActiveX control like any other Bean in Java code. The Microsoft VM will use these attributes in the class file to expose the ActiveX control as a Bean to any Java code. The Microsoft VM provides the necessary bridge between the invoking Java code and the corresponding IDispatch interface in the ActiveX control. Note that this only works with virtual machines that understand these attributes.

    This is best illustrated with an example. The following sample uses the Microsoft Calendar ActiveX control that ships with Microsoft Office. Running the tool jactivex on the Calendar control produces Java source classes, which are then compiled into the calendar classes imported below. A Java programmer would use the control with code similar to the following:

import java.awt.*;
import com.ms.activex.*;
import calendar.*;  // Classes from JActiveX when run on Calendar control or typelib

public class UseCalendar extends Frame implements ActiveXControlListener
{
    Calendar c;
    public UseCalendar()
    {
        c = new Calendar();

        c.addActiveXControlListener(this);
        add(c);
    }

    // Implementation of ActiveXControlListener interface method(s)
    public void controlCreated(Object o);
    {
        if (o instanceof Calendar)
        {
            c.today();
        }
    }
}

Notice that the control is manipulated like any other Bean. The constructor code creates the Bean, registers a listener (in this case, one defined by the ActiveXControlListener interface), and then adds itself to the layout. The single method of the ActiveXControlListener interface is controlCreated. When the control is created, the Microsoft VM fires an event defined by the ActiveXControlListener interface and, if the ActiveX control supports events as this example does, the corresponding listener method on the Bean is called. The code necessary to sink the event to the corresponding listener is provided automatically by the Microsoft VM.

The result is that when the Calendar control is created, and the controlCreated method is called, which displays the month corresponding to the current date.

Raw Native Interface

The Raw Native Interface (RNI) is a high-performance interface supported by the Microsoft VM for Java. This interface is meant for "pedal-to-the-metal" kind of performance programming. It provides an efficient way of both traversing between Java and native code, and manipulating objects while in native code. The native code must be an active participant when running in or interfacing with a Java environment; it has certain responsibilities, which include following naming conventions, adapting to Java data representations, and dealing with the garbage collection process of the Java environment.

For example, if the native code is going to be in a long loop, the garbage collector should be called periodically. Similarly, if the code is going to block on user input or call a thread that will block, it should call the garbage collector around the code that can block. Furthermore, objects need to be protected by garbage collection frames when calling back into Java.

The required knowledge of garbage collection and other issues increases the complexity of programming using RNI for the benefit of increasing performance. For this reason, this interface should be used only in cases where high performance is needed and therefore justifies the extra effort.

For more information about using the raw native interface, see Introduction to Using the Raw Native Interface and see the samples in the Microsoft SDK for Java.

Low-Level Java/COM Integration

ActiveX objects can be implemented as dual-interface objects, meaning that they support both the IDispatch interface for automation and also vtable access to COM interface methods. Like C and C++, Java can access the vtable methods directly. When accessed this way, these objects do not have many of the restrictions as to the type of data they can pass and the type of interfaces they must support as do ActiveX controls that use automation. Also, some COM objects do not support IDispatch and can only be accessed through vtable methods.

The tool that enables this access is jactivex, the same tool used for hosting ActiveX controls as JavaBeans components, but using the -javatlb switch. Because this is a much lower-level approach than the ActiveX/Beans integration, and data types are less restricted, there may be additional steps involved. This is especially true if there are complex data types passed through the interfaces exposed by the COM object. In particular, custom marshaling techniques might have to be used to manipulate these data types. It should also be noted that this approach does not create a JavaBeans object from the COM object. Instead, it creates a class that exposes the methods in the COM interfaces as its own class methods and calls the COM object for implementation.

See the Using Jactivex to Create a User-Defined Type for Java/COM Marshaling article for more information on Custom Marshaling, the Low-Level Java/COM Integration article for an overview of Java/COM integration, and the Jactivex Reference for detailed information about the JactiveX tool. Also, see the samples in the SDK for Java. Samples pertaining to low-level COM integration can be found in subdirectories under the /MsVmJava/Samples/ directory in the SDK.

Summary

The Microsoft VM provides various ways to call non-Java code from Java. The programmer can choose the best way depending on the issue at hand. The approach taken can be one of the following:
J/Direct | Functionality that enables a Java programmer to call APIs in other DLLs (such as Win32 API). This exposes the full richness of the Win32 platform to the Java programmer. Details of interfacing the DLL with the Java environment are handled automatically.
ActiveX/JavaBeans integration | Automatic bidirectional support for ActiveX control and JavaBeans integration. An ActiveX control will appear as a Bean to a Java programmer. A Bean will appear as an ActiveX control to an ActiveX control programmer.
RNI | Powerful performance-driven interface where the programmer is aware of the Java environment. However, the programmer must be aware of garbage collection issues.
Low-level Java/COM integration | More sophisticated COM object manipulation, which might require techniques such as custom marshaling.

Most programmers will use the first two approaches listed above: J/Direct and ActiveX/JavaBeans integration. The support provided by the Microsoft VM is both broad and complete: broad, in that it covers most scenarios for accessing native code, and complete in that it provides full access to the immense feature set of native code on the Win32 platform.


Controlling an Applet Using Scripting
In this topic

* Controlling a Java Applet Through Scripting

* Firing Events from an Java Applet

Articles | Welcome!
Controlling an Applet Using Scripting | Welcome!

Controlling an Applet Using Scripting

Web developers can embed Microsoft® ActiveX® Controls into their Web pages and drive them using Microsoft® Visual Basic® Scripting Edition (VBScript). The Microsoft Win32 VM for Java (Microsoft VM) offers developers another option by making Java applets scriptable, too. When a Java applet is running in a browser, such as Microsoft® Internet Explorer, all the public methods and variables of the applet automatically become available to VBScript or any other language supporting the ActiveX scripting protocol.

Controlling a Java Applet Through Scripting

Consider the following fragment from a Java applet.

    class Buzzer extends Applet

    {

        public int pitch;

        public void buzz()

        {

            //Play a sound at the specified pitch.
            ...

        }

 ...

    }

To include this applet in your HTML page, use the <APPLET> tag, specifying the ID attribute. This enables you to refer to the applet from the scripting language, as shown in the following example:

    <APPLET CODE="Buzzer.class" ID=doorbell>

You can then define buttons that enable the user to control the applet, as shown in the following example.

    <INPUT TYPE=button VALUE="Higher" NAME="BtnHigher">

    <INPUT TYPE=button VALUE="Lower"  NAME="BtnLower">

    <INPUT TYPE=button VALUE="Play"   NAME="BtnPlay">

The NAME attribute lets you refer to each button from the scripting language.

In the scripting portion of your HTML page, you can define OnClick handlers for each button, making them manipulate the applet, as follows:

    <SCRIPT language = "VBScript">

    Sub BtnHigher_OnClick

        document.doorbell.pitch = 880

    End Sub

    Sub BtnLower_OnClick

        document.doorbell.pitch = 440

    End Sub

    Sub BtnPlay_OnClick

        document.doorbell.buzz

    End Sub

    </SCRIPT>

Now, when a user clicks a button on the Web page, the appropriate VBScript handler is invoked, which in turn manipulates the Java applet. Note that when the applet is referenced from VBScript, its name has the identifier document attached to it.

Using scripting, Java applets can be driven just like ActiveX controls. The script can read and write the public variables of the applet, as well as call its public methods (including passing parameters and reading return values). However, only classes derived from java.Applet class are directly accessible from the scripting language. If your Java applet includes other classes that you want to make available to the scripting language, you must define public methods in your Applet subclass that delegate to those classes.

You can also embed both Java applets and ActiveX controls in the same Web page and use VBScript handlers to connect them. For example, you can read values from an ActiveX control and pass them to a Java applet, or vice versa. You can even fire events from a Java applet. This automatic scripting capability is provided by the Microsoft VM for Java. As a result, your script code can manipulate Java applets developed with any tool, not just ones developed with Microsoft® Visual J++™.

Firing Events from an Java Applet

Applets in Internet Explorer 4.0 can fire events to scripts. To do so, use the <applet> tag and specify a <param name=FireScriptEvents value=True> tag, as shown in the following example.

A look at an example taken from the AFCBean sample in the SDK for Java may help to demonstrate how this works.

The AFCBean class in AFCBean.java contains a handleEvent method that fires an event called itemSelected.

    /**

     *  When a item is selected, an action is performed. The LIST_SELECT

     *  event is parsed and an event called itemSelected is fired.

     */

     public boolean handleEvent(Event e)

     {

        if ((e.target instanceof UIList) && (e.id == Event.LIST_SELECT))

        {

            AFCBeanListener listener[];

            synchronized (m_listeners)

            {

                listener = new AFCBeanListener[m_listeners.size()];

                m_listeners.copyInto(listener);

            }

            for (int i=0; i<listener.length; i++)

                listener[i].itemSelected(getSelectedItem());

        }

        return super.handleEvent(e);

    }

In the AFCBean.html file, the following <applet> tag declares that the applet can fire events that will be handled by the script.

    <applet code="AFCBean.class" name="AFCBean" width="300" height="300">

        <param name="FiresScriptEvents" value="true">

    </applet>

The following JavaScript then sinks the event.

<script language="JavaScript" for="AFCBean" event="itemSelected(s)">

    txtSelectedText.value = s;

</script>

Finally, the selected string is displayed in the table on the HTML page.

    <tr>

        <td>Sinks the event itemSelected and displays the string.</td>

        <td><input name="txtSelectedText"></td>

 </tr>

</e>

When the <object> tag is supported by the Microsoft VM, it will assume the JDK 1.1 event model, so the FireScriptEvents parameter will not be required when using this tag.

For more information about VBScript, see the VBScript Web site at http://www.microsoft.com/vbscript/ External Link (which is accessible using the Web Favorites command on the Help menu).


Trust-Based Security for Java

Overview

Trust-based security for Java is a cross-platform security model that provides fine-grained administration of the permissions granted to Java applets and libraries. This security system provides intermediate levels of trust so that Java applications can be given some additional permissions without being offered unlimited access to every permission in the system. The following features are provided.

  • Security Zones that allow related sites (such as all sites on a company intranet) to be administered as a group.
  • A Permission Model that integrates with security zones to provide parameterized control over what Java classes can do.
  • Permission Signing that allows a signed cabinet file to specify not only the identity of the signer but also the set of permissions being requested for the signed classes.
  • Permission Scoping that enables a developer who designs a trusted class to precisely limit the range of code for which a granted permission is enabled.
  • A Package Manager that allows classes to be installed with their permissions.
  • A User Interface that simplifies or eliminates the decisions that end users need to make.

Features of Trust-Based Security

Each of the features of the trust-based security system offers benefits to end users and to administrators. To further explain these benefits, the implementation of each feature is discussed in the following sections.

Security Zones

Security zones allow a system administrator to manage groups of sites using the same level of trust for a whole group. The idea is to be able to set nonrestrictive security options for trusted areas and, at the same time, set very safe (restrictive) security options elsewhere. Predefined zones exist for categories such as the Local Intranet and the Internet. Security zones relieve administrators from having to list every trusted applet and its permissions, and they help administrators avoid the risk of leaving too many detailed decisions up to end users.

There are five default security zones defined in the trust-based security for Java implementation in Internet Explorer 4.0. These zones correspond to the most commonly used types of sites.

  • My Computer

    This zone includes most classes stored on the local machine. Because this zone is completely trusted, few or no security restrictions apply.

  • Local Intranet

    This zone includes content that is known to be reliable (typically located inside the firewall or obtained using a secure sockets layer [SSL] connection).

  • Trusted Sites

    This zone includes responsible Internet sites that are allowed to run with increased permissions, but not with the powerful permissions allowed to the Intranet zone.

  • Internet

    This zone includes all other sites, including scratch and development areas inside the firewall, and untrusted parts of local drives. This zone would typically be set to the standard applet permissions.

  • Restricted Sites

    This zone includes potentially harmful sites to which severely restricted permissions apply. For these sites, you may want to define "sandboxes" that are even more restrictive than the standard Java sandbox.

Network administrators can configure three different sets of permissions for each zone. The set that a permission is placed in determines whether or not the user will be presented with a dialog box that shows requested permissions.

  • Permissions granted without user intervention.

    These permissions are granted to applets from the specified zone without querying the user. These permissions can be separately specified for signed and unsigned applets.

  • Permissions granted with user intervention.

    These permissions can be determined directly through a list of permissions to query the user about, in which case every permission not mentioned is assumed to be denied.

  • Permissions that are prohibited.

    These permissions are considered too dangerous to allow under any circumstances. They are automatically denied.

If an applet uses only permissions granted without user intervention to its zone, it will run without user intervention. If it uses any explicitly denied permissions, it will automatically be prevented from running. Otherwise, the user will be presented with a single dialog box listing all of the permissions being requested and their associated risk. The user can then make one decision about whether to trust the applet that has that set of permissions.

An applet that does not receive the additional permissions requested will still be permitted to run, but will be prevented from exercising those permissions by security exceptions. The applet can catch the security exceptions so that it can take alternate action, perhaps continuing to run with more limited functionality.

The administrator can define a set of permissions that is assigned to all unsigned classes and scripts. This set defines the permissions of unsigned applets.

The Permission Model

The permission model for trust-based security supports a useful set of parameterized and non-parameterized permissions that can be individually granted or denied for a particular zone by an administrator. To reduce the number of options that administrators must specify in common cases, the administrative user interface provides several "preset" permission sets that can be applied. These predefined permission sets, called High, Medium, and Low, represent the most restrictive to the least restrictive predefined set of permissions, respectively.

Permissions can only be defined by system libraries with the highest degree of trust. This solves the problem of having to administer a potentially unlimited set of permission requests with uncertain, application-defined meanings.

Defined Permissions

The following list describes each permission defined by the permission model and lists the parameters available for limiting each permission.

  • Client Storage Permission

    Determines whether applets can access scratch space. Parameters for this permission include the size of the scratch space and flags that indicate whether storage is exempt from global storage limits and whether roaming files can be created. For more information, see the ClientStoragePermission class.

  • Execution Permission

    Determines which programs can be executed on the client's machine. Parameters for this permission include a pattern that indicates which applications to include or exclude from the permission. For more information, see the ExecutionPermission class.

  • File I/O Permission

    Determines whether applets can perform file operations. Parameters include the type of access (read, write, or delete), the filename or a pattern that indicates a group of files, and a flag that specifies whether the operation is denied or allowed. For more information, see the FileIOPermission class.

  • Multimedia Permission

    Controls access to extended multimedia capability. This permission has no parameters. For more information, see the MultimediaPermission class.

  • Network I/O Permission

    Controls the ability to perform networking components for three types of network operations: connect, bind, and multicast. Parameters include the network operation type (connect, bind, or multicast), a flag that indicates allowing or denying the operation, a pattern that indicates which hosts or ports to include or exclude, Internet Protocol (IP) addresses, port ranges, and flags that indicate whether you can bind to a non-file:// URL codebase or to a file://URL codebase. For more information, see the NetIOPermission class.

  • Printing Permission

    Controls whether an applet is allowed to print. This permission has no parameters. For more information, see the PrintingPermission class.

  • Property Permission

    Controls the ability to access and manipulate the global system properties. Parameters include a flag that indicates whether access to all properties is turned on or off, a pattern that indicates which properties are included or excluded, and suffixes indicating properties that could be accessed under certain conditions. For more information, see the PropertyPermission class.

  • Reflection Permission

    Determines whether access to the java.lang.reflect API is permitted. Parameters include a loader type (same loader, different loader, system loader, all, or none) and an access type (public or declared). For more information, see the ReflectionPermission class.

  • Registry Permission

    Controls the ability to access the registry. Parameters include the type of access (read, write, open, delete, or create) and a pattern that indicates which keys/values are included or excluded from access. For more information, see the RegistryPermission class.

  • Security Permission

    Controls access to the java.lang.security package. This permission has no parameters. For more information, see the SecurityPermission class.

  • System Streams Permission

    Controls the ability to change the values of the system streams java.lang.System.in, java.lang.System.out, and java.lang.System.err. Parameters include flags that indicate whether System.in, System.out, and System.err can be set. For more information, see the SystemStreamsPermission class.

  • Thread Permission

    Controls the ability to create and manipulate threads and thread groups. Parameters include a thread or thread group object, a flag that indicates whether unrestricted thread access is allowed, and a flag that indicates whether unrestricted thread group access is allowed. For more information, see the ThreadPermission class.

  • User File I/O Permission

    Determines whether user-directed file I/O can be performed. Parameters for this permission include the access type (read or write) and a file name or a pattern that indicates which files to allow access to. For more information, see the UserFileIOPermission class.

  • User Interface Permission

    Controls the ability to create top level windows, access the system clipboard, create file dialog boxes, and access the AWT event queue. Parameters for this permission include flags that indicate access to one or more of the enhanced UI functions. For more information, see the UIPermission class.

Defining Applet Permissions

The following sets of permissions correspond to the standard Java sandbox.

  • Thread access in the current execution context.
  • Network connections to the applet host.
  • Creation of top-level windows with warning banners.
  • Reflection to classes from the same loader.
  • Access to base system properties.

You can choose these permissions or you can set up an even more restrictive set of permissions for applets. Choosing a less restrictive set is not recommended

Defining Custom Permissions

Internet service providers or personal users might want to define custom permissions. Permission objects can be defined to protect some functionality in your code against misuse. Custom permissions can be added to the digital signature so that the user can decide (via a dialog box) whether or not to accept the risk. To add custom permissions to the digital signature, you would specify the requested permissions in an .ini file that is used by the signcode tool when signing the cabinet file. For more information about using the permission .ini file with the signcode tool, see the Signing a Cabinet File with Java Permissions Using Signcode article and the Sample Permissions .INI File.

Permission Signing

Permission signing extends the signed cabinet file functionality provided by Microsoft® Internet Explorer 3.0. Under trust-based security, a signed cabinet file can securely specify not only the identity of the signer but also the set of permissions being requested for the signed classes. The security system can determine all of the permissions requested by a Java component by inspecting the digital signature. This information is used to present to the user a single dialog box that displays all of the relevant trust questions. The dialog box is presented before any code starts to run. In addition, because the set of permissions is fully defined and understood by the Microsoft Win32 VM for Java, the dialog box can accurately warn users about the risk of each requested permission. For more information on permission signing, see the article on Signing a Cabinet File with Java Permissions Using Signcode.

Permission Scoping

Permission scoping prevents permissions granted to a trusted component from being misused (either inadvertently or intentionally) by a less trusted component. A trusted class can precisely limit the range of code for which a granted permission is enabled. This is an important issue because some methods that use enhanced permissions are designed to be safely called by anyone, while other methods are designed to be used internally by trusted callers only and should not expose their permissions to less trusted callers.

Trust-based security distinguishes between permissions that have been granted to a class and permissions that are actually enabled at a particular time. The granted permissions are determined by the administrative options for a class's zone and by the permissions with which the class was signed. In contrast, enabled permissions are determined by the permissions granted to other callers on the call stack and by any calls that were made to the assertPermission, denyPermission, and revertPermission methods. If there are any less trusted callers on the call stack, the enabled permissions can be more restrictive than the granted permissions.

When the Microsoft VM for Java implements permission scoping, two rules are followed. The first rule is that permissions are never inherited from the caller. If a class has not been directly granted a permission, it can never make use of that permission, regardless of what permissions its callers may have. This makes trust-based security invulnerable to "luring" attacks, in which an untrusted class "lures" a trusted class into calling it so that the untrusted class is allowed to make use of the expanded permissions of its caller.

The second rule is that even if a class has been granted a permission, its methods must explicitly enable that permission using the assertPermission method whenever there is a caller on the call stack that has not been granted that permission. In other words, permission P is enabled only if either statement 1 or 2 listed below is true, and if statement 3 is true.

  1. P is granted in all of the stack frames from the active frame up to the earliest frame on the stack.
  2. P is granted in all of the stack frames up to a frame that has called assertPermission on P.
  3. No intervening frame has called denyPermission on P.

The deep security checks of the PolicyEngine class perform the stack crawl that follows the above rules. The Java APIs contain calls to the StandardSecurityManager checkXX methods, which in turn call the PolicyEngine.checkPermission methods to check for a particular permission.

The methods of the PolicyEngine class allows you to control which permissions are enabled. For example, the following code sample asserts the right to access scratch space through the com.ms.io.clientstorage APIs, then reverts this right.

import com.ms.security.*;
import com.ms.io.clientstorage.*;

// Assert the right to access the
// com.ms.io.clientstorage APIs.
PolicyEngine.assertPermission(PermissionID.CLIENTSTORE);

// Now open a file for writing. Because rights have been
// asserted, this check will succeed even if the callers
// do not possess the CLIENTSTORE permission.
OutputStream os =
   ClientStorageManager.openWritable("Scratch1.txt");

...
// Remove the scratch space assertion.
PolicyEngine.revertPermission(PermissionID.CLIENTSTORE);
...

// Open a file for reading.
// This time the callers will be included in the
// security check because the right to access the
// com.ms.io.clientstorage APIs is no longer asserted.
// The security check will succeed only if all callers
// have the appropriate CLIENTSTORE permission.
InputStream is =
   ClientStorageManager.openReadable("Scratch2.txt");
...

For more information on asserting, denying, and reverting permissions, see the com.ms.security overview. For more information about how the stack crawl for security checks is implemented, see the overview for the PolicyEngine class.

The Package Manager

The package manager allows the installation of local class libraries that are not fully trusted by using permission signing. This is especially important for components such as JavaBeans and class libraries. It is desirable to allow these components to reside locally and to have some expanded permissions, but it is often not necessary to give them unlimited power.

System libraries are libraries that are shared and have all possible security permissions available to them. These libraries are the core of the Java system APIs, and they are the most privileged Java code. Most packages installed from non-system providers do not need this level of permissions. However, Java has traditionally treated all local classes on the class path as if they were system libraries.

Under trust-based security, classes from installed packages are not shared between applets or applications that use them. They carry specific system permission identifiers that are approved by either the user or the system administrator when the package is installed on the user's system. The permission identifiers determine the maximum permissions that can be used by the classes in that package. For more information on the package manager, see the Java Package Management article.

The User Interface

The user interface (UI) defined by trust-based security for Java shields end users from complicated trust decisions and reduces the number of dialog boxes that they must respond to. The integration of permissions with zones means that users only need to make a simple yes/no decision about whether to trust an application. An administrator has already made preliminary decisions, based on the zone involved, about which permissions to leave to the discretion of the user.

Permission signing allows the security system for the Microsoft VM for Java to predetermine all of the permissions required by a class. When a package is installed, the security system uses the digital signature to determine exactly which system permissions are needed. Before the code runs, a single dialog box clearly presents to the user all of the permissions required by an application.

Summary

Trust-based security for Java provides a flexible, easy to use security system. The permission model provides control over what a Java class can do by providing a way to associate a set of permissions with a class. Encoding the permission set in the digital signature allows the Microsoft VM for Java to present the end user with a dialog box that lists the requested permissions so that the user can decide whether to trust the applet. Because administrators can make preliminary security decisions based on predefined zones, the end user is spared from many tedious security decisions. Permission scoping prevents untrusted classes from taking advantage of the expanded permissions of trusted classes and gives developers the ability to decide which parts of their trusted code enable a particular permission. Finally, package management allows for local installation of components that are not fully trusted so that those components have expanded permissions, but not unlimited power.


About the Microsoft Packages

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Packages | Welcome!
 | Welcome!

About the Microsoft Packages

The following Microsoft packages are in the Microsoft SDK for Java:

Package com.ms.activeX
Provides access to ActiveX controls.
Package com.ms.awt
Provides access to Win32® window-management and graphics features.
Package com.ms.awt.peer
Provides access to an interface supporting Win32® window-management features.
Package com.ms.com
Provides access to Component Object Model (COM) services from Java.
Package com.ms.directX
Provides access to Microsoft® DirectX™ services and features.
Package com.ms.dll
Provides additional support for Microsoft® J/Direct™, the technology that allows access to Windows® dynamic-link libraries (DLLs).
Package com.ms.fx
Provides access to graphics features of the Application Foundation Classes (AFC).
Package com.ms.io
Provides access to file dialog boxes, specialized input and output streams, and a class for manipulating path strings.
Package com.ms.io.clientstorage
Provides access to client storage management and enforcement of client storage limitations.
Package com.ms.lang
Provides access to Microsoft® Win32® system-level features.
Package com.ms.license
Provides classes that support Java object licensing files.
Package com.ms.object
Provides classes and interfaces used to facilitate data transfer.
Package com.ms.object.dragdrop
Provides classes and interfaces for implementing visual drag/drop operations.
Package com.ms.security
Provides access to classes that control the security system.
Package com.ms.security.auditing
Provides an interface for supplying information about an audited security request to a security auditor.
Package com.ms.security.permissions
Provides access to classes that represent permission and request objects that are used to perform security checks.
Package com.ms.service
Provides access to Microsoft® Windows NT® system services.
Package com.ms.ui
Provides access to user interface components of the Application Foundation Classes (AFC).
Package com.ms.ui.resource
Provides access to Win32-style resources from Java applets and applications.
Package com.ms.ui.event
Provides support for the Delegation Event model in the Application Foundation Classes (AFC).
Package com.ms.util
Provides access to version control, task manager, and timer services from Java.
Package com.ms.util.cab
Provides access to cabinet file creation and extraction classes.
Package com.ms.util.InputMethod
Provides access to Input Method Editor (IME) java components.
Package com.ms.vm
Provides a class that implements a weak reference to an object. A weak reference tracks an object without preventing it from being garbage collected.
Package com.ms.xml.dso
Provides a Data Source Object (DSO) applet class that can be used to provide data for data binding using XML files.
Package com.ms.xml.om
Provides classes that implement the Microsoft XML Object Model in Java.
Package com.ms.xml.parser
Provides the Microsoft® XML Parser, which is a validating XML parser written in Java.
Package com.ms.xml.util
Provides base classes for Microsoft XML object technology, including input and output stream objects specifically designed for XML.


About com.ms.activeX

In this topic

* Overview of Classes

* Hosting an ActiveX Control

* Invoking Methods of an ActiveX Control

* Retrieving Properties of an ActiveX Control

* Initializing an ActiveX Control Using Property Bags

* Sinking Events from ActiveX Objects

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.activeX | Packages | Next

About com.ms.activeX

You can use the classes and interfaces in the com.ms.activeX package to host Microsoft® ActiveX® controls and ActiveX Automation objects, to use ActiveX streams, and to access helper functions.

Overview of Classes

The ActiveXControl class provides methods that enable you to host an ActiveX control. You can create the control using the ActiveXControl constructor and then call other methods in the class to set its properties, retrieve its properties, and invoke its methods. The Hosting an ActiveX Control section of this document further describes how you can host an ActiveX control in your Java application.

The ActiveXControlListener interface, when used with the ActiveXControl.addActiveXControlListener method, allows you to register a listener for an ActiveX control so that the listener will be notified when the ActiveX control has been created. Any listeners must implement the ActiveXControlListener interface, which contains a single method called controlCreated. When an ActiveX control is created, the Microsoft Win32 VM for Java calls the controlCreated method on the listener object. To view a code sample that adds a listener, see the Mixing Java and Native Code article.

The ActiveXInputStream and ActiveXOutputStream classes wrap IStream objects that are obtained from COM objects. Instances of these classes are compatible with other Java classes that take java.io.InputStream and java.io.OutputStream objects as parameters. These classes are also used by the Microsoft VM to wrap IStream objects that it obtains from ActiveX containers like Microsoft® Visual Basic®. Once the object is wrapped, the VM can use the java.io serialization classes that work only with InputStream and OutputStream objects.

The ActiveXToolkit class contains methods that allow you to create a FontX object, given an IUnknown interface. You can also use the methods in this class to retrieve the IUnknown interface of a Font object and to create a Java color from an OLE_COLOR.

Hosting an ActiveX Control

Generating a Java Wrapper for an ActiveX Control
Using the ActiveXControl Class to Host an ActiveX Control

There are two ways two host an ActiveX control in a Java application. One way is to use the jactivex tool to generate a Java wrapper for the ActiveX control. The other is to use the ActiveXControl classes directly.

Generating a Java Wrapper for an ActiveX Control

You can run the jactivex tool on the ActiveX control to generate Java source code for the control. When you compile the .java files emitted by jactivex, you get .class files that you can import. You can then use the control just as you would any other Java object. For example, suppose you have obtained a control called MyControl that has a method called MyMethod. After you run the jactivex tool on this control and compile the resulting files, you could use the object in the following way.

   import MyControl.*;
   import java.awt.*;
   ...
   // create the control
   MyControl c = new MyControl();

   //add the control to the layout
   add("Center", c);
   ...

   // call MyMethod
   c.MyMethod(...);

For more information about using jactivex to host an ActiveX control, see the Mixing Java and Native Code article and the jactivex section of the Tools Quick Reference.

Using the ActiveXControl Class to Host an ActiveX Control

The other way to host an ActiveX control involves using the methods in the ActiveX control class. To create the control, you would pass the CLSID or ProgID to the ActiveXControl constructor. You can then invoke methods, retrieve properties, or set properties of the control. Again, suppose you have a control called MyControl that has a method called MyMethod. You can create the control and add it to the layout, as shown in the following example.

   import com.ms.activeX.ActiveXControl;
   import java.awt.*;

   ...
   // create the control
   ActiveXControl c = new ActiveXControl("MyControl");

   // add the control to the layout
   add("Center", c);

   // do something interesting
   ...

Invoking Methods of an ActiveX Control

Suppose MyControl has a method called MyMethod that you want to call. Let's assume that MyMethod takes three parameters: a String, an integer, and a boolean. The ActiveXControl.invoke method allows you to call MyMethod. The invoke method takes as a parameter an array of Variants that contains the arguments to the method you want to call. The arguments are passed to the control through IDispatch. This example shows how you could create and initialize an array of Variants called args and call MyMethod by passing args to the invoke method.

   Variant args[] = new Variant[3};
   args[0] = new Variant("String arg");
   args[1] = new Variant(100);
   args[2] = new Variant(true);
   c.invoke("MyMethod", args);

Retrieving Properties of an ActiveX Control

You can also use the ActiveXControl class to retrieve properties from an object. To do this, call the ActiveXControl.getProperty method. If MyControl had a property called MyProperty, you could retrieve its value in the following way.

   // Create the control as before
   ActiveXControl c = new ActiveXControl("MyControl");
   ...

   // Retrieve a property
   Variant propvalue = c.getProperty("MyProperty");

Initializing an ActiveX Control Using Property Bags

You can call the setProperty method of the ActiveXControl class to set a property of an ActiveX control. If the setProperty method is called before the addNotify method is called, the setProperty method places properties in the property bag of the control. This gives the control a mechanism for setting its default state. After the control has been called on addNotify, the setProperty method is invoked using IDispatch. The following example shows how to initialize two properties of MyControl using the setProperty method to place the properties in the property bag.

   ActiveXControl c = new ActiveXControl("MyControl");
   c.setProperty("MyProperty", true);
   c.setProperty("MyOtherProperty", 1);
   add("Center", c);

Sinking Events from ActiveX Objects

Using the jactivex tool, you can gain access to the event interface of the ActiveX object. For example, suppose you have a control called MyControl that has an event interface called MyEventInterface. Let's say this interface has a method called theEvent, which needs to be implemented by any class that wants to sink theEvent from MyControl. A Java object can sink events from the ActiveX object by using the com.ms.com.ConnectionPointCookie class, as follows.

import MyControl.*;
import com.ms.activeX.ActiveXControl;
import com.ms.com.ConnectionPointCookie;

public class MyEventSinker implements MyEventInterface {

   ...

   MyControl c = new MyControl;
   Eventcookie = new ConnectionPointCookie(c, this,
                 Class.forName("MyControl.MyEventInterface");

   // hold onto Eventcookie as long as you want the connection to exist
   ...

   public void theEvent(String x){

      // do something interesting
      ...
   }
}

Classes

Class ActiveXComponent
This class provides basic Microsoft® ActiveX® control functionality.
Class ActiveXControl
This class exposes methods, properties, and events used to host Microsoft® ActiveX® controls.
Class ActiveXInputStream
This class provides access to methods that manipulate input streams.
Class ActiveXOutputStream
This class provides access to methods that manipulate output streams.
Class ActiveXToolkit
This class provides a toolkit of Component Object Model (COM) functions.

Interfaces

Interface ActiveXControlListener
This interface provides a method that notifies an object after a Microsoft® ActiveX® control has been created.
Interface ActiveXControlServices
This interface represents a standard system service that is available for Java components hosted inside ActiveX containers.

Hierarchy

Object
  |
  +--ActiveXToolkit

Canvas
  |
  +--ActiveXComponent
     |
     +--ActiveXControl (Serializable, HeavyComponent)

InputStream
  |
  +--ActiveXInputStream

OutputStream
  |
  +--ActiveXOutputStream

ActiveXControlListener
ActiveXControlServices


Class ActiveXComponent

public class ActiveXComponent extends Canvas
{
  // Constructors
  public ActiveXComponent();
  public ActiveXComponent(String c);
  public ActiveXComponent(IUnknown punk);

  // Methods
  public IUnknown createInstance(String c);
  public IUnknown createInstance();
  public void createInstance(IUnknown punk);
  public void enableEvents();
  public String getCLSID();
  protected IAXComponent getHost();
  public IUnknown getObject();
  public Variant getProperty(String propertyname);
  public Variant invoke(String methodname, Variant args[]);
  public void setCLSID(String c);
  public void setProperty(String name, Variant value);
}

This class provides basic Microsoft® ActiveX® control functionality. Its methods allow you to create ActiveXComponent objects, to set or retrieve the CLSID (class identifier) that identifies the class of the object, and to get the IUnknown interface of an ActiveXComponent object. The ActiveXControl class extends this class.

Canvas
  |
  +--ActiveXComponent

Constructors

ActiveXComponent

public ActiveXComponent();

Creates a new ActiveXComponent object.

ActiveXComponent

public ActiveXComponent(String c);

Creates a new ActiveXComponent object whose class is identified by the CLSID or ProgID (programatic identifier).

Parameter | Description
c | The CLSID (or ProgID) of the object that is created. The CLSID must be in the form "{xxx...xxx}", where x represents a numeric character between 0 and 9, inclusive.

ActiveXComponent

public ActiveXComponent(IUnknown punk);

Creates a new ActiveXComponent object using the identity of a pre-existing COM object.

Parameter | Description
punk | The identity of the COM object.

Methods

createInstance

public IUnknown createInstance(String c);

Creates a new instance of the ActiveXComponent class.

Return Value:

Returns the IUnknown interface of the new object.

Parameter | Description
c | The CLSID (or ProgID) of the object that is created. The CLSID must be in the form "{xxx...xxx}", where x represents a numeric character between 0 and 9, inclusive.

createInstance

public IUnknown createInstance();

Creates a new ActiveXComponent object with the CLSID that was previously set by the constructor or by the setCLSID method.

Return Value:

Returns the IUnknown interface of the new object.

createInstance

public void createInstance(IUnknown punk);

Creates a new ActiveXComponent object using the identity of a pre-existing COM object.

Return Value:

No return value.

Parameter | Description
punk | The identity of the COM object.

enableEvents

public void enableEvents();

Wires events for an object. When an object derives from the ActiveXComponent class, this method should be implemented using an instance of ConnectionPointCookie to sink an event.

Return Value:

No return value.

getCLSID

public String getCLSID();

Retrieves the CLSID (or ProgID) of the ActiveXComponent object.

Return Value:

Returns the CLSID (or ProgID) for the component.

getHost

protected IAXComponent getHost();

Retrieves the interface of the ActiveXComponent host.

Return Value:

Returns the interface of the ActiveXComponent host.

getObject

public IUnknown getObject();

Retrieves the IUnknown interface of an ActiveXComponent object.

Return Value:

Returns the IUnknown interface of the ActiveXComponent object.

getProperty

public Variant getProperty(String propertyname);

Invokes a property to retrieve the property value.

Return Value:

Returns the value of the property.

Parameter | Description
propertyname | The name of the property whose value will be retrieved.

Exceptions:

IllegalArgumentException if propertyname is null.

invoke

public Variant invoke(String methodname, Variant args[]);

Invokes a method on the ActiveX control.

Return Value:

Returns the value returned by the invoked method.

Parameter | Description
methodname | The name of the method to invoke.
args | The argument list for the method.

Exceptions:

IllegalArgumentException if methodname is null.

setCLSID

public void setCLSID(String c);

Sets the CLSID or (ProgID) of the ActiveXComponent object.

Return Value:

No return value.

Parameter | Description
c | The new CLSID (or ProgID) of the object. The CLSID must be in the form "{xxx...xxx}", where x represents a numeric character between 0 and 9, inclusive.

setProperty

public void setProperty(String name, Variant value);

Sets a variant property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property to set.
value | The value of the property.

Exceptions:

IllegalArgumentException if name is null.


Class ActiveXControl

public class ActiveXControl extends ActiveXComponent
             implements Serializable, HeavyComponent
{
  // Fields
  public static final int CURRENCY;
  public static final int DATE;
  public static final int DOUBLE;

  // Constructors
  public ActiveXControl();
  public ActiveXControl(String clsid);
  public ActiveXControl(IUnknown punk);

  // Methods
  public void activate();
  public void activateNoGUI();
  public void addActiveXControlListener(
        ActiveXControlListener listener);
  protected void createControl(String clsid) throws Exception;
  protected void createControl(IUnknown punk) throws Exception;
  protected void finalize() throws Throwable;
  public Dimension getMinimumSize();
  public Dimension getPreferredSize();
  public boolean isFocusTraversable();
  public synchronized void processComponentEvent(
        ComponentEvent event);
  public void processFocusEvent(FocusEvent event);
  public void removeActiveXControlListener(
        ActiveXControlListener listener);
  public void removeNotify();
  public void setBackground(Color c);
  public void setDesignMode(boolean b);
  public void setFont(Font f);
  public void setForeground(Color c);
  public void setProperty(String name, String value);
  public void setProperty(String name, int value);
  public void setProperty(String name, short value);
  public void setProperty(String name, boolean value);
  public void setProperty(String name, long value, int flag);
  public void setProperty(String name, double value);
  public void setProperty(String name, double value, int flag);
  public void setProperty(String name, float value);
  public void setProperty(String name, Variant value);
  public void showPropertyDialog();
}

This class exposes methods, properties, and events used to host Microsoft® ActiveX® controls. Instances of the ActiveXControl class are objects that enable Java components to host ActiveX controls.

Canvas
  |
  +--ActiveXComponent
    |
    +--ActiveXControl

Constructors

ActiveXControl

public ActiveXControl();

Creates an ActiveXControl object that is a container for an ActiveX control. To add a control to the container, you can call the createControl method.

ActiveXControl

public ActiveXControl(String clsid);

Creates an ActiveXControl object that is a container for an ActiveX control. This method hosts the control specified by the CLSID (class identifier) or ProgID (programatic identifier).

Parameter | Description
clsid | Identifies the CLSID (or ProgID) for the ActiveX control. The CLSID is in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", where x is a valid hexadecimal number.

ActiveXControl

public ActiveXControl(IUnknown punk);

Creates an ActiveXControl object that is a container for an ActiveX control. This method hosts a control that has already been created.

Parameter | Description
punk | The identity of the ActiveX control.

Methods

activate

public void activate();

Tells the control to become in-place active.

Note By default, a control is activated at addNotify time. Therefore, if an ActiveXControl object needs properties for initialization, calls to the setProperty method should be made before addNotify time.

Return Value:

No return value.

activateNoGUI

public void activateNoGUI();

Activates a non-GUI control. By default, all ActiveX controls are assumed to have UI. However, the negotiation for such a control happens at addNotify time when an object is added to a layout. You should call this method to activate a control that does not have GUI representation.

Return Value:

No return value.

addActiveXControlListener

public void addActiveXControlListener(ActiveXControlListener listener);

Adds an ActiveXControlListener object that listens to events sourced by the ActiveXControl class.

Return Value:

No return value.

Parameter | Description
listener | The ActiveXControlListener object that will sink events.

createControl

protected void createControl(String clsid) throws Exception;

Creates an ActiveXControl object that is a container for an ActiveX control. This method hosts the control specified by the CLSID (or ProgID).

Return Value:

No return value.

Parameter | Description
clsid | Identifies the CLSID (or ProgID) for the ActiveX control. The CLSID is in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", where "x" is a valid hexadecimal number.

Remarks:

This method is used to defer the hosting of an ActiveX control, and is typically used when a control host was created using the ActiveXControl() constructor or when extending the ActiveXControl class.

Exceptions:

Exception if there is an error when initializing the control.

NullPointerException if clsid is null or if the IUnknown for the ActiveX control is not valid.

createControl

protected void createControl(IUnknown punk) throws Exception;

Creates an ActiveXControl object that is a container for an ActiveX control. This method hosts a control that has already been created.

Return Value:

No return value.

Parameter | Description
punk | The identity of the ActiveX control.

Remarks:

This method is used to defer the hosting of an ActiveX control, and is typically used when a control host was created using the ActiveXControl() constructor or when extending the ActiveXControl class.

Exceptions:

Exception if there is an error when initializing the control.

NullPointerException if punk is null.

finalize

protected void finalize() throws Throwable;

Removes the ActiveX control from memory. This method is called by the garbage collector.

Return Value:

No return value.

getMinimumSize

public Dimension getMinimumSize();

Retrieves the minimum size of the ActiveXControl object.

Return Value:

Returns the object's minimum size, which is the same as its preferred size, measured in pixels.

getPreferredSize

public Dimension getPreferredSize();

Retrieves the preferred size of the ActiveXControl object.

Return Value:

Returns the preferred width and height of the object, measured in pixels.

isFocusTraversable

public boolean isFocusTraversable();

Tells the window manager that we want focus.

Return Value:

Returns true if the object is placed in the focus traversing list.

processComponentEvent

public synchronized void processComponentEvent(ComponentEvent event);

Processes the events from the component. It determines when the object has been resized, shown, or hidden.

Return Value:

No return value.

Parameter | Description
event | The ComponentEvent that was fired by the container.

processFocusEvent

public void processFocusEvent(FocusEvent event);

Processes focus events. When the focus is gained, the ActiveX control will become UI-active.

Return Value:

No return value.

Parameter | Description
event | The FocusEvent object that was fired by the window manager.

removeActiveXControlListener

public void removeActiveXControlListener(ActiveXControlListener listener);

Removes an ActiveXControlListener object from the list of interested listeners. After this method is called, the component will no longer be notified on control hosting events.

Return Value:

No return value.

Parameter | Description
listener | The ActiveXControlListener object that will be removed.

removeNotify

public void removeNotify();

Destroys the component's peer.

Warning You should never call this method directly.

Return Value:

No return value.

setBackground

public void setBackground(Color c);

Sets the background color of the component. This method notifies the control that the background color has changed.

Return Value:

No return value.

Parameter | Description
c | The new color of the background.

setDesignMode

public void setDesignMode(boolean b);

Tells the ActiveX control to go into design mode.

Return Value:

No return value.

Parameter | Description
b | The value that indicates whether the control should be notified that it is in design mode. If the value is true, the control is notified that the container is in design mode. If the value is false (the default), the container notifies the control that it is in run mode.

setFont

public void setFont(Font f);

Sets the font of the component. This method notifies the control that the font has changed.

Return Value:

No return value.

Parameter | Description
f | The new font.

setForeground

public void setForeground(Color c);

Sets the foreground color of the component. This method notifies the control that the foreground color has changed.

Return Value:

No return value.

Parameter | Description
c | The new color of the foreground.

setProperty

public void setProperty(String name, String value);

Sets a string property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The string value of the property.

setProperty

public void setProperty(String name, int value);

Sets an integer property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The integer value of the property.

setProperty

public void setProperty(String name, short value);

Sets a short integer property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The short integer value of the property.

setProperty

public void setProperty(String name, boolean value);

Sets a boolean property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The boolean value of the property.

setProperty

public void setProperty(String name, long value, int flag);

Sets a currency property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The value of the property.
flag | Indicates how to set the property. If the value is CURRENCY, the property type is set to indicate currency; otherwise, the method returns without setting a property.

setProperty

public void setProperty(String name, double value);

Sets a double property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The value of the property.

setProperty

public void setProperty(String name, double value, int flag);

Sets a double or a date property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The double value of the property.
flag | The value that determines how to set the property type. If the value is DATE, the property type is set to indicate a date; if the value is DOUBLE, the property type is set to indicate a double.

setProperty

public void setProperty(String name, float value);

Sets a float property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property that is set.
value | The float value of the property.

setProperty

public void setProperty(String name, Variant value);

Sets a variant property of the ActiveX control.

Return Value:

No return value.

Parameter | Description
name | The name of the property to set.
value | The value of the property.

Overrides:

setProperty(String,Variant) in ActiveXComponent.

showPropertyDialog

public void showPropertyDialog();

Queries an ActiveX control for its property pages and displays the property dialog box.

Return Value:

No return value.

Fields

CURRENCY
Indicates the currency variant type.
DATE
Indicates the date variant type.
DOUBLE
Indicates the double variant type.


Class ActiveXInputStream

public class ActiveXInputStream extends InputStream
{
  // Constructors
  public ActiveXInputStream(IStream stream);

  // Methods
  public int available() throws IOException;
  public void close() throws IOException;
  public int read() throws IOException;
  public int read(byte b[], int off, int len) throws IOException;
  public long skip(long n) throws IOException;
}

This class provides access to methods that manipulate input streams. You can create an input stream, read bytes from it, skip a specified number of bytes in the stream, see how many bytes are available to read, and close an input stream using the methods in this class.

InputStream
  |
  +--ActiveXInputStream

Constructors

ActiveXInputStream

public ActiveXInputStream(IStream stream);

Creates an ActiveXInputStream object.

Parameter | Description
stream | The IStream interface for the new object.

Methods

available

public int available() throws IOException;

Determines the number of bytes that can be read from the input stream without blocking.

Return Value:

Returns the number of bytes that can be read from the input stream without blocking.

Exceptions:

IOException if an I/O error occurs.

close

public void close() throws IOException;

Closes the input stream and releases the IStream interface associated with the stream.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurs.

read

public int read() throws IOException;

Reads the next byte of data from the input stream. The value of the byte is returned as an integer in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Return Value:

Returns the next byte of data, or -1 if the end of the stream is reached.

Exceptions:

IOException if an I/O error occurs.

read

public int read(byte b[], int off, int len) throws IOException;

Reads bytes of data from the input stream into an array of bytes. This method blocks until some input is available.

Return Value:

Returns the total number of bytes read into the buffer; returns -1 if there is no more data because the end of the file has been reached.

Parameter | Description
b | The buffer into which the data is read.
off | The starting offset of the data.
len | The maximum number of bytes to read.

Exceptions:

IOException if an I/O error occurs.

skip

public long skip(long n) throws IOException;

Skips over and discards bytes of data from the input stream and returns the number of bytes actually skipped.

Return Value:

Returns the number of bytes skipped.

Parameter | Description
n | The number of bytes to skip.

Remarks:

If there are fewer than n bytes remaining before the end of the stream, this method skips the number of bytes remaining. The current read position is set to the end of the file and the number of bytes skipped is returned.

Exceptions:

IOException if an I/O error occurs.


Class ActiveXOutputStream

public class ActiveXOutputStream extends OutputStream
{
  // Constructors
  public ActiveXOutputStream(IStream stream);

  // Methods
  public void close() throws IOException;
  public void flush() throws IOException;
  public void write(int b) throws IOException;
  public void write(byte b[], int off, int len) throws IOException;
}

This class provides access to methods that manipulate output streams. You can create an output stream, write bytes to it, flush the output stream, and close it by using the methods in this class.

OutputStream
  |
  +--ActiveXOutputStream

Constructors

ActiveXOutputStream

public ActiveXOutputStream(IStream stream);

Creates an ActiveXOutputStream object that has the specified IStream interface.

Parameter | Description
stream | The IStream interface of the object.

Methods

close

public void close() throws IOException;

Closes the output stream and releases the IStream interface associated with the stream.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurs.

flush

public void flush() throws IOException;

Flushes the output stream and forces buffered output bytes to be written out.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurs.

write

public void write(int b) throws IOException;

Writes a byte to the output stream.

Return Value:

No return value.

Parameter | Description
b | The byte to write to the output stream.

Exceptions:

IOException if an I/O error occurs.

write

public void write(byte b[], int off, int len) throws IOException;

Writes a specified number of bytes from a byte array to the output stream, beginning with the byte at offset off in the array.

Return Value:

No return value.

Parameter | Description
b | The bytes to write.
off | The starting offset in the array.
len | The number of bytes to write.

Exceptions:

IOException if an I/O error occurs.


Class ActiveXToolkit

public class ActiveXToolkit
{
  // Methods
  static public java.awt.Color getColorFromOLECOLOR(int colorindex);
  static public FontX getFontX(Object punk);
  static public Object getIUnknownFont(Font font);
}

This class provides a toolkit of Component Object Model (COM) functions.

Methods

getColorFromOLECOLOR

static public java.awt.Color getColorFromOLECOLOR(int colorindex);

Creates a Java color from an OLE_COLOR.

Return Value:

Returns the Java color that is derived from the OLE_COLOR.

Parameter | Description
colorindex | The OLE_COLOR that the Java color is created from.

getFontX

static public FontX getFontX(Object punk);

Creates a FontX object, given an IUnknown interface. This method obtains the font for the object by using QueryInterface on IUnknown to query for the IFont interface.

Return Value:

Returns a FontX object obtained by querying IUnknown for the IFont interface. If punk is null, null is returned.

Parameter | Description
punk | The IUnknown interface that is queried for the IFont interface.

getIUnknownFont

static public Object getIUnknownFont(Font font);

Retrieves the IUnknown interface of a Font object that represents a Java font.

Return Value:

Returns the IUnknown interface of an Font object that represents a Java font.

Parameter | Description
font | The Font object that represents a Java font.


Interface ActiveXControlListener

public interface ActiveXControlListener extends java.util.EventListener
{
  // Methods
  public void controlCreated(Object target);
}

This interface provides a method that notifies an object after a Microsoft® ActiveX® control has been created. After the control has been created, it is safe to call methods on the ActiveX control.

EventListener
  |
  +--ActiveXControlListener

Methods

controlCreated

public void controlCreated(Object target);

Notifies an object after an ActiveX control has been created. After such notification, it is safe to call methods on the ActiveX control.

Return Value:

No return value.

Parameter | Description
target | The ActiveX control that was created.


Interface ActiveXControlServices

public interface ActiveXControlServices
{
  // Methods
  public Object getClientSite();
}

This interface represents a standard system service that is available for Java components hosted inside Microsoft® ActiveX® containers. The ActiveXControlServices system service can be obtained by using the queryService method of the com.ms.object.IServiceObjectProvider interface to query a site object.

A Java component must implement the com.ms.object.ISiteable interface to obtain an object that implements the com.ms.object.ISite interface. This site object can be queried for the ActiveXControlServices service when the Java component is hosted from an ActiveX container, such as Microsoft® Visual Basic®.

Methods

getClientSite

public Object getClientSite();

Retrieves the ActiveX client site object. This object might implement any number of standard ActiveX site interfaces, such as IOleClientSite or IOleInPlaceSite. The client site object can be used as a bridge between an ActiveX container and a Java component that it is hosting.


About com.ms.awt

This package provides access to Microsoft® Win32® system-level features that are not available in the standard java.awt package.

Classes

Class CaretX
This class is obsolete.
Class CursorX
This class implements an extended cursor object.
Class Device
This class manages information associated with a generic device.
Class DeviceException
Signals that a com.ms.awt.Device-related exception has occurred.
Class DisplayDevice
This class handles display devices.
Class FocusEvent
This class manages component-level focus events.
Class FontMetricsX
This class provides an extended font metrics implementation specific to the Microsoft Win32 VM for Java.
Class FontX
This class creates a font object that defines the font family, font face, style, and size.
Class GraphicsX
This class provides a graphics implementation specifically for the Microsoft VM.
Class ImageX
This class encapsulates an extended image object.
Class Mat2
This class defines a transformation matrix that can be used with outline font methods.
Class MenuBarX
This class is obsolete.
Class MenuItemX
This class is obsolete.
Class MenuX
This class is obsolete.
Class PointFx
This class defines the x and y coordinates of a point on the outline of a TrueType character.
Class PrinterDevice
This class handles printer devices.
Class WDragSession
This class is an AWT drag-and-drop implementation using the object and dragdrop protocols.
Class Win32SystemResourceDecoder
This class is used to utilize Win32 system resource (.res) files.
Class WinEvent
This class provides a raw API that enables Java objects to use Microsoft Active Accessibility.
Class WPrintGraphics
This class encapsulates a print graphics context for a printable page.
Class WPrintJob
This class creates Win32 WPrintJob objects that handle printing.

Interfaces

Interface HeavyComponent
This interface is implemented by Java classes that require a Microsoft® Win32® system window (an HWND) for operations that access the native operating system.
Interface MenuXConstants
This interface is obsolete.

Hierarchy

Object
  |
  +--CaretX
  |
  +--Device
  |  |
  |  +--DisplayDevice
  |  |
  |  +--PrinterDevice
  |
  +--Mat2
  |
  +--PointFx
  |
  +--WinEvent (com.ms.ui.IWinEvent)

Cursor
  |
  +--CursorX

Exception
  |
  +--DeviceException

FocusEvent
  |
  +--FocusEvent

FxFontMetrics
  |
  +--FontMetricsX

FxFont
  |
  +--FontX

FxGraphics
  |
  +--GraphicsX (PeerConstants, PaintSurface)
     |
     +--WPrintGraphics (PrintGraphics)

Image
  |
  +--ImageX

MenuBar
  |
  +--MenuBarX (MenuXConstants)

CheckboxMenuItem
  |
  +--MenuItemX

Menu
  |
  +--MenuX (MenuXConstants)

DragHelper
  |
  +--WDragSession (DragSession)

Win32ResourceDecoder
  |
  +--Win32SystemResourceDecoder

PrintJob
  |
  +--WPrintJob

HeavyComponent
MenuXConstants


Class CaretX

public class CaretX
{
  // Constructors
  public CaretX(Component c, InputMethodListener ime);
  public CaretX(Component c, int w, int h);

  // Methods
  public void finalize();
  public int getHeight();
  public int getWidth();
  public void hide();
  public void setPos(Point p);
  public void setPos(int px, int py);
  public void show();
}

This class is obsolete. This class has been replaced by the FxCaret implementation in the com.ms.fx package.

Constructors

CaretX

public CaretX(Component c, InputMethodListener ime);

Note This constructor is obsolete.

CaretX

public CaretX(Component c, int w, int h);

Note This constructor is obsolete.

Methods

finalize

public void finalize();

Note This method is obsolete.

getHeight

public int getHeight();

Note This method is obsolete.

getWidth

public int getWidth();

Note This method is obsolete.

hide

public void hide();

Note This method is obsolete.

setPos

public void setPos(Point p);

Note This method is obsolete.

setPos

public void setPos(int px, int py);

Note This method is obsolete.

show

public void show();

Note This method is obsolete.


Class CursorX

public class CursorX extends Cursor
{
  // Constructors
  public CursorX(Image img, int x, int y);

  // Methods
  public int getType();
}

This class implements an extended cursor object.

Note For the Microsoft SDK for Java version 2.01 release, images must be 32-by-32 pixels to be used successfully with CursorX objects.

Cursor
  |
  +--CursorX

Constructors

CursorX

public CursorX(Image img, int x, int y);

Creates an extended cursor object with a default type from a specified image.

Parameter | Description
img | The Image to create the cursor from.
x | The x coordinate of the point that acts as the cursor's hot spot.
y | The y coordinate of the point that acts as the cursor's hot spot.

Methods

getType

public int getType();

Retrieves the current CursorX object's type.

Return Value:

Returns the cursor type. Currently, all CursorX objects are created with a java.awt.Cursor.DEFAULT_CURSOR type, and will return 0.


Class Device

public class Device
{
  // Fields
  public static final int BLTALIGNMENT;
  public final static int CC_CHORD;
  public final static int CC_CIRCLES;
  public final static int CC_ELLIPSES;
  public final static int CC_INTERIORS;
  public final static int CC_NONE;
  public final static int CC_PIE;
  public final static int CC_ROUNDRECT;
  public final static int CC_STYLED;
  public final static int CC_WIDE;
  public final static int CC_WIDESTYLED;
  public final static int CP_NONE;
  public final static int CP_RECTANGLE;
  public final static int CP_REGION;
  public static final int DESKTOPHORZRES;
  public static final int DESKTOPVERTRES;
  public final static int DT_CHARSTREAM;
  public final static int DT_DISPFILE;
  public final static int DT_METAFILE;
  public final static int DT_PLOTTER;
  public final static int DT_RASCAMERA;
  public final static int DT_RASDISPLAY;
  public final static int DT_RASPRINTER;
  public final static int LC_INTERIORS;
  public final static int LC_MARKER;
  public final static int LC_NONE;
  public final static int LC_POLYLINE;
  public final static int LC_POLYMARKER;
  public final static int LC_STYLED;
  public final static int LC_WIDE;
  public final static int LC_WIDESTYLED;
  public final static int PC_INTERIORS;
  public final static int PC_NONE;
  public final static int PC_PATHS;
  public final static int PC_POLYGON;
  public final static int PC_POLYPOLYGON;
  public final static int PC_RECTANGLE;
  public final static int PC_SCANLINE;
  public final static int PC_STYLED;
  public final static int PC_TRAPEZOID;
  public final static int PC_WIDE;
  public final static int PC_WIDESTYLED;
  public final static int PC_WINDPOLYGON;
  public final static int RC_BANDING;
  public final static int RC_BIGFONT;
  public final static int RC_BITBLT;
  public final static int RC_BITMAP64;
  public final static int RC_DEVBITS;
  public final static int RC_DI_BITMAP;
  public final static int RC_DIBTODEV;
  public final static int RC_FLOODFILL;
  public final static int RC_GDI20_OUTPUT;
  public final static int RC_GDI20_STATE;
  public final static int RC_NONE;
  public final static int RC_OP_DX_OUTPUT;
  public final static int RC_PALETTE;
  public final static int RC_SAVEBITMAP;
  public final static int RC_SCALING;
  public final static int RC_STRETCHBLT;
  public final static int RC_STRETCHDIB;
  public final static int TC_CP_STROKE;
  public final static int TC_CR_90;
  public final static int TC_CR_ANY;
  public final static int TC_EA_DOUBLE;
  public final static int TC_IA_ABLE;
  public final static int TC_OP_CHARACTER;
  public final static int TC_OP_STROKE;
  public final static int TC_RA_ABLE;
  public final static int TC_RESERVED;
  public final static int TC_SA_CONTIN;
  public final static int TC_SA_DOUBLE;
  public final static int TC_SA_INTEGER;
  public final static int TC_SCROLLBLT;
  public final static int TC_SF_X_YINDEP;
  public final static int TC_SO_ABLE;
  public final static int TC_UA_ABLE;
  public final static int TC_VA_ABLE;
  public static final int VREFRESH;

  // Constructors
  protected Device();

  // Methods
  public Dimension getAspectRatio();
  public int getAspectRatioXY();
  public void getBasics(int hdc) throws DeviceException;
  public int getBitsPerPixel();
  public int getClipCapabilities();
  public int getColorResolution();
  public int getCurveCapabilities();
  public final static Device getDeviceFromGraphics(
        Graphics g) throws DeviceException;
  public Dimension getDeviceSize();
  protected int getDisplayContext(Graphics g)
        throws DeviceException;
  public int getDriverVersion();
  public int getLineCapabilities();
  public Dimension getLogicalPixelsPerInch();
  public int getNumberOfBrushes();
  public int getNumberOfColors();
  public int getNumberOfFonts();
  public int getNumberOfMarkers();
  public int getNumberOfPens();
  public int getPaletteReserved();
  public int getPaletteSize();
  public Dimension getPixelRes();
  public int getPlanes();
  public int getPolygonCapabilities();
  public int getRasterCapabilities();
  public int getTechnology();
  public int getTextCapabilities();
}

This class manages information associated with a generic device.

The DisplayDevice and PrinterDevice classes are derived from the Device class.

Constructors

Device

protected Device();

A constructor for the abstract class.

Methods

getAspectRatio

public Dimension getAspectRatio();

Retrieves the device aspect ratio.

Return Value:

Returns a Dimension that defines the device aspect ratio.

getAspectRatioXY

public int getAspectRatioXY();

getBasics

public void getBasics(int hdc) throws DeviceException;

Retrieves the basic information set (common to all devices types) from the native system. The information set includes the driver version, pixel resolution, curve, line, polygon, and raster capabilities, color resolution, logical pixels per inch, and so on.

Return Value:

No return value.

Parameter | Description
hdc | The device context.

Exceptions:

com.ms.awt.DeviceException

getBitsPerPixel

public int getBitsPerPixel();

Retrieves the device number of bits per pixel.

Return Value:

Returns the bits per pixel.

getClipCapabilities

public int getClipCapabilities();

Retrieves the clipping capabilities of the device.

Return Value:

Returns one of the clipping capabilities flags as shown in the following table.
CP_NONE CP_RECTANGLE CP_REGION

getColorResolution

public int getColorResolution();

Retrieves a device's color resolution.

Return Value:

Returns the color resolution.

getCurveCapabilities

public int getCurveCapabilities();

Retrieves the curve capabilities of the device.

Return Value:

Returns one or a combination of the following curve capabilities flags:
CC_NONE CC_CIRCLES CC_PIE CC_CHORD
CC_ELLIPSES CC_WIDE CC_STYLED CC_WIDESTYLED
CC_INTERIORS CC_ROUNDRECT

getDeviceFromGraphics

public final static Device getDeviceFromGraphics(Graphics g)
        throws DeviceException;

Retrieves a device, given a graphics context. The device created is an instance of the DisplayDevice or the PrinterDevice class.

Parameter | Description
g | An extended graphics context, either an FxGraphics or a GraphicsX object.

Exceptions:

com.ms.awt.DeviceException if the graphics context is not valid.

getDeviceSize

public Dimension getDeviceSize();

Retrieves the physical device size as a Dimension.

Return Value:

Returns a Dimension that defines the physical size of the device.

getDisplayContext

protected int getDisplayContext(Graphics g) throws DeviceException;

Retrieves a display context usable on the device. If the display device is something other than a monitor (a printer, for example), the device context is obtained from the native peer object.

Return Value:

Returns zero if the device is the screen; otherwise, returns the handle of the device context.

Parameter | Description
g | The Graphics object to get the context for.

Exceptions:

com.ms.awt.DeviceException if the graphics context is not an instance of the FxGraphics or GraphicsX graphics classes.

getDriverVersion

public int getDriverVersion();

Retrieves the device driver version number.

Return Value:

Returns the driver version.

getLineCapabilities

public int getLineCapabilities();

Retrieves the line capabilities of the device.

Return Value:

Returns one or a combination of the following line capabilities flags:
LC_NONE LC_POLYLINE LC_MARKER LC_POLYMARKER
LC_WIDE LC_STYLED LC_WIDESTYLED LC_INTERIORS

getLogicalPixelsPerInch

public Dimension getLogicalPixelsPerInch();

Retrieves a device's logical pixels per inch.

Return Value:

Returns a device's logical pixels per inch.

getNumberOfBrushes

public int getNumberOfBrushes();

Retrieves the number of brushes used by the device.

Return Value:

Returns the number of brushes.

getNumberOfColors

public int getNumberOfColors();

Retrieves the number of colors used by the device.

Return Value:

Returns the number of colors.

getNumberOfFonts

public int getNumberOfFonts();

Retrieves the number of fonts used by the device.

Return Value:

Returns the number of fonts.

getNumberOfMarkers

public int getNumberOfMarkers();

Retrieves the number of markers used by the device.

Return Value:

Returns the number of markers.

getNumberOfPens

public int getNumberOfPens();

Retrieves the number of pens used by the device.

Return Value:

Returns the number of pens.

getPaletteReserved

public int getPaletteReserved();

Retrieves a reserved device palette.

Return Value:

Returns the reserved palette.

getPaletteSize

public int getPaletteSize();

Retrieves a device palette size.

Return Value:

Returns the size of the palette.

getPixelRes

public Dimension getPixelRes();

Retrieves the device's pixel resolution (in pixels per inch).

Return Value:

Returns the pixel resolution.

getPlanes

public int getPlanes();

Retrieves the number of planes used by the device.

Return Value:

Returns the number of planes.

getPolygonCapabilities

public int getPolygonCapabilities();

Retrieves the polygon capabilities of the device.

Return Value:

Returns one or a combination of the polygon capabilities flags shown in the following table.
PC_NONE PC_POLYGON PC_RECTANGLE PC_WINDPOLYGON
PC_TRAPEZOID PC_SCANLINE PC_WIDE PC_STYLED
PC_WIDESTYLED PC_INTERIORS PC_POLYPOLYGON PC_PATHS

getRasterCapabilities

public int getRasterCapabilities();

Retrieves the device raster capabilities.

Return Value:

Returns one or a combination of the raster capabilities flags shown in the following table.
RC_NONE RC_BITBLT RC_BANDING RC_SCALING
RC_BITMAP64 RC_GDI20_OUTPUT RC_GDI20_STATE RC_SAVEBITMAP
RC_DI_BITMAP RC_PALETTE RC_DIBTODEV RC_BIGFONT
RC_STRETCHBLT RC_FLOODFILL RC_STRETCHDIB RC_OP_DX_OUTPUT
RC_DEVBITS

getTechnology

public int getTechnology();

Retrieves the device technology.

Return Value:

Returns one of the following device technology flags:
DT_PLOTTER DT_RASDISPLAY DT_RASPRINTER
DT_RASCAMERA DT_CHARSTREAM DT_METAFILE DT_DISPFILE

getTextCapabilities

public int getTextCapabilities();

Retrieves the text capabilities of the device.

Return Value:

Returns one or a combination of the text capabilities flags shown in the following table.
TC_OP_CHARACTER TC_OP_STROKE TC_CP_STROKE TC_CR_90
TC_CR_ANY TC_SF_X_YINDEP TC_SA_DOUBLE TC_SA_INTEGER
TC_SA_CONTIN TC_EA_DOUBLE TC_IA_ABLE TC_UA_ABLE
TC_SO_ABLE TC_RA_ABLE TC_VA_ABLE TC_RESERVED
TC_SCROLLBLT

Fields

BLTALIGNMENT
The preferred blit alignment.
CC_CHORD
A curve capabilities flag that indicates chord arcs are supported.
CC_CIRCLES
A curve capabilities flag that indicates circles are supported.
CC_ELLIPSES
A curve capabilities flag that indicates ellipses are supported.
CC_INTERIORS
A curve capabilities flag that indicates interiors are supported.
CC_NONE
A curve capabilities flag that indicates curves are not supported.
CC_PIE
A curve capabilities flag that indicates pie wedge shapes are supported.
CC_ROUNDRECT
A curve capabilities flag that indicates rounded rectangles are supported.
CC_STYLED
A curve capabilities flag that indicates styled lines are supported.
CC_WIDE
A curve capabilities flag that indicates wide lines are supported.
CC_WIDESTYLED
A curve capabilities flag that indicates wide styled lines are supported.
CP_NONE
A clipping capabilities flag that indicates clipping of output is not supported.
CP_RECTANGLE
A clipping capabilities flag that indicates output is clipped to rectangles.
CP_REGION
A clipping capabilities flag that indicates output is clipped to Regions.
DESKTOPHORZRES
The desktop's horizontal resolution.
DESKTOPVERTRES
The desktop's vertical resolution.
DT_CHARSTREAM
The device technology flag for a character stream.
DT_DISPFILE
The device technology flag for a display file.
DT_METAFILE
The device technology flag for a metafile.
DT_PLOTTER
The device technology flag for a vector plotter (typically used in CAD).
DT_RASCAMERA
The device technology flag for a raster camera.
DT_RASDISPLAY
The device technology flag for a raster display.
DT_RASPRINTER
The device technology flag for a raster printer.
LC_INTERIORS
A line capabilities flag that indicates interiors are supported.
LC_MARKER
A line capabilities flag that indicates marker lines are supported.
LC_NONE
A line capabilities flag that indicates lines are not supported.
LC_POLYLINE
A line capabilities flag that indicates polylines are supported.
LC_POLYMARKER
A line capabilities flag that indicates polylinemarkers are supported.
LC_STYLED
A line capabilities flag that indicates styled lines are supported.
LC_WIDE
A line capabilities flag that indicates wide lines are supported.
LC_WIDESTYLED
A line capabilities flag that indicates wide styled lines are supported.
PC_INTERIORS
A polygonal capabilities flag that indicates interiors are supported.
PC_NONE
A polygonal capabilities flag that indicates polygonals are not supported.
PC_PATHS
A polygonal capabilities flag that indicates paths are supported.
PC_POLYGON
A polygonal capabilities flag that indicates polygons are supported.
PC_POLYPOLYGON
A polygonal capabilities flag that indicates poly-polygons are supported.
PC_RECTANGLE
A polygonal capabilities flag that indicates rectangles are supported.
PC_SCANLINE
A polygonal capabilities flag that indicates scan lines are supported.
PC_STYLED
A polygonal capabilities flag that indicates styled borders are supported.
PC_TRAPEZOID
A polygonal capabilities flag that indicates trapezoids are supported.
PC_WIDE
A polygonal capabilities flag that indicates wide borders are supported.
PC_WIDESTYLED
A polygonal capabilities flag that indicates wide styled borders are supported.
PC_WINDPOLYGON
A polygonal capabilities flag that indicates winding polygonals are supported.
RC_BANDING
A raster capabilities flag that indicates the device requires banding support.
RC_BIGFONT
A raster capabilities flag that indicates the device supports fonts greater than 64K.
RC_BITBLT
A raster capabilities flag that indicates the device can transfer bitmaps.
RC_BITMAP64
A raster capabilities flag that indicates the device can support bitmaps larger than 64K.
RC_DEVBITS
A raster capabilities flag that indicates the device supports device bitmaps.
RC_DI_BITMAP
A raster capabilities flag that indicates the device supports setDIBits and getDIBits Windows functions.
RC_DIBTODEV
A raster capabilities flag that indicates the device supports the SetDIBitsToDevice and getDIBitsToDevice Windows function.
RC_FLOODFILL
A raster capabilities flag that indicates the device supports flood fill operations.
RC_GDI20_OUTPUT
A raster capabilities flag that indicates the device supports Windows version 2.0 features.
RC_GDI20_STATE
A raster capabilities flag that indicates the device includes a state block in the device context.
RC_NONE
A raster capabilities flag that indicates the device has no raster capabilities.
RC_OP_DX_OUTPUT
A raster capabilities flag that indicates the device supports device opaque and dx arrays.
RC_PALETTE
A raster capabilities flag that specifies a palette-based device.
RC_SAVEBITMAP
A raster capabilities flag that indicates the device can save bitmaps locally.
RC_SCALING
A raster capabilities flag that indicates the device supports scaling.
RC_STRETCHBLT
A raster capabilities flag that indicates the device supports StretchBlt operations.
RC_STRETCHDIB
A raster capabilities flag that indicates the device supports the StretchDIBits Windows function.
TC_CP_STROKE
A text capabilities flag that indicates the device can clip device fonts to a pixel boundary.
TC_CR_90
A text capabilities flag that indicates 90-degree character rotation is supported. Fonts are rotated only 90 degrees at a time.
TC_CR_ANY
A text capabilities flag that indicates any degree character rotation is supported.
TC_EA_DOUBLE
A text capabilities flag that indicates the device can make device fonts bold. If this bit is not set for printer drivers, the GDI (graphics device interface) attempts to create bold device fonts by printing them twice.
TC_IA_ABLE
A text capabilities flag that indicates the device can make device fonts italic. If this bit is not set, the GDI assumes that italics are not available.
TC_OP_CHARACTER
A text capabilities flag that indicates the device can place device fonts at any pixel location. This is required for any device with device fonts.
TC_OP_STROKE
A text capabilities flag that indicates the device can omit any stroke of a device font.
TC_RA_ABLE
A text capabilities flag that indicates that the GDI should enumerate any raster or TrueType fonts that are available for this device in response to a call to the EnumFonts or EnumFontFamilies Microsoft® Windows® functions. If this bit is not set, GDI-supplied raster or TrueType fonts are not enumerated when these functions are called.
TC_RESERVED
A reserved text capabilities flag.
TC_SA_CONTIN
A text capabilities flag that indicates the device can scale device fonts by any amount, but still preserve the x and y ratios.
TC_SA_DOUBLE
A text capabilities flag that indicates can double the size of device fonts.
TC_SA_INTEGER
A text capabilities flag that the device can scale device fonts in any integer multiple.
TC_SCROLLBLT
A text capabilities flag that indicates text scrolling is not performed with blitting operations.
TC_SF_X_YINDEP
A text capabilities flag that indicates the device can scale device fonts separately in x and y directions.
TC_SO_ABLE
A text capabilities flag that indicates the device can strikeout device fonts. If this bit is not set, GDI creates strikethroughs for device fonts.
TC_UA_ABLE
A text capabilities flag that indicates the device can underline device fonts. If this bit is not set, the GDI creates underlines for device fonts.
TC_VA_ABLE
A text capabilities flag that indicates that GDI should enumerate any vector fonts available for this device in response to a call to the EnumFonts or EnumFontFamilies Windows functions. This is significant for vector devices only (that is, for plotters). Display drivers (which must be able to use raster fonts) and raster printer drivers always enumerate vector fonts, because GDI rasterizes vector fonts before sending them to the driver.
VREFRESH
The current vertical refresh rate of the display device.


Class DeviceException

public class DeviceException extends Exception
{
  // Constructors
  public DeviceException(String msg);
}

Signals that a com.ms.awt.Device-related exception has occurred.

Exception
  |
  +--DeviceException

Constructors

DeviceException

public DeviceException(String msg);

Creates a DeviceException object with a String that describes the exception in detail.

Parameter | Description
msg | The detailed message.


Class DisplayDevice

public class DisplayDevice extends Device
{
  // Constructors
  public DisplayDevice(Graphics g) throws DeviceException;

  // Methods
  public int getBltAlignment();
  public Dimension getDesktopResolution();
  public int getVerticalRefresh();
}

This class handles display devices.

Device
  |
  +--DisplayDevice

Constructors

DisplayDevice

public DisplayDevice(Graphics g) throws DeviceException;

Creates a display device object.

Parameter | Description
g | The graphics object that the device is created for.

Exceptions:

com.ms.awt.DeviceException if the graphics object is not an instance of the FxGraphics or the GraphicsX class.

Methods

getBltAlignment

public int getBltAlignment();

Retrieves the blit alignment.

Return Value:

Returns the blit alignment.

getDesktopResolution

public Dimension getDesktopResolution();

Retrieves the display device desktop resolution.

Return Value:

Returns the dimensions of the desktop resolution. This is commonly one of the resolutions shown in the following table.
480 x 640, 600 x 800, 768 x 1024, 864 x 1152, or 1024 x 1280

getVerticalRefresh

public int getVerticalRefresh();

Retrieves the device vertical refresh rate.

Return Value:

Returns the vertical refresh rate (in MHz).


Class FocusEvent

public class FocusEvent extends java.awt.event.FocusEvent
{
  // Constructors
  public FocusEvent(Component source, int id, Component other,
        boolean temporary);
  public FocusEvent(Component source, int id, Component other);

  // Methods
  public Component getOtherComponent();
  public String paramString();
}

This class manages component-level focus events. This class is similar to the java.awt.event.FocusEvent class, except that it also incorporates the target component of a component focus event.

FocusEvent
  |
  +--FocusEvent

Constructors

FocusEvent

public FocusEvent(Component source, int id, Component other,
        boolean temporary);

Creates a FocusEvent object by using the component that received the focus, the component that lost focus, the identifier of the focus event, and whether the focus event is temporary or permanent.

Parameter | Description
source | The component that generates the event.
other | The target component.
id The identifier of the focus event. This may be either FOCUS_LOST or FOCUS_GAINED.

If the identifier is FOCUS_GAINED, the other component is the component that loses focus. If the identifier is FOCUS_LOST, the other component is the component that gains focus. However, if the application is currently gaining or losing focus, the identifier may be null.

temporary | Set to true if the focus change is a temporary one. Set to false if the focus change is a permanent one.

FocusEvent

public FocusEvent(Component source, int id, Component other);

Creates a FocusEvent object by using the component that received the focus, the component that lost focus, and the identifier of the focus event. A FocusEvent created with this constructor is permanent (by default).

Parameter | Description
source | The component that generates the event.
other | The target component.
id The identifier of the focus event. This may be either FOCUS_LOST or FOCUS_GAINED.

If the identifier is FOCUS_GAINED, the other component is the component that loses focus. If the identifier is FOCUS_LOST, the other component is the component that gains focus. However, if the application is currently gaining or losing focus, the identifier may be null.

Methods

getOtherComponent

public Component getOtherComponent();

Retrieves the target component involved in the focus shift.

Return Value:

Returns the other component involved in the focus change (if any).

paramString

public String paramString();

Describes the focus event.

Return Value:

Returns a string that describes the focus event ("FOCUS_LOST other= other", for example).


Class FontMetricsX

public class FontMetricsX extends FxFontMetrics
{
}

This class provides an extended font metrics implementation specific to the Microsoft Win32 VM for Java. For more information on the methods in this class, see the com.ms.fx.FxFontMetrics class.

FxFontMetrics
  |
  +--FontMetricsX


Class FontX

public class FontX extends FxFont
{
  // Fields
  public static final int EMBEDDED;
  public static final int OUTLINE;
  public static final int STRIKEOUT;
  public static final int UNDERLINE;

  // Constructors
  public FontX();
  public FontX(String name, int style, int size);
  public FontX(String name, int style, int size, boolean bEmbed);
  public FontX(String name, int style, int size, int xFlags);

  // Methods
  public static FontX chooseFont(Component c);
  public static FontX chooseFont(Component c, FontX f);
  public boolean equals(Object obj);
  public static String[] getAttributeList();
  public static String[] getAttributeList(String face);
  public int getFlags();
  public static int getFlagsVal(String face, String attribute);
  public static Font getFont(String face, int style, int size,
        int flags);
  public static Font getFont(String face, Vector v, int size);
  public static String[] getFontList();
  public static int getStyleVal(String face, String attribute);
  public boolean isTypeable(int language);
  public static boolean matchFace(String face);
  public String toString();
}

This class creates a font object that defines the font family, font face, style, and size. The FontX class also supports TrueType fonts.

With JDK 1.1, fonts are mapped with a font properties file, and you can obtain different fonts by editing this file. However, the Microsoft implementation does not support this type of font association. You can obtain desired fonts with FontX objects; they are created with Win32 font names.

FxFont
  |
  +--FontX

Constructors

FontX

public FontX();

Creates a nondescript font (12-point Dialog).

FontX

public FontX(String name, int style, int size);

Creates a new font with the specified name, style, and point size. This constructor is used to access system fonts on the Microsoft® Win32® platform not otherwise available in Java (for example, the "symbol" font).

Parameter | Description
name | The name of the font face.
style The font style, which can be a combination of the values shown in the following table.
BOLD ITALIC PLAIN
size | The point size of the font.

FontX

public FontX(String name, int style, int size, boolean bEmbed);

Creates a new font with the specified name, style, and point size; specifies whether the font is embedded.

Parameter | Description
name | The name of the font face.
style The font style, which can be a combination of the values shown in the following table.
BOLD ITALIC PLAIN
size | The point size of the font.
bEmbed | Set to true if the font is embedded, false otherwise.

FontX

public FontX(String name, int style, int size, int xFlags);

Creates an extended font.

Parameter | Description
name | The name of the font face.
style The font style, which can be a combination of the values shown in the following table.
BOLD ITALIC PLAIN
size | The point size of the font.
xFlags An extended style, which can be one of the values shown in the following table.
EMBEDDED
UNDERLINE
STRIKEOUT
OUTLINE

Methods

chooseFont

public static FontX chooseFont(Component c);

Note This method is obsolete. It has been replaced by the UIFontDialog class.

Return Value:

Returns a FontX object or null if the user cancelled the dialog box by selecting the Cancel button.

Parameter | Description
c | A component that owns the dialog box (and subsequently is blocked until the dialog box is closed).

chooseFont

public static FontX chooseFont(Component c, FontX f);

Note This method is obsolete. It has been replaced by the UIFontDialog class.

Return Value:

Returns a FontX object or null if the user cancelled the dialog box by selecting the Cancel button.

Parameter | Description
c | A component that owns the dialog box (and subsequently is blocked until the dialog box is closed).
f | The FontX object to use as the default.

equals

public boolean equals(Object obj);

Checks that the argument is not null (is either a Font or a FontX object) and has the same name, same style, and same point size as this FontX object.

Return Value:

Returns true if the objects are equal; otherwise, returns false.

Parameter | Description
obj | The object to be compared with the FontX object.

getAttributeList

public static String[] getAttributeList();

Retrieves a list of the attributes that the current font supports.

Return Value:

Returns an array of strings describing the attributes the font supports.

getAttributeList

public static String[] getAttributeList(String face);

Retrieves a list of the attributes this font supports, given the font face.

Return Value:

Returns an array of strings describing the attributes the font supports.

Parameter | Description
face | The current font face.

getFlags

public int getFlags();

Retrieves the extended flags of a FontX object.

Return Value:

Returns a one or a combination of these extended styles: EMBEDDED, STRIKEOUT, UNDERLINE, and OUTLINE.

getFlagsVal

public static int getFlagsVal(String face, String attribute);

Retrieves a value for the flags associated with the given face.

Return Value:

Returns a value for the face name flags.

Parameter | Description
face | The current font face.
attribute | A string that contains the attributes (for example, "Rotatable") of the font.

getFont

public static Font getFont(String face, int style, int size, int flags);

Retrieves a font if an exact match is made, given the font face, style, size, and any specified flags.

Return Value:

Returns the Font that is the exact match to the given parameters.

Parameter | Description
face | The font face.
style | The font style.
size | The font size, in points.
flags One or more of the following font flags:
EMBEDDED
STRIKEOUT
UNDERLINE
OUTLINE

getFont

public static Font getFont(String face, Vector v, int size);

Retrieves a font if an exact match is made, given the font face, vector, and size.

Return Value:

Returns the Font that is the exact match to the given parameters.

Parameter | Description
face | The font face.
v | A list of style names.
size | The font size, in points.

getFontList

public static String[] getFontList();

Retrieves a list of the names of the font faces available.

Return Value:

Returns a string array containing the names of available font faces.

getStyleVal

public static int getStyleVal(String face, String attribute);

Retrieves a value for the style associated with the given face.

Return Value:

Returns a value for the face name style.

Parameter | Description
face | The current font face.
attribute | A string that contains the attributes of the font (for example, "Rotatable").

isTypeable

public boolean isTypeable(int language);

Checks whether the font can be typed in the given language.

Return Value:

Returns true if the font can be typed; otherwise, returns false.

Parameter | Description
language | The identifier of the language to be checked.

matchFace

public static boolean matchFace(String face);

Compares the current font face to the specified face.

Return Value:

Returns true if the current face is the same as the specified face; otherwise, returns false.

Parameter | Description
face | The name of the font face to compare to the current font face.

toString

public String toString();

Returns a string that specifies the family, font face, style, and size of the given font.

Return Value:

Returns a string having the following format:

class[family=family-name,name=font-name,style=bold/italic,size=size]

Fields

EMBEDDED
Indicates the new font should be linked to a privately embedded font.

Note This is only significant for fonts that are loaded by non-Java objects. Fonts that are loaded by Java objects are automatically embedded.

OUTLINE
Indicates that the text drawn by using the new font should be drawn by using the outline of the glyph. This is only supported by certain fonts in the system, and only GraphicsX will support this feature. Trying to draw outline fonts using a Win32Graphics object will result in the glyph being drawn normally.
STRIKEOUT
Indicates that text drawn using the new font should be struckthrough.
UNDERLINE
Indicates that text drawn using the new font should be underlined.


Class GraphicsX

public class GraphicsX extends FxGraphics implements
            PeerConstants, PaintSurface
{
  // Constructors
  public GraphicsX(int hdc);

  // Methods
  public void drawCharsWithoutFxFont(char data[], int offset,
        int length, int x, int y, Rectangle optionRect,
        int options, int dx[], int dy[]);
  public void drawOutlinePolygon(int xOrig, int yOrig,
        OutlinePolygon op);
  public void drawPixels(int[] pels, int len);
  public void drawScanLines(boolean xChanging, int[] points,
        int offset, int nPoints);
  public void drawStringWithoutFxFont(String str,int x, int y,
        Rectangle optionRect, int options, int[] dx,int[] dy);
  public Device getDevice() throws DeviceException;
  public GlyphOutline getGlyphOutline(char ch);
  public int gethdc();
  public Point getTranslation();
  public void setTextBackgroundColor(Color c);
}

This class provides a graphics implementation specifically for the Microsoft VM. This class is not used directly in applets or applications, and is not cross-platform.

The following methods are methods implemented only for the Microsoft Virtual Machine. All other graphics methods are defined in FxGraphics and the java.awt.Graphics class.

FxGraphics
  |
  +--GraphicsX

Constructors

GraphicsX

public GraphicsX(int hdc);

Creates a graphics object for a user-supplied display context.

Parameter | Description
hdc | The display context to create the graphics object for.

Methods

drawCharsWithoutFxFont

public void drawCharsWithoutFxFont(char data[], int offset, int length, int
        x, int y, Rectangle optionRect, int options, int dx[], int dy[]);

Uses a native peer graphics object to draw the given character array using the supplied advancement lists. This method is used by an FxFont object if it needs to be able to draw and then process a character array.

Return Value:

No return value.

Parameter | Description
str | The string to draw.
x | The x coordinate of the point where the string is drawn.
y | The y coordinate of the point where the string is drawn.
optionRect | The optional rectangle used for clipping and opaquing.
options | The options for this method.
dx | An array of destination x values.
dy | An array of destination y values.

See Also: com.ms.fx.FxGraphics

drawOutlinePolygon

public void drawOutlinePolygon(int xOrig, int yOrig, OutlinePolygon op);

Draws an outline polygon.

Return Value:

No return value.

Parameter | Description
xOrig | The horizontal starting point for the shape.
yOrig | The vertical starting point for the shape.
op | The OutlinePolygon to draw.

See Also: com.ms.fx.OutlinePolygon

drawPixels

public void drawPixels(int[] pels, int len);

Draws a given list of pixels.

Return Value:

No return value.

Parameter | Description
pels | An array of pixels.
len | The length of the array.

drawScanLines

public void drawScanLines(boolean xChanging, int[] points, int offset,
        int nPoints);

Draws fast lines, either horizontally or vertically.

Return Value:

No return value.

Parameter | Description
xChanging | The direction that the line is drawn, either vertically or horizontally.
points | An array of points.
offset | The offset to use.
nPoints | The number of points in the array.

drawStringWithoutFxFont

public void drawStringWithoutFxFont(String str,int x, int y,
        Rectangle optionRect, int options, int[] dx,int[] dy);

Uses a native peer graphics object to draw the given string using the supplied advancement lists. This method is used by an FxFont object if it needs to be able to draw and then process a string.

Return Value:

No return value.

Parameter | Description
str | The string to draw.
x | The x coordinate of the point where the string is drawn.
y | The y coordinate of the point where the string is drawn.
optionRect | The optional rectangle used for clipping and opaquing.
options | The options for this method.
dx | An array of destination x values.
dy | An array of destination y values.

See Also: com.ms.fx.FxGraphics

getDevice

public Device getDevice() throws DeviceException;

Retrieves an an instance of a device class that the graphics object draws on.

Return Value:

Returns an instance of the either the DisplayDevice or the PrinterDevice class.

Exceptions:

com.ms.awt.DeviceException

getGlyphOutline

public GlyphOutline getGlyphOutline(char ch);

Retrieves the outline of a character in the currently selected font.

Note This method is obsolete. Use the FxOutlineFont class.

Return Value:

Returns an OutlinePolygon object. If the font is not an outline font, then null is returned.

Parameter | Description
ch | The character whose outline is requested.

gethdc

public int gethdc();

Retrieves the Win32 display context handle. This is useful when the graphics object is used with a Microsoft DirectDraw surface, printer or ActiveX object (graphics objects created for components do not have consistent HDC values).

Return Value:

Returns the Win32 display context handle.

getTranslation

public Point getTranslation();

Retrieves the origin Point used in a translate operation on a graphics context, after the translation is complete.

Return Value:

Returns the origin for the translation.

setTextBackgroundColor

public void setTextBackgroundColor(Color c);

Sets the text background color. This is used for opaquing text.

Return Value:

No return value.

Parameter | Description
c | The Color to set the text background to.


Class ImageX

public class ImageX extends com.ms.awt.image.Image
{
  // Constructors
  public ImageX(Component c, int w, int h);
  public ImageX(ImageProducer producer);

  // Methods
  public int getCursor(int x, int y);
  public Graphics getGraphics();
  public int getIcon();
}

This class encapsulates an extended image object.

This class provides the getCursor and getIcon methods, which retrieve Win32 images for cursors and icons, respectively.

Image
  |
  +--ImageX

Constructors

ImageX

public ImageX(Component c, int w, int h);

Creates an image for offscreen rendering to be used with the specified Component.

Parameter | Description
c | The Component that uses the image.
w | The width of the image (in pixels).
h | The height of the image (in pixels).

ImageX

public ImageX(ImageProducer producer);

Creates an image from an ImageProducer object.

Parameter | Description
producer | The ImageProducer object to create the image for.

Methods

getCursor

public int getCursor(int x, int y);

Retrieves an ImageRepresentation of a native Win32 cursor based on the current ImageX object.

Return Value:

Returns the handle of a native cursor.

Parameter | Description
x | The x coordinate of the cursor's hot spot.
y | The y coordinate of the cursor's hot spot.

getGraphics

public Graphics getGraphics();

Creates a graphics context for drawing to an off-screen image.

Return Value:

Returns a Graphics object.

getIcon

public int getIcon();

Retrieves an ImageRepresentation of a native Win32 icon based on the current ImageX object.

Return Value:

Returns the handle of a native icon.


Class Mat2

public class Mat2
{
  // Fields
  public float em11;
  public float em12;
  public float em21;
  public float em22;
}

This class defines a transformation matrix that can be used with outline font methods.

The identity matrix produces a transformation, in which the transformed graphical object is identical to the source object. In the identity matrix, the value of em11 and em22 is 1. The value of em12 and em21 is 0.

Fields

em11
The M11 component of a 3-by-3 transformation matrix.
em12
The M12 component of a 3-by-3 transformation matrix.
em21
The M21 component of a 3-by-3 transformation matrix.
em22
The M22 component of a 3-by-3 transformation matrix.


Class MenuBarX

public class MenuBarX extends MenuBar implements MenuXConstants
{
  // Constructors
  public MenuBarX( MenuItemX items[], int nItems);
  public MenuBarX( MenuItemX items[], int nItems, Applet theApp,
        String param);
  public MenuBarX( MenuItemX items[], int nItems, String params[]);

  // Methods
  public int getItemID(String s);
}

This class is obsolete. This class has been replaced by the UIMenu implementation in the com.ms.ui package, which includes the UIMenuLauncher, UIMenuItem, and UIMenuList classes.

MenuBar
  |
  +--MenuBarX

Constructors

MenuBarX

public MenuBarX( MenuItemX items[], int nItems);

Note This constructor is obsolete.

MenuBarX

public MenuBarX( MenuItemX items[], int nItems, Applet theApp,
        String param);

Note This constructor is obsolete.

MenuBarX

public MenuBarX( MenuItemX items[], int nItems, String params[]);

Note This constructor is obsolete.

Methods

getItemID

public int getItemID(String s);

Note This method is obsolete.


Class MenuItemX

public class MenuItemX extends CheckboxMenuItem
{
  // Constructors
  public MenuItemX(String s, int i1, int i2);

  // Methods
  public synchronized void addNotify();
  public void Check(boolean val);
  public int getID();
  public boolean isChecked();
  public void setState(boolean t);
}

This class is obsolete. This class has been replaced by the UIMenu implementation in the com.ms.ui package, which includes the UIMenuLauncher, UIMenuItem, and UIMenuList classes.

CheckboxMenuItem
  |
  +--MenuItemX

Constructors

MenuItemX

public MenuItemX(String s, int i1, int i2);

Note This constructor is obsolete.

Methods

addNotify

public synchronized void addNotify();

Note This method is obsolete.

Check

public void Check(boolean val);

Note This method is obsolete.

getID

public int getID();

Note This method is obsolete.

isChecked

public boolean isChecked();

Note This method is obsolete.

setState

public void setState(boolean t);

Note This method is obsolete.


Class MenuX

public class MenuX extends Menu implements MenuXConstants
{
  // Constructors
  public MenuX( String theLabel );

  // Methods
  public boolean CheckMenuItem(int i, int flags);
  public boolean CheckMenuItem( String s, int flags);
  public int getItemID(String s);
}

This class is obsolete. This class has been replaced by the UIMenu implementation in the com.ms.ui package, which includes the UIMenuLauncher, UIMenuItem, and UIMenuList classes.

Menu
  |
  +--MenuX

Constructors

MenuX

public MenuX( String theLabel );

Note This constructor is obsolete.

Methods

CheckMenuItem

public boolean CheckMenuItem(int i, int flags);

Note This method is obsolete.

CheckMenuItem

public boolean CheckMenuItem( String s, int flags);

Note This method is obsolete.

getItemID

public int getItemID(String s);

Note This method is obsolete.


Class PointFx

public class PointFx
{
  // Fields
  public float x;
  public float y;

  // Constructors
  public PointFx(float newX, float newY);
  public PointFx();
}

This class defines the x and y coordinates of a point on the outline of a TrueType character.

Constructors

PointFx

public PointFx(float newX, float newY);

Creates an initialized point object.

Parameter | Description
newX | The x coordinate.
newY | The y coordinate.

PointFx

public PointFx();

Creates an uninitialized point object.

Fields

x
The x coordinate of a point on the outline of a TrueType character.
y
The y coordinate of a point on the outline of a TrueType character.


Class PrinterDevice

public class PrinterDevice extends Device
{
  // Constructors
  public PrinterDevice(Graphics g) throws DeviceException;

  // Methods
  public Dimension getPhysicalOffset();
  public Dimension getPhysicalSize ();
  public Dimension getScalingFactor();
}

This class handles printer devices.

Device
  |
  +--PrinterDevice

Constructors

PrinterDevice

public PrinterDevice(Graphics g) throws DeviceException;

Creates a printer device object.

Parameter | Description
g | The graphics object that the device is created for.

Exceptions:

com.ms.awt.DeviceException if the graphics object is not an instance of the FxGraphics or the GraphicsX extended graphics class.

Methods

getPhysicalOffset

public Dimension getPhysicalOffset();

Retrieves the physical offset of the printer device.

Return Value:

Returns the Dimension of the offset.

getPhysicalSize

public Dimension getPhysicalSize ();

Retrieves the physical size of the device.

Return Value:

Returns the Dimension of the device.

getScalingFactor

public Dimension getScalingFactor();

Retrieves the scaling factor.

Return Value:

Returns the scaling factor.


Class WDragSession

public class WDragSession extends DragHelper implements
            DragSession
{
  // Methods
  public static void beginDrag(TransferSession session);
  public static void beginDrag(MetaObject data, int available);
  public static void beginDrag(MetaObject data, int available, int preferred);
  public static void beginDrag(DragSource source, MetaObject data,
        int available);
  public static void beginDrag(DragSource source, MetaObject data,
        int available, int preferred);
  public static void beginDrag(DragSource source, TransferSession session);
}

This class is an extension of the DragHelper class. It implements the drag-and-drop APIs presented in the com.ms.object and com.ms.object.dragdrop Java packages for AWT objects. The dragdrop APIs work for both AWT and Microsoft AFC, but are implemented slightly different. The following example shows how you can implement drag-and-drop functionality using AWT and a WDragSession object.

import java.awt.*;
import com.ms.object.*;
import com.ms.object.dragdrop.*;
import com.ms.awt.WDragSession;

class DragMeAWT extends Canvas
{
//...
    public boolean mouseDown(Event e, int x, int y)
    {
        ObjectBag data = new ObjectBag();
        data.addObject(null, null, Color.red);
        WDragSession.beginDrag(data, Transfer.COPY | Transfer.LINK);

        return true;
    }
}

The same functionality is achieved with the UIDragDrop class when you use AFC.

import com.ms.ui.*;
import com.ms.object.*;
import com.ms.object.dragdrop.*;
import java.awt.Color;

class DragMeAFC extends UICanvas
{
//...
    public boolean mouseDown(Event e, int x, int y)
    {
        ObjectBag data = new ObjectBag();
        data.addObject(null, null, Color.red);
        UIDragDrop.beginDrag(data, Transfer.COPY | Transfer.LINK);

        return true;
    }
}

Use the beginDrag methods to start a drag-and-drop operation. All beginDrag methods act on two parameters, a DragSource object, and a TransferSession. Several of the beginDrag methods accept various TransferSession constructor parameters to simplify drag session creation.

DragHelper
  |
  +--WDragSession

Methods

beginDrag

public static void beginDrag(TransferSession session);

Starts a drag session by obtaining a TransferSession object and acting on it. The drag session has an undefined DragSource object. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
session | The TransferSession object that is used during the current drag operation.

beginDrag

public static void beginDrag(MetaObject data, int available);

Starts a drag session by obtaining a TransferSession object and acting on it. The drag session has an undefined DragSource object. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
data | A MetaObject used to create a TransferSession object. It is used in the current drag session.
available | The transfer effects that are available for the created TransferSession. These include NONE, COPY, MOVE, and LINK.

beginDrag

public static void beginDrag(MetaObject data, int available, int preferred);

Starts a drag session by obtaining a TransferSession object and acting on it. The drag session has an undefined DragSource object. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
data | A MetaObject used to create a TransferSession object. It is used in the current drag session.
available | The transfer effects that are available for the created TransferSession. These include NONE, COPY, MOVE, and LINK.
preferred | The preferred transfer effects for the current TransferSession.

beginDrag

public static void beginDrag(DragSource source, MetaObject data,
        int available);

Starts a drag session by obtaining a TransferSession object and acting on it. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
source | A DragSource object that provides custom cursor behavior for the drag session.
data | A MetaObject used to create a TransferSession object. It is used in the current drag session.
available | The transfer effects that are available for the created TransferSession. These include NONE, COPY, MOVE, and LINK.

beginDrag

public static void beginDrag(DragSource source, MetaObject data,
        int available, int preferred);

Starts a drag session by obtaining a TransferSession object and acting on it. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
source | A DragSource object that provides custom cursor behavior for the drag session.
data | A MetaObject used to create a TransferSession object. It is used in the current drag session.
available | The transfer effects that are available for the created TransferSession. These include NONE, COPY, MOVE, and LINK.
preferred | The preferred transfer effects for the current TransferSession.

beginDrag

public static void beginDrag(DragSource source, TransferSession session);

Starts a drag session by obtaining a TransferSession object and acting on it. Drag-and-drop TransferSession implementations must support Transfer.MOVE.

Return Value:

No return value.

Parameter | Description
source | A DragSource object that provides custom cursor behavior for the drag session.
session | The TransferSession object that is used during the current drag operation.


Class Win32SystemResourceDecoder

public class Win32SystemResourceDecoder extends Win32ResourceDecoder
{
  // Constructors
  public Win32SystemResourceDecoder() throws FileNotFoundException;
  public Win32SystemResourceDecoder(String filename)
        throws FileNotFoundException;

  // Methods
  public byte[] getBytes(int type, int strId)
        throws ResourceFormattingException;
  public byte[] getBytes(int type, String name)
        throws ResourceFormattingException;
  public UIDialog getDialog(int dlgId);
  public UIDialog getDialog(String dlgname);
  public int getLocale();
  public String getString(int strId);
  public void populateDialog(UIDialog dlg, int dlgId, int language);
  public void populateDialog(UIDialog dlg, String dlgname,
        int language);
  public void setLocale(int locale);
}

This class is used to utilize Win32 system resource (.res) files.

Win32ResourceDecoder
  |
  +--Win32SystemResourceDecoder

Constructors

Win32SystemResourceDecoder

public Win32SystemResourceDecoder() throws FileNotFoundException;

Creates a resource decoder object that attaches to the Microsoft VM for Java resource handler (vmhelper.dll). This is the resource handler the object obtains resources from.

Exceptions:

FileNotFoundException if vmhelper.dll cannot be found.

Win32SystemResourceDecoder

public Win32SystemResourceDecoder(String filename)
        throws FileNotFoundException;

Creates a resource decoder object that attaches to the user specified resource handler.

Parameter | Description
filename | The resource handler file that the object attaches to and obtains resources from.

Exceptions:

FileNotFoundException if filename is invalid or cannot be found.

Methods

getBytes

public byte[] getBytes(int type, int strId)
        throws ResourceFormattingException;

Retrieve a byte block of the specified resource type, with the given identifier.

Return Value:

Returns a bytes block that contains the resource type.

Parameter | Description
type | The resource type.
srtId | The resource identifier.

Exceptions:

ResourceFormattingException if the resource type or identifier are invalid.

getBytes

public byte[] getBytes(int type, String name)
        throws ResourceFormattingException;

Retrieve a byte block of the specified resource type, with the given name.

Return Value:

Returns a bytes block that contains the resource type.

Parameter | Description
type | The resource type.
name | The resource name.

Exceptions:

ResourceFormattingException if the resource type or identifier are invalid.

getDialog

public UIDialog getDialog(int dlgId);

Retrieves a UIDialog object with the specified dialog identifier from native resources.

Return Value:

Returns a UIDialog object, or null if one could not be created.

Parameter | Description
dlgId | The dialog identifier.

getDialog

public UIDialog getDialog(String dlgname);

Retrieves a UIDialog object with the specified name from native resources.

Return Value:

Returns a UIDialog object, or null if one could not be created.

Parameter | Description
dlgname | The dialog name.

getLocale

public int getLocale();

Retrieves the current locale.

Return Value:

Returns the current locale. Currently, this methods returns 0.

See Also: setLocale

getString

public String getString(int strId);

Retrieves a string resource with the specified string identifier.

Return Value:

Returns the requested string resource, or null if one could not be created.

Parameter | Description
strId | The identifier of the string resource.

populateDialog

public void populateDialog(UIDialog dlg, int dlgId, int language);

Fills an existing dialog box, in the current locale with the specified identifier, with the data and/or controls as specified in the resource. This is useful for classes that are derived from UIDialog.

Return Value:

No return value.

Parameter | Description
dlg | The dialog object to populate.
dlgId | The identifier of the dialog resource containing the components.
language | The language of the resources.

Remarks:

Currently, this method is not implemented.

populateDialog

public void populateDialog(UIDialog dlg, String dlgname, int language);

Fills an existing dialog box, in the current locale with the specified name, with the data and/or controls as specified in the resource. This is useful for classes which are derived from UIDialog.

Return Value:

No return value.

Parameter | Description
dlg | The dialog object to populate.
dlgname | The name of the dialog resource containing the components.
language | The language of the resources.

Remarks:

Currently, this method is not implemented.

setLocale

public void setLocale(int locale);

Sets the current locale.

Return Value:

No return value.

Parameter | Description
locale | The current locale.

Remarks:

Currently, this method is not implemented.

See Also: getLocale


Class WPrintGraphics

public class WPrintGraphics extends GraphicsX implements
            PrintGraphics
{
  // Constructors
  public WPrintGraphics(WPrintJob pjob);

  // Methods
  public Graphics create();
  public void dispose();
  public PrintJob getPrintJob();
}

This class encapsulates a print graphics context for a printable page.

FxGraphics
  |
  +--GraphicsX
    |
    +--WPrintGraphics

Constructors

WPrintGraphics

public WPrintGraphics(WPrintJob pjob);

Creates a print graphics object based on a WPrintJob object.

Parameter | Description
pjob | The WPrintJob object that the new object is based on.

Methods

create

public Graphics create();

Creates a new WPrintGraphics object based on the current one.

Return Value:

Returns a new WPrintGraphics object.

dispose

public void dispose();

Disposes the graphics object after it is no longer being referenced.

Return Value:

No return value.

getPrintJob

public PrintJob getPrintJob();

Retrieves the PrintJob associated with the print graphics object.

Return Value:

Returns the PrintJob associated with the print graphics object.


Class WPrintJob

public class WPrintJob extends PrintJob
{
  // Constructors
  public WPrintJob(String title) throws IOException;

  // Methods
  public void end();
  public Graphics getGraphics();
  public Dimension getPageDimension();
  public int getPageResolution();
  public boolean lastPageFirst();
  public void setPageDimensions(int width, int height);
}

This class creates Win32 WPrintJob objects that handle printing. This class is similar to the java.awt.PrintJob class, but includes the setPageDimensions method and other improvements.

Printing in Java is performed with this and other printing classes, and with the java.awt.Toolkit class. The following example shows how to use Toolkit to print from an applet.

Toolkit tools = getToolkit();
WPrintJob wpj = (WPrintJob)tools.getPrintJob(null, "Print?", null);
if(wpj != null)
{
     Graphics g = wpj.getGraphics();
     if(g != null)
     {
          paint(g);
          g.dispose();
     }
wpj.end();
}
PrintJob
  |
  +--WPrintJob

Constructors

WPrintJob

public WPrintJob(String title) throws IOException;

Creates a Win32 print job object with the specified title.

Parameter | Description
title | The name of the print job.

Methods

end

public void end();

Ends the print job and performs cleanup operations.

Return Value:

No return value.

getGraphics

public Graphics getGraphics();

Retrieves a Graphics object that will draw to the next page. The page is flushed to the printer when the graphics object calls the dispose method.

Return Value:

Returns a Graphics object that draws to the printer.

getPageDimension

public Dimension getPageDimension();

Retrieves the dimensions of the page (in pixels).

Return Value:

Returns the Dimension of the page (in pixels). If the setPageDimensions has not been called, the Dimension object returned is a default Dimension.

getPageResolution

public int getPageResolution();

Retrieves the resolution of the page (in pixels per inch).

Return Value:

Returns the page resolution.

lastPageFirst

public boolean lastPageFirst();

Determines if the last page should be printed first.

Return Value:

Returns true if the last page should be printed first.

setPageDimensions

public void setPageDimensions(int width, int height);

Sets the logical page dimensions and enables you to effectively use a mapping mode (like GDI).

Return Value:

No return value.

Parameter | Description
width | The width of the page (in pixels).
height | The height of the page (in pixels).


Class WinEvent

public class WinEvent implements com.ms.ui.IWinEvent
{
  // Constructors
  public WinEvent();

  // Methods
  public Object getObject(int id);
  public void notify(int event, Object obj);
}

This class provides a raw API that enables Java objects to use Microsoft Active Accessibility. However, it is recommended that you use the UIWinEvent class, which provides essentially the same API and contains all the needed constants as well.

Constructors

WinEvent

public WinEvent();

Creates a new WinEvent object.

Methods

getObject

public Object getObject(int id);

Retrieves an object with a specified identifier.

Return Value:

Returns The object, or null if the identifier is invalid.

Parameter | Description
id | The identifier of the object to find.

notify

public void notify(int event, Object obj);

Generates an event notification that is propagated to any currently associated listener objects.

Return Value:

No return value.

Parameter | Description
event | The event to send.
obj | The Java object that posted the event.


Interface HeavyComponent

public interface HeavyComponent
{
  // Methods
  public boolean needsHeavyPeer();
}

This interface is implemented by Java classes that require a Microsoft® Win32® system window (an HWND) for operations that access the native operating system. Java applets and applications that interact with the native system can use this interface with a java.awt.Canvas object to request a system window.

The HeavyComponent interface is not cross-platform.

Currently, this interface only supports java.awt.Canvas objects. When a Canvas object that implements HeavyComponent is created, needsHeavyPeer is called to determine whether the Canvas object requires a Win32 window.

For example, the HeavyComponent interface is used by the Microsoft® ActiveX® component support.

Methods

needsHeavyPeer

public boolean needsHeavyPeer();

Called by the toolkit when creating the peer object for a Canvas that implements the HeavyComponent interface.

Note The HeavyComponent interface only supports java.awt.Canvas objects.

Return Value:

Returns true if the Java object requires a Win32 system window; otherwise, returns false.


Interface MenuXConstants

public interface MenuXConstants
{
  // Fields
  public final int BY_COMMAND;
  public final int BY_POSITION;
  public final int CHECKED;
  public final int ENDMENU;
  public final int POPUP;
  public final int SEPARATOR_NEXT;
  public final int UNCHECKED;
}

This interface is obsolete. This interface has been replaced by the UIMenu implementation in the com.ms.ui package, which includes the UIMenuLauncher, UIMenuItem, and UIMenuList classes.

Fields

BY_COMMAND
Note This field is obsolete.
BY_POSITION
Note This field is obsolete.
CHECKED
Note This field is obsolete.
ENDMENU
Note This field is obsolete.
POPUP
Note This field is obsolete.
SEPARATOR_NEXT
Note This field is obsolete.
UNCHECKED
Note This field is obsolete.


About com.ms.awt.peer

This package provides access to Microsoft® Win32® system-level features that are not available in the java.awt.peer package.

Interfaces

Interface ComponentPeerX
This interface is an abstract interface that extends the component peer.

Hierarchy

ComponentPeerX


Interface ComponentPeerX

public interface ComponentPeerX extends ComponentPeer
{
  // Methods
  public int gethwnd();
  public int getHwnd();
  public int getNearestHwnd();
  public int getTopHwnd();
  public boolean isWindowless();
}

This interface is an abstract interface that extends the component peer.

The ComponentPeerX interface is used (instead of com.ms.awt.WComponentPeer, for example) when accessing a peer object's HWNDs.

This support is significant for Microsoft® J/Direct™ technology, as the windowless component support for the Microsoft packages makes it more difficult to retrieve window handles (HWNDs) for Java components that interact with native Win32 code.

ComponentPeer
  |
  +--ComponentPeerX

Methods

gethwnd

public int gethwnd();

Retrieves the Win32 window handle that is directly associated with the peer's component, if any.

Return Value:

Returns the HWND of the Win32 window for this peer.

Remarks:

Both getHwnd and gethwnd methods are supported in this interface for backwards compatability.

Exceptions:

IllegalStateException if the peer does not have its own HWND and is using a parent component's HWND.

getHwnd

public int getHwnd();

Retrieves the Win32 window handle that is directly associated with the peer's component, if any.

Return Value:

Returns the HWND of the Win32 window for this peer.

Remarks:

Both getHwnd and gethwnd methods are supported in this interface for backwards compatability.

Exceptions:

IllegalStateException if the peer does not have its own HWND and is using a parent component's HWND.

getNearestHwnd

public int getNearestHwnd();

Retrieves the nearest Win32 window handle associated with a component. If the component has its own HWND, then that is returned; otherwise, the handle associated with the nearest component in the parent chain is returned.

Return Value:

Returns the HWND of the nearest Win32 window in the parent chain.

getTopHwnd

public int getTopHwnd();

Retrieves the top-level parent HWND in the parent chain. This is the outermost handle used by the system to host the component.

Return Value:

Returns the HWND of the top-level parent Win32 window in the parent chain.

isWindowless

public boolean isWindowless();

Queries a peer to determine if it is windowless. If the component is using a parent component's window handle, the component is windowless.

Return Value:

Returns true if the component is using a parent component's window handle; otherwise, returns false if the component is directly associated with an HWND.


About com.ms.com

In this topic

* COM Objects and Java

* Frequently Used Classes

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.com | Packages | Next

About com.ms.com

The classes and interfaces in the com.ms.com package allow you to implement and use Component Object Model (COM) objects from Java. Used in conjunction with the jactivex and javareg tools, the classes in this package allow you to benefit from Java/COM integration provided by the Microsoft Win32 VM for Java. The Microsoft VM supports two levels of integration with COM objects. High-level integration involves converting Microsoft® ActiveX® controls to JavaBeans components and exposing JavaBeans components as ActiveX controls. Low-level Java/COM integration refers to accessing COM objects by their vtable methods, which is useful when you need to marshal data types that are not handled by IDispatch. This overview briefly explains how COM objects can be implemented in Java, and then describes some of the most frequently used classes in the com.ms.com package.

COM Objects and Java

Every Java class automatically implements IUnknown and IDispatch. This fact makes every Java object a COM object. The dispinterface implemented by the IDispatch interface contains the public methods that are on the default interface for the class. At runtime, the Microsoft VM automatically provides type information for this IDispatch implementation. To implement a simple Automation object in Java, you place it in the class path and run the javareg tool to register it. No IDLs, type libraries, or Wizards are required.

Frequently Used Classes

The com.ms.com.IUnknown interface is a placeholder for COM interfaces. Every Java version of a COM interface is derived from com.ms.com.IUnknown. Therefore, you never call methods on com.ms.com.IUnknown. If your Java program calls a COM method whose return type is com.ms.com.IUnknown, you should cast the return value to the COM interface that you are expecting. If your program calls a COM method that takes a parameter of type com.ms.com.IUnknown, you can pass any COM interface to the COM method.

The Dispatch class enables Java programs to invoke methods and access the properties of any ActiveX component that supports the IDispatch interface. Each of the methods in this class performs one of the following functions:

getIDsOfNames methods:
Maps methods or property names to dispids.
invokev methods:
Invokes methods or accesses properties.
invokeSubv methods:
Invokes subroutines.

Three classes are used to communicate error information from a COM method to Java: com.ms.com.ComException, com.ms.com.ComFailException, and com.ms.com.ComSuccessException. The ComException class wraps the HRESULT error code that is returned by COM interface methods. ComException objects communicate error information from a COM method to Java when the COM method fails. This class defines a getHResult method that retrieves the error code from the ComException object. The ComFailException and the ComSuccessException classes are derived from the ComException class. Typically, you try to catch ComFailException objects so that you know when something has gone wrong during a call to a COM method. The documentation for the ComFailException class contains a list of the values of system-defined HRESULTs. For ComSuccessException objects, the default value of the stored HRESULT is S_FALSE (0x00000001L). This value indicates the successful completion of a method that returns a boolean value of false.

The com.ms.com.Variant class is used to bridge Java with ActiveX components that manipulate VARIANTs. Most of the methods found in this class belong to one of three categories:

to XXX methods:
Attempt to coerce the Variant object to type XXX and return the converted value, but do not copy the result back to the Variant.
get XXX methods:
Retrieve data from a Variant object of type XXX, succeeding only if the Variant object is already the correct type.
put XXX methods:
Change the type of a Variant object and initialize it to a new value.

Certain classes in the com.ms.com package are used by internal operations and must be installed on your host system for the com.ms.com package to work correctly. Any Java applications you create, however, never need to call these classes directly. These classes are as follows:

AnsiStringMarshaller
Converts LPCSTR (pointer to a constant null-terminated Windows character string) to java.lang.String.
CUnknown
Serves as the default class for Java-callable wrappers. These wrappers belong to COM interfaces that are marshaled to Java interfaces.
UniStringMarshaller
Converts LPWSTR (pointer to a null-terminated Unicode character string) to java.lang.String.

Classes

Class _Guid
This class represents globally unique identifiers (GUIDs), which are 128-bit integer values that are used to assign world-wide unique identifiers for COM interfaces and CoClasses.
Class ComError
This class signals errors in linking Java and Component Object Model (COM) objects.
Class ComException
This class wraps an HRESULT, the return type for most methods in the Component Object Model (COM).
Class ComFailException
This class wraps an HRESULT, the return type for most methods in the Component Object Model (COM).
Class ComLib
This class contains routines that are used during Java Component Object Model (COM) integration.
Class ComSuccessException
This class wraps an HRESULT, the return type used in most methods in the Component Object Model (COM).
Class ConnectionPointCookie
This class provides methods for creating and closing a connection between a source and a sink object.
Class Dispatch
This class enables Java programs to invoke methods and access the properties of any Microsoft® ActiveX® Automation object.
Class DispatchProxy
This class wraps a dispatchable object with a Java interface.
Class LicenseMgr
This class works with the ILicenseMgr interface to enable you to use licensed Component Object Model (COM) components or controls in your Java application.
Class SafeArray
This class wraps a Microsoft® ActiveX® Automation SAFEARRAY data structure.
Class STATSTG
This class represents an STATSTG structure, which contains statistical information about an open storage, stream or byte array object.
Class Variant
This class is used to bridge Java with Microsoft® ActiveX® components that manipulate VARIANT data types.
Class WrongThreadException
This class represents objects that are thrown when a method call cannot be made because it was called on the wrong thread.

Interfaces

Interface ComContext
This class defines constants that specify the contexts that a Component Object Model (COM) class can run in.
Interface IAccessible
This interface provides methods that enable users to request selection and focus information, perform hit tests, and navigate by using object and child identifiers.
Interface IAccessibleDefault
This interface provides methods that enable users to request selection and focus information, perform hit tests, and navigate by using object and child identifiers.
Interface IEnumVariant
This interface provides methods for enumerating a collection of variants.
Interface IExternalConnectionSink
This interface provides methods that allow Java objects exposed as Component Object Model (COM) objects to receive notifications about calls made to the IExternalConnection interface that is exposed by the Microsoft® Win32® VM for Java.
Interface ILicenseMgr
This interface supports the use of licensed Component Object Model (COM) components or controls in a Java application.
Interface IPropertyNotifySink
This interface provides methods that allow a sink object to receive notifications about property changes from another object.
Interface IServiceProvider
This interface provides a method that locates a service specified by a GUID and returns the interface pointer for a requested interface on the service.
Interface IStream
This interface provides methods for reading and writing data to stream objects.
Interface IUnknown
This interface is used as the return type for Component Object Model (COM) methods that return arbitrary COM interfaces.
Interface NoAutoScripting
When used in the implements clause of a class definition, this interface prevents the Microsoft Win32 VM for Java from including its own IDispatch implementation for the class.

Hierarchy

Object
  |
  +--_Guid
  |
  +--ComLib
  |
  +--ConnectionPointCookie
  |
  +--Dispatch
  |
  +--DispatchProxy
  |
  +--LicenseMgr (IUnknown, ILicenseMgr)
  |
  +--SafeArray
  |
  +--STATSTG
  |
  +--Variant

OutOfMemoryError
  |
  +--ComError

RuntimeException
  |
  +--ComException
  |  |
  |  +--ComFailException
  |  |
  |  +--ComSuccessException
  |
  +--WrongThreadException

ComContext
IAccessible
IUnknown
IAccessibleDefault
IEnumVariant
IExternalConnectionSink
ILicenseMgr
IPropertyNotifySink
IServiceProvider
IStream
NoAutoScripting


Class _Guid

public final class _Guid
{
  // Constructors
  public _Guid(byte [] ba);
  public _Guid(int d1, short d2, short d3, byte b8, byte b9,
        byte b10, byte b11, byte b12, byte b13, byte b14,
        byte b15);
  public _Guid(String str);
  public _Guid();

  // Methods
  public boolean equals(Object g2);
  public int hashCode();
  public void set(byte [] ba);
  public void set(String str);
  public void set(int d1, short d2, short d3, byte b8, byte b9,
        byte b10, byte b11, byte b12, byte b13, byte b14,
        byte b15);
  public byte [] toByteArray();
  public String toString();
}

This class represents globally unique identifiers (GUIDs), which are 128-bit integer values that are used to assign world-wide unique identifiers for COM interfaces and CoClasses. The jactivex tool maps all GUIDs found in a type library to instances of the _Guid class.

Constructors

_Guid

public _Guid(byte [] ba);

Constructs a new _Guid object, whose value matches the internal representation of the specified 16-element byte array.

Caution This constructor form is efficient but not endian-portable. Its use, therefore, is not recommended for cross-platform applications.

Parameter | Description
ba | The 16-element byte array.

_Guid

public _Guid(int d1, short d2, short d3, byte b8, byte b9, byte b10,
        byte b11, byte b12, byte b13, byte b14, byte b15);

Constructs a new _Guid object. whose value is specified by the internal representations of the parameters d1 through b15 in order.

Parameter | Description
d1 | A 32-bit integer.
d2 | A 16-bit integer.
d3 | A 16-bit integer.
b8 | An 8-bit integer.
b9 | An 8-bit integer.
b10 | An 8-bit integer.
b11 | An 8-bit integer.
b12 | An 8-bit integer.
b13 | An 8-bit integer.
b14 | An 8-bit integer
b15 | An 8-bit integer.

_Guid

public _Guid(String str);

Constructs a new _Guid object from its string representation. The string representation is in the following form, in which each x denotes a hexadecimal digit:

{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

Parameter | Description
str | The GUID string representation.

_Guid

public _Guid();

Constructs a new _Guid object, whose value is as follows:

{00000000-0000-0000-0000-000000000000}.

Methods

equals

public boolean equals(Object g2);

Tests whether the GUID represented by the parameter g2 is equal to the GUID represented by the current _Guid object. Two GUIDs are equal only if each of the 128 bits in the two GUIDs is equal

Return Value:

Returns true if each of the 128 bits in the two GUIDs are equal; otherwise, returns false.

Parameter | Description
g2 | The object whose GUID is being compared against the current _Guid object

hashCode

public int hashCode();

Computes a hash code based on the value of the GUID.

Return Value:

Returns an integer hash code.

set

public void set(byte [] ba);

Reinitializes an existing _Guid object from a 16-element byte array.

Caution This method of reinitialization is not endian-portable.

Return Value:

No return value.

Parameter | Description
ba | A 16-element byte array.

set

public void set(String str);

Reinitializes an existing _Guid from its registry string representation. The string representation is in the following form, in which each x denotes a hexadecimal digit:

{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

Return Value:

No return value.

Parameter | Description
str | The registry string representation.

set

public void set(int d1, short d2, short d3, byte b8, byte b9, byte b10,
        byte b11, byte b12, byte b13, byte b14, byte b15);

Reinitializes an existing _Guid object so that its value is specified by the internal representations of the parameters d1 through b15 in order.

Return Value:

No return value.

Parameter | Description
d1 | A 32-bit integer.
d2 | A 16-bit integer.
d3 | A 16-bit integer.
b8 | An 8-bit integer.
b9 | An 8-bit integer.
b10 | An 8-bit integer.
b11 | An 8-bit integer.
b12 | An 8-bit integer.
b13 | An 8-bit integer.
b14 | An 8-bit integer.
b15 | An 8-bit integer.

toByteArray

public byte [] toByteArray();

Converts a GUID to a 16-element byte array.

Caution The byte array representation is not endian-portable; it cannot be used to transmit GUIDs between processors.

Return Value:

Returns a 16-element byte array that represents the GUID.

toString

public String toString();

Converts a GUID to its registry string representation.

Return Value:

Returns the registry string representation of the GUID.


Class ComError

public class ComError extends OutOfMemoryError
{
  // Constructors
  public ComError();
  public ComError(String s);
}

This class signals errors in linking Java and Component Object Model (COM) objects. ComError extends the OutOfMemoryError class to achieve backward compatibility with Microsoft SDK for Java 1.0.

OutOfMemoryError
  |
  +--ComError

Constructors

ComError

public ComError();

Creates an empty ComError object.

ComError

public ComError(String s);

Creates a ComError object that contains a specific detail message.

Parameter | Description
s | The detail message that describes the exception.


Class ComException

public abstract class ComException extends RuntimeException
{
  // Fields
  protected int hr;
  protected int m_helpContext;
  protected String m_helpFile;
  protected String m_source;

  // Constructors
  public ComException(int hr);
  public ComException(int hr, String description);
  public ComException(int hr, String source, String helpFile,
        int helpContext);
  public ComException(int hr, String description, String source,
        String helpFile, int helpContext);
  public ComException();
  public ComException(String description);

  // Methods
  public int getHelpContext();
  public String getHelpFile();
  public int getHResult();
  public String getSource();
}

This class wraps an HRESULT, the return type for most methods in the Component Object Model (COM). When you call COM methods from Java, you catch ComException objects to handle error conditions. Because ComException is derived from the RuntimeException class, the compiler does not check whether methods throw ComException objects. Use your discretion as to when you should use try-catch blocks.

When implementing COM classes that use Java, ComException objects are thrown to signal error conditions. Because ComException is an abstract class, a ComException object cannot be constructed directly. However, ComFailException objects and ComSuccessException objects are constructed using ComException constructors.

RuntimeException
  |
  +--ComException

Constructors

ComException

public ComException(int hr);

Creates a ComException object that contains the specified HRESULT.

Parameter | Description
hr | The HRESULT value.

ComException

public ComException(int hr, String description);

Creates a ComException object that contains an HRESULT and a description.

Parameter | Description
hr | The HRESULT value that is returned.
description | The detail description.

ComException

public ComException(int hr, String source, String helpFile,
        int helpContext);

Creates a ComException object that contains the HRESULT, source, Help file, and help context.

Parameter | Description
hr | The HRESULT value that is returned.
source | The source of the ComException object.
helpFile | The Help file that explains the ComException object.
helpContext | The identifier that indicates the context of the exception.

ComException

public ComException(int hr, String description, String source,
        String helpFile, int helpContext);

Creates a ComException object that contains the specified HRESULT, description, source, Help file, and Help context.

Parameter | Description
hr | The HRESULT value to be returned.
description | The detail description.
source | The source of the ComException object.
helpFile | The Help file that explains the ComException object.
helpContext | The identifier that indicates the context of the exception.

ComException

public ComException();

Creates and stores an uninitialized ComException object.

ComException

public ComException(String description);

Creates and stores a ComException object that contains the detail description.

Parameter | Description
description | The detail description.

Methods

getHelpContext

public int getHelpContext();

Retrieves the Help context of the ComException object. The Help context is an identifier that indicates the context of the exception.

Return Value:

Returns the Help context of the ComException object.

getHelpFile

public String getHelpFile();

Retrieves the Help file that explains the ComException object.

Return Value:

Returns the Help file that explains the ComException object.

getHResult

public int getHResult();

Retrieves the HRESULT returned by the COM method. To catch a ComException object thrown by a COM method, call this method.

Return Value:

Returns the HRESULT returned by the COM method.

getSource

public String getSource();

Retrieves the source of the ComException object.

Return Value:

Returns the source of the ComException object.

Fields

hr
The HRESULT value.
m_helpContext
The identifier used by the Help file that indicates the context of the exception.
m_helpFile
The help file that explains the ComException object.
m_source
The source of the ComException object.


Class ComFailException

public class ComFailException extends ComException
{
  // Constructors
  public ComFailException(int hr);
  public ComFailException(int hr, String message);
  public ComFailException(int hr, String source, String helpFile,
        int helpContext);
  public ComFailException(int hr, String description,
        String source, String helpFile, int helpContext);
  public ComFailException();
  public ComFailException(String message);
}

This class wraps an HRESULT, the return type for most methods in the Component Object Model (COM). The default value of the HRESULT stored in a ComFailException object is E_FAIL (0x80004005L).

The values of system-defined HRESULTs can be found in WINERROR.H, which is included with the Microsoft® Platform SDK. For information on component-specific errors, refer to the documentation associated with the component.

For system-defined errors, the detail description stored in the ComException object is the string returned by the Win32® API function, FormatMessage. This function returns a brief description of the error. This description can be retrieved by calling the getMessage method that is defined by the Throwable class.

The following table lists some common HRESULT values:

Error | Meaning | Value
E_UNEXPECTED | Unexpected failure | 0x8000FFFF
E_NOTIMPL | Not implemented | 0x80004001
E_OUTOFMEMORY | Ran out of memory | 0x8007000E
E_INVALIDARG | One or more arguments are invalid | 0x80070057
E_NOINTERFACE | No such interface supported | 0x80004002
E_POINTER | Invalid pointer | 0x80004003
E_HANDLE | Invalid handle | 0x80070006
E_ABORT | Operation aborted | 0x80004004
E_FAIL | Unspecified error | 0x80004005
E_ACCESSDENIED | General access denied error | 0x80070005
E_NOTIMPL | Not implemented | 0x80000001
DISP_E_UNKNOWNINTERFACE | Unknown interface | 0x80020001
DISP_E_MEMBERNOTFOUND | Member not found | 0x80020003
DISP_E_PARAMNOTFOUND | Parameter not found | 0x80020004
DISP_E_TYPEMISMATCH | Type mismatch | 0x80020005
DISP_E_UNKNOWNNAME | Unknown name | 0x80020006
DISP_E_NONAMEDARGS | No named arguments | 0x80020007
DISP_E_BADVARTYPE | Bad variable type | 0x80020008
DISP_E_EXCEPTION | Exception occurred | 0x80020009
DISP_E_OVERFLOW | Out of present range | 0x8002000A
DISP_E_BADINDEX | Invalid index | 0x8002000B
DISP_E_UNKNOWNLCID | Memory is locked | 0x8002000C
DISP_E_ARRAYISLOCKED | Memory is locked | 0x8002000D
DISP_E_BADPARAMCOUNT | Invalid number of parameters | 0x8002000E
DISP_E_PARAMNOTOPTIONAL | Parameter not optional | 0x8002000F
DISP_E_BADCALLEE | Invalid callee | 0x80020010
DISP_E_NOTACOLLECTION | Does not support a collection | 0x80020011

RuntimeException
  |
  +--ComException
    |
    +--ComFailException

Constructors

ComFailException

public ComFailException(int hr);

Creates a ComFailException object that contains the specified HRESULT.

Parameter | Description
hr | The HRESULT value that is returned.

ComFailException

public ComFailException(int hr, String message);

Creates a ComFailException object that contains the specified HRESULT and detail description.

Parameter | Description
hr | The HRESULT value that is returned.
message | The detail description.

ComFailException

public ComFailException(int hr, String source, String helpFile,
        int helpContext);

Creates a ComFailException object that contains the specified HRESULT, source, help file, and help context.

Parameter | Description
hr | The HRESULT value that is returned.
source | The source of the ComFailException object.
helpFile | The help file for the ComFailException object.
helpContext | The identifier that indicates the context of the exception.

ComFailException

public ComFailException(int hr, String description, String source,
        String helpFile, int helpContext);

Creates a ComFailException object that contains the specified HRESULT, description, source, Help file, and help context.

Parameter | Description
hr | The HRESULT value that is returned.
description | The detail description.
source | The source of the ComFailException object.
helpFile | The help file for the ComFailException object.
helpContext | The identifier that indicates the context of the exception.

ComFailException

public ComFailException();

Creates a ComFailException object. The default value of the HRESULT stored in the object is E_FAIL (0x80004005L).

ComFailException

public ComFailException(String message);

Creates a ComFailException object that contains the specified detail description. The default value of the HRESULT stored in the object is E_FAIL (0x80004005L).

Parameter | Description
message | The detail description.


Class ComLib

public class ComLib
{
  // Methods
  public native static void declareMessagePumpThread();
  public static native boolean isEqualUnknown(Object o1, Object o2);
  public native static int jcdwClassOffsetOf(Class cls,
        String fieldName);
  public native static int jcdwClassSizeOf(Class cls);
  public native static int jcdwOffsetOf(Object jcdw,
        String fieldName);
  public native static int jcdwSizeOf(Object jcdw);
  public static boolean ownsCleanup(Object structObj);
  public static native Object ptrToStruct(Class structClass,
        int ptr);
  public native static void release(Object o);
  protected static native void setDataWrapperSize(
        Object DataWrapper, int cb);
  public native static boolean supportsInterface(Object pComObject,
        _Guid iid);
  public static native void threadStartMTA(Thread thd);
}

This class contains routines that are used during Java Component Object Model (COM) integration. All ComLib methods are static; therefore, you can use this class without instantiating it.

Methods

declareMessagePumpThread

public native static void declareMessagePumpThread();

Enables apartment model hosting.

Return Value:

No return value.

isEqualUnknown

public static native boolean isEqualUnknown(Object o1, Object o2);

Compares the COM identity of two Java objects. If the two objects have equal IUnknown* pointers, they have the same COM identity.

Return Value:

Returns true if the two objects have the same COM identity; otherwise, returns false.

Parameter | Description
o1 | The first object to be compared.
o2 | The second object to be compared.

jcdwClassOffsetOf

public native static int jcdwClassOffsetOf(Class cls, String fieldName);

Retrieves the offset of a COM data structure that represents an instance of a Java proxy class. The offset is measured in bytes.

Return Value:

Returns the offset of a COM data structure, measured in bytes.

Parameter | Description
cls | The class object for a Java proxy to a COM data structure.
fieldName | The name of the COM-mapped field.

jcdwClassSizeOf

public native static int jcdwClassSizeOf(Class cls);

Retrieves the size (measured in bytes) of a COM data structure that represents instances of the class.

Return Value:

Returns the size of a COM data structure, measured in bytes.

Parameter | Description
cls | The class object for a Java proxy to a COM data structure.

jcdwOffsetOf

public native static int jcdwOffsetOf(Object jcdw, String fieldName);

Retrieves the offset of a COM data structure (measured in bytes) that is represented by a Java proxy.

Return Value:

Returns the COM data structure offset, measured in bytes.

Parameter | Description
jcdw | The Java proxy to a data structure.
fieldName | The name of the COM-mapped field.

jcdwSizeOf

public native static int jcdwSizeOf(Object jcdw);

Retrieves the size of a COM data structure (measured in bytes) that is represented by a Java proxy.

Return Value:

Returns the size of a COM data structure, measured in bytes.

Parameter | Description
jcdw | The Java proxy to a data structure.

ownsCleanup

public static boolean ownsCleanup(Object structObj);

Determines whether Java is responsible for doing cleanup tasks for the COM object.

Return Value:

Returns true if the object is owned by Java; otherwise, returns false.

Parameter | Description
structObj | The COM object that is being checked.

ptrToStruct

public static native Object ptrToStruct(Class structClass, int ptr);

Maps a raw pointer onto a structure. This method simulates a C-style cast of an arbitrary pointer to a structure.

Return Value:

Returns an instance of structClass.

Parameter | Description
structClass | The class declared using @dll.struct.
ptr | The raw pointer that is mapped.

release

public native static void release(Object o);

Forces Java to release all outstanding reference counts on a native COM object. After releasing the reference counts, any attempts to use the COM object through this Java proxy results in an UnsatisfiedLinkError. If the specified object does not wrap a native COM object, this method quietly succeeds but does nothing.

Return Value:

No return value.

Parameter | Description
o | The Java proxy of a native COM object.

Remarks:

If the Java proxy wraps a non–thread-safe native COM object that was created on another thread, the actual release of the object can occur after the release method has returned.

setDataWrapperSize

protected static native void setDataWrapperSize(Object DataWrapper, int cb);

Allocates and binds memory to an existing data wrapper.

Return Value:

No return value.

Parameter | Description
DataWrapper | The wrapper that memory is allocated and bound to.
cb | The memory (measured in bytes) that is bound to the data wrapper.

supportsInterface

public native static boolean supportsInterface(Object pComObject,
        _Guid iid);

Determines whether a COM object supports a particular interface by using that object's QueryInterface method. The interface is not returned because Java interfaces exist only at compile time and are not distinguishable from the main object at runtime.

Return Value:

Returns true if the interface is supported; otherwise, returns false.

Parameter | Description
pComObject | Any Java object that can be mapped to a COM object.
iid | The identifier of the interface to query for.

threadStartMTA

public static native void threadStartMTA(Thread thd);

Initializes a thread without initializing COM. This means that (by default) the thread will be in a COM multi-threaded apartment. This method is similar to the Thread.start method, but Thread.start initializes the thread as a separate single-threaded COM apartment.

Return Value:

No return value.

Parameter | Description
thd | The Thread to start.

Exceptions:

IllegalThreadStateException if the thread was already started.


Class ComSuccessException

public class ComSuccessException extends ComException
{
  // Constructors
  public ComSuccessException(int hr);
  public ComSuccessException(int hr, String message);
  public ComSuccessException(int hr, String source,
        String helpFile, int helpContext);
  public ComSuccessException(int hr, String description,
        String source, String helpFile, int helpContext);
  public ComSuccessException();
  public ComSuccessException(String message);
}

This class wraps an HRESULT, the return type used in most methods in the Component Object Model (COM). In a ComSuccessException object, the default value of the stored HRESULT is S_FALSE (0x00000001L). This value indicates the successful completion of a method that returns a boolean value of false.

Note To return an S_OK value when implementing a COM method in Java, code the method to return as it normally would. No special code is required.

RuntimeException
  |
  +--ComException
    |
    +--ComSuccessException

Constructors

ComSuccessException

public ComSuccessException(int hr);

Creates a ComSuccessException object that contains the specified HRESULT.

Parameter | Description
hr | The HRESULT that a COM method returns.

ComSuccessException

public ComSuccessException(int hr, String message);

Creates a ComSuccessException object that contains the specified HRESULT and a detail description.

Parameter | Description
hr | The HRESULT that a COM method returns.
message | The detail description.

ComSuccessException

public ComSuccessException(int hr, String source, String helpFile,
        int helpContext);

Creates a ComSuccessException object that contains the specified HRESULT, a detail description, a Help file, and the Help context.

Parameter | Description
hr | The HRESULT that a COM method returns.
source | The detail description.
helpFile | The Help file for the ComSuccessException object.
helpContext | The identifier that indicates the context of the exception.

ComSuccessException

public ComSuccessException(int hr, String description, String source,
        String helpFile, int helpContext);

Creates a ComSuccessException object that contains the specified HRESULT, detail description, source, a Help file, and Help context.

Parameter | Description
hr | The HRESULT that the COM method returns.
description | The detail description.
source | The source of the ComSuccessException.
helpFile | The Help file for the ComSuccessException object.
helpContext | The identifier that indicates the context of the exception.

ComSuccessException

public ComSuccessException();

Creates a ComSuccessException object. The default value of the HRESULT stored in the object is S_FALSE (0x00000001L). This value indicates the successful completion of a method that returns a boolean value of false.

ComSuccessException

public ComSuccessException(String message);

Creates a ComSuccessException object that contains the specified detail description. The default value of the HRESULT stored in the object is S_FALSE (0x00000001L). This value indicates the successful completion of a method that returns a boolean value of false.

Parameter | Description
message | The detail description.


Class ConnectionPointCookie

public class ConnectionPointCookie
{
  // Constructors
  public ConnectionPointCookie(Object source, Object sink,
        Class connectionInterface);

  // Methods
  public native synchronized void disconnect();
  protected void finalize();
}

This class provides methods for creating and closing a connection between a source and a sink object.

Constructors

ConnectionPointCookie

public ConnectionPointCookie(Object source, Object sink,
        Class connectionInterface);

Creates a connection between the source and the sink object by using the connection interface identifier (IID).

Parameter | Description
source | The source object that is used to make the interface connection.
sink | The sink object that is used to make the interface connection.
connectionInterface | The connection interface that is used to connect the source and the sink objects.

Methods

disconnect

public native synchronized void disconnect();

Explicitly closes the connection between the source and the sink objects. The connection is closed independently of the garbage collection process.

Return Value:

No return value.

finalize

protected void finalize();

Closes the connection between the source and the sink objects by calling the ConnectionPointCookie object's disconnect method. When the object is no longer in processing scope, the Microsoft Win32 VM for Java ensures that appropriate cleanup occurs by calling this method.

Return Value:

No return value.


Class Dispatch

public class Dispatch
{
  // Fields
  public static final int DISPID_ABOUTBOX;
  public static final int DISPID_AMBIENT_APPEARANCE;
  public static final int DISPID_AMBIENT_AUTOCLIP;
  public static final int DISPID_AMBIENT_BACKCOLOR;
  public static final int DISPID_AMBIENT_CHARSET;
  public static final int DISPID_AMBIENT_CODEPAGE;
  public static final int DISPID_AMBIENT_DISPLAYASDEFAULT;
  public static final int DISPID_AMBIENT_DISPLAYNAME;
  public static final int DISPID_AMBIENT_FONT;
  public static final int DISPID_AMBIENT_FORECOLOR;
  public static final int DISPID_AMBIENT_LOCALEID;
  public static final int DISPID_AMBIENT_MESSAGEREFLECT;
  public static final int DISPID_AMBIENT_PALETTE;
  public static final int DISPID_AMBIENT_SCALEUNITS;
  public static final int DISPID_AMBIENT_SHOWGRABHANDLES;
  public static final int DISPID_AMBIENT_SHOWHATCHING;
  public static final int DISPID_AMBIENT_SUPPORTSMNEMONICS;
  public static final int DISPID_AMBIENT_TEXTALIGN;
  public static final int DISPID_AMBIENT_TRANSFERPRIORITY;
  public static final int DISPID_AMBIENT_UIDEAD;
  public static final int DISPID_AMBIENT_USERMODE;
  public static final int DISPID_APPEARANCE;
  public static final int DISPID_AUTOSIZE;
  public static final int DISPID_BACKCOLOR;
  public static final int DISPID_BACKSTYLE;
  public static final int DISPID_BORDERCOLOR;
  public static final int DISPID_BORDERSTYLE;
  public static final int DISPID_BORDERVISIBLE;
  public static final int DISPID_BORDERWIDTH;
  public static final int DISPID_CAPTION;
  public static final int DISPID_CLICK;
  public static final int DISPID_COLLECT;
  public static final int DISPID_CONSTRUCTOR;
  public static final int DISPID_DBLCLICK;
  public static final int DISPID_DESTRUCTOR;
  public static final int DISPID_DOCLICK;
  public static final int DISPID_DRAWMODE;
  public static final int DISPID_DRAWSTYLE;
  public static final int DISPID_DRAWWIDTH;
  public static final int DISPID_ENABLED;
  public static final int DISPID_ERROREVENT;
  public static final int DISPID_EVALUATE;
  public static final int DISPID_FILLCOLOR;
  public static final int DISPID_FILLSTYLE;
  public static final int DISPID_FONT;
  public static final int DISPID_FORECOLOR;
  public static final int DISPID_HWND;
  public static final int DISPID_KEYDOWN;
  public static final int DISPID_KEYPRESS;
  public static final int DISPID_KEYUP;
  public static final int DISPID_MOUSEDOWN;
  public static final int DISPID_MOUSEICON;
  public static final int DISPID_MOUSEMOVE;
  public static final int DISPID_MOUSEPOINTER;
  public static final int DISPID_MOUSEUP;
  public static final int DISPID_NEWENUM;
  public static final int DISPID_PICTURE;
  public static final int DISPID_PROPERTYPUT;
  public static final int DISPID_READYSTATE;
  public static final int DISPID_READYSTATECHANGE;
  public static final int DISPID_REFRESH;
  public static final int DISPID_TABSTOP;
  public static final int DISPID_TEXT;
  public static final int DISPID_UNKNOWN;
  public static final int DISPID_VALID;
  public static final int DISPID_VALUE;
  public static final int fdexNameCaseSensitive;
  public static final int Get;
  public static final int LOCALE_SYSTEM_DEFAULT;
  public static final int Method;
  public static final int Put;
  public static final int PutRef;

  // Methods
  public static Variant call(Object pDispatch, String dispName);
  public static Variant call(Object pDispatch, String dispName,
        Object o0);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6);
  public static Variant call(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6, Object o7);
  public static Variant call(Object pDispatch, int dispid);
  public static Variant call(Object pDispatch, int dispid,
        Object o0);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6);
  public static Variant call(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6, Object o7);
  public static Variant callN(Object pDispatch, String dispName,
        Object oArg[]);
  public static Variant callN(Object pDispatch, int dispid,
        Object oArg[]);
  public static Variant callN_casesensitive(Object pDispatch,
        String dispName, Object oArg[]);
  public static void callSub(Object pDispatch, String dispName);
  public static void callSub(Object pDispatch, String dispName,
        Object o0);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6);
  public static void callSub(Object pDispatch, String dispName,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6, Object o7);
  public static void callSub(Object pDispatch, int dispid);
  public static void callSub(Object pDispatch, int dispid,
        Object o0);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6);
  public static void callSub(Object pDispatch, int dispid,
        Object o0, Object o1, Object o2, Object o3, Object o4,
        Object o5, Object o6, Object o7);
  public static void callSubN(Object pDispatch, String dispName,
        Object oArg[]);
  public static void callSubN(Object pDispatch, int dispid,
        Object oArg[]);
  public static Variant get(Object pDispatch, String dispName);
  public static Variant get(Object pDispatch, int dispid);
  public static Variant get_casesensitive(Object pDispatch,
        String dispName);
  public static int getIDOfName(Object pDispatch, String dispName);
  public static int[] getIDsOfNames(Object pDispatch, _Guid iid,
        int lcid, String dispNames[]);
  public static Variant invoke(Object pDispatch, _Guid iid,
        String dispName, int dispID, int lcid, int wFlags, Object
        oArg[], int uArgErr[]);
  public static Variant invoke(Object pDispatch, String dispName,
        int wFlags, Object oArg[], int uArgErr[]);
  public static Variant invoke(Object pDispatch, int dispid,
        int wFlags, Object oArg[], int uArgErr[]);
  public static void invokeSub(Object pDispatch, _Guid iid,
        String dispName, int dispID, int lcid, int wFlags, Object
        oArg[], int uArgErr[]);
  public static void invokeSub(Object pDispatch, String dispName,
        int wFlags, Object oArg[], int uArgErr[]);
  public static void invokeSub(Object pDispatch, int dispid,
        int wFlags, Object oArg[], int uArgErr[]);
  public static void invokeSubv(Object pDispatch, _Guid iid, String
        dispName, int dispID, int lcid, int wFlags, Variant
        vArg[], int uArgErr[]);
  public static void invokeSubv(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[]);
  public static void invokeSubv(Object pDispatch, int dispid,
        int wFlags, Variant vArg[], int uArgErr[]);
  public static Variant invokev(Object pDispatch, _Guid iid, String
        dispName, int dispID, int lcid, int wFlags, Variant
        vArg[], int uArgErr[]);
  public static Variant invokev(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[], int wFlagsEx);
  public static Variant invokev(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[]);
  public static Variant invokev(Object pDispatch, int dispid,
        int wFlags, Variant vArg[], int uArgErr[]);
  public static void put(Object pDispatch, String dispName,
        Object val);
  public static void put(Object pDispatch, int dispid, Object val);
  public static void put_casesensitive(Object pDispatch,
        String dispName, Object val);
  public static void putRef(Object pDispatch, String dispName,
        Object val);
  public static void putRef(Object pDispatch, int dispid,
        Object val);
}

This class enables Java programs to invoke methods and access the properties of any Microsoft® ActiveX® Automation object. (ActiveX Automation objects are ActiveX components that support the IDispatch interface.) Methods in the Dispatch class are static; it is never necessary to instantiate this class.

Although this class includes a large number of methods, three basic methods define its capabilities:

getIDsOfNames:
Maps methods or property names to dispids.
invokev:
Invokes methods or accesses properties.
invokeSubv:
Invokes subroutines.

If one of these methods does not accomplish a given task, neither will any of the other methods in the Dispatch class. Each of the other methods in the class has the same function as one of the three basic methods; however, each of the other methods supplies (wraps) commonly used default parameters for ease of use.

The following list describes the parameters required by the invokev and invokeSubv methods and specifies default values that aren't mentioned in the wrapper method documentation:

Parameter | Description and Default Value
Object pDispatch | Either a Java object that wraps an ActiveX Automation object or a Variant object that can be coerced to such an object by the Variant.toDispatch method. There is no default value for this parameter; every wrapper method requires it.
_Guid iid | The IID of the interface that is invoked. (The interface must derive from IDispatch.) If the value is missing or null, the value of IID_IDispatch is used.
String dispName | The name of the method or property that is invoked. If the value is null, dispID is used to determine the method or property.
int dispID | Indicates the method or property that is invoked. This parameter is ignored if dispName is null.
int lcid | Indicates the locale identifier. Wrapper methods automatically pass Dispatch.LOCALE_SYSTEM_DEFAULT for this value.
int wFlags | Indicates the type of access: must be either Dispatch.Method, Dispatch.Get, Dispatch.Put or Dispatch.PutRef. Most of the wrapper methods provide a fixed access that is indicated by the method name: Get methods default to DISPATCH_PROPERTYGET; Put methods default to DISPATCH_PROPERTYPUT; Call methods default to DISPATCH_METHOD.
Variant vArg | The parameters of the method or property accessor. No default value.
int uArgErr[] | If the Automation object rejects a parameter, this array receives the index of the offending parameter; It must be null or be a one-element integer array.

Most wrapper methods accept objects other than Variant objects. These objects are converted to the appropriate variant type according to the following rules:

Original Type | Converted Type
null | Converted to VT_EMPTY.
Variant | Passed as is.
Integer | Converted to VT_I4.
String | Converted to VT_BSTR.
Boolean | Converted to VT_BOOL.
Double | Converted to VT_R8.
Float | Converted to VT_R4.
SafeArray | Converted to VT_BYREF|VT_ARRAY|*.
other | Converted to VT_DISPATCH.

Methods

call

public static Variant call(Object pDispatch, String dispName);

Invokes a method (that has no parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0);

Invokes a method (that has one parameter) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1);

Invokes a method (that has two parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2);

Invokes a method (that has three parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3);

Invokes a method (that has four parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4);

Invokes a method (that has five parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5);

Invokes a method (that has six parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6);

Invokes a method (that has seven parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6,
        Object o7);

Invokes a method (that has eight parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.
o7 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid);

Invokes a method (that has no parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0);

Invokes a method (that has one parameter) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1);

Invokes a method (that has two parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2);

Invokes a method (that has three parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3);

Invokes a method (that has four parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | Identifies the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4);

Invokes a method (that has five parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5);

Invokes a method (that has six parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6);

Invokes a method (that has seven parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.

call

public static Variant call(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6,
        Object o7);

Invokes a method (that has eight parameters) on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the invoked method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.
o7 | A parameter of the invoked method.

callN

public static Variant callN(Object pDispatch, String dispName,
        Object oArg[]);

Invokes a method on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispname | The name of the invoked method.
oArg | The parameters of the invoked method.

callN

public static Variant callN(Object pDispatch, int dispid, Object oArg[]);

Invokes a method on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
oArg | The parameters of the invoked method.

callN_casesensitive

public static Variant callN_casesensitive(Object pDispatch,
        String dispName, Object oArg[]);

Invokes a method on an ActiveX Automation object.

Return Value:

Returns the Variant returned by the method.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispname | The name of the invoked method. This name is case-sensitive.
oArg | The parameters of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName);

Invokes a subroutine (that has no parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0);

Invokes a subroutine (that has one parameter) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1);

Invokes a subroutine (that has two parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2);

Invokes a subroutine (that has three parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3);

Invokes a subroutine (that has four parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4);

Invokes a subroutine (that has five parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5);

Invokes a subroutine (that has six parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6);

Invokes a subroutine (that has seven parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, String dispName, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6,
        Object o7);

Invokes a subroutine (that has eight parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.
o7 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid);

Invokes a subroutine (that has no parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0);

Invokes a subroutine (that has one parameter) on an ActiveX Automation object.

Return Value:

No return value

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1);

Invokes a subroutine (that has two parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2);

Invokes a subroutine (that has three parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3);

Invokes a subroutine (that has four parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4);

Invokes a subroutine (that has five parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5);

Invokes a subroutine (that has six parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6);

Invokes a subroutine (that has seven parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.

callSub

public static void callSub(Object pDispatch, int dispid, Object o0,
        Object o1, Object o2, Object o3, Object o4, Object o5, Object o6,
        Object o7);

Invokes a subroutine (that has eight parameters) on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
o0 | A parameter of the invoked method.
o1 | A parameter of the invoked method.
o2 | A parameter of the invoked method.
o3 | A parameter of the invoked method.
o4 | A parameter of the invoked method.
o5 | A parameter of the invoked method.
o6 | A parameter of the invoked method.
o7 | A parameter of the invoked method.

callSubN

public static void callSubN(Object pDispatch, String dispName,
        Object oArg[]);

Invokes a method on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method.
oArg | The parameters of the invoked method.

callSubN

public static void callSubN(Object pDispatch, int dispid, Object oArg[]);

Invokes a method on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the invoked method.
oArg | The parameters for the invoked method.

get

public static Variant get(Object pDispatch, String dispName);

Accesses a property on an ActiveX Automation object.

Return Value:

Returns the value of the property.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the property that is accessed.

get

public static Variant get(Object pDispatch, int dispid);

Accesses a property on an ActiveX Automation object.

Return Value:

Returns the value of the property.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the property that is accessed.

get_casesensitive

public static Variant get_casesensitive(Object pDispatch, String dispName);

Accesses a property on an ActiveX Automation object.

Return Value:

Returns the value of the property.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the property that is accessed.

getIDOfName

public static int getIDOfName(Object pDispatch, String dispName);

Maps the name of a dispmember to its dispid. This method is a direct wrapper around the IDispatch::GetIDsOfNames call. A ComFailException is thrown if the name is not recognized by the object.

Return Value:

Returns the dispid that corresponds to the specified name.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name that is resolved.

getIDsOfNames

public static int[] getIDsOfNames(Object pDispatch, _Guid iid, int lcid,
        String dispNames[]);

Maps the names of a dispmember and parameter names to their dispids. This method is a direct wrapper around the IDispatch::GetIDsOfNames call. A ComFailException is thrown if a name is not recognized by the object.

Return Value:

Returns an array of resolved dispids.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
iid | The interface to query; if null, the interface identifier defaults to IID_IDispatch.
lcid | The locale identifier.
dispNames | The array of names to resolve.

invoke

public static Variant invoke(Object pDispatch, _Guid iid, String dispName,
        int dispID, int lcid, int wFlags, Object oArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. The difference between this method and invokev is that this method accepts arbitrary objects rather than Variant objects as arguments to the invoked method.

Return Value:

Returns the Variant object returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
iid | The identifier of the interface that is called. If the value is null, defaults to IID_IDispatch.
dispName | The name of the method or property that is invoked. If the value is null, dispID is used.
dispID | The identifier of the method or property. Unless dispName is null, this parameter is ignored.
lcid | The locale ID.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invoke

public static Variant invoke(Object pDispatch, String dispName, int wFlags,
        Object oArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. This method is easier to call than the full invokev method and enables you to pass arbitrary objects rather than Variants. However, the method does not enable you to specify the interface IID or the locale, and the method must be identified by name.

Return Value:

Returns the Variant returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invoke

public static Variant invoke(Object pDispatch, int dispid, int wFlags,
        Object oArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. This method is easier to call than the full invokev method because it allows you to pass arbitrary objects rather than Variant objects. However, this method does not enable you to specify the interface IID or the locale, and the method must be identified by dispid.

Return Value:

Returns the Variant object returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokeSub

public static void invokeSub(Object pDispatch, _Guid iid, String dispName,
        int dispID, int lcid, int wFlags, Object oArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. The difference between this method and invoke is that this method accepts arbitrary objects rather than Variant objects as arguments to the invoked method. This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations do not invoke subroutines as if they were functions. If the invoked method does not return a value, use invokeSub.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
iid | The identifier of the interface that is called. If the value is null, the interface identifier defaults to IID_IDispatch.
dispName | The name of the method or property that is invoked. If the value is null, dispIDM is used.
dispID | The identifier of the method or property. Unless dispName is null, this parameter is ignored.
lcid | The locale ID.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokeSub

public static void invokeSub(Object pDispatch, String dispName, int wFlags,
        Object oArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations do not invoke subroutines as if they were functions. If the method does not return a value, use invokeSub to avoid problems. This method is easier to call than the full invokeSub method and enables you to pass arbitrary objects rather than Variant objects. However, the method does not enable you to specify the interface identifier or the locale, and the method must be identified by name.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokeSub

public static void invokeSub(Object pDispatch, int dispid, int wFlags,
        Object oArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations do not invoke subroutines as if they were functions. If the method does not return a value, use invokeSub to avoid problems. This method is easier to call than the full invokeSub method and enables you to pass arbitrary objects rather than Variant objects. However, the method does not enable you to specify the interface IID or the locale, and the method must be identified by dispid.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
oArg | The arguments to the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokeSubv

public static void invokeSubv(Object pDispatch, _Guid iid, String dispName,
        int dispID, int lcid, int wFlags, Variant vArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. This method is very similar to invokev, but it does not accept a return value from the method.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
iid | The identifier of the interface that is called. If the value is null, this parameter defaults to IID_IDispatch.
dispName | The name of the method or property that is invoked. If the value is null, dispID is used.
dispID | The identifier of the method or property. Unless dispName is null, this parameter is ignored.
lcid | The locale ID.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

Remarks:

This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations distinguish between functions and subroutines; subroutines written in such languages cannot be called as if they were functions. If the method does not return a value, use invokeSubv to avoid this problem.

invokeSubv

public static void invokeSubv(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. This method is easier to call than the full invokeSubv method, but it does not allow you to specify the interface IID or the locale, and the method must be identified by name.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

Remarks:

This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations distinguish between functions and subroutines; subroutines written in such languages cannot be called as if they were functions. If the method does not return a value, use invokeSubv to avoid this problem.

invokeSubv

public static void invokeSubv(Object pDispatch, int dispid, int wFlags,
        Variant vArg[], int uArgErr[]);

Invokes a subroutine or sets a property on an ActiveX Automation object. This method is very similar to invokev, but it does not accept a return value from the method. Some language implementations do not invoke subroutines as if they were functions. If the method does not return a value, use invokeSubv to avoid problems. This method is easier to call than the full invokeSubv method. However, it does not enable you to specify the interface identifier or the locale, and the method must be identified by dispid.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispID | The identifier of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokev

public static Variant invokev(Object pDispatch, _Guid iid, String dispName,
        int dispID, int lcid, int wFlags, Variant vArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method.

Return Value:

Returns the Variant returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
iid | The identifier of the interface that is called. If the value is null, it defaults to IID_IDispatch.
dispName | The name of the method or property that is invoked. If the value is null, dispID is used.
dispID | The identifier that identifies the method or property; ignored unless dispName is null.
lcid | The locale ID.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokev

public static Variant invokev(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[], int wFlagsEx);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. This method is easier to call than the full invokev method. It does not, however, enable you to specify the IID or the locale, and the method must be identified by name.

Return Value:

Returns the variant that is returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the invoked method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.
wFlagsEx | The extended flags that are passed to IDispatchEx.

invokev

public static Variant invokev(Object pDispatch, String dispName,
        int wFlags, Variant vArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. This method is easier to call than the full invokev method. However, it does not enable specifying the interface IID or the locale, and the method must be identified by name.

Return Value:

Returns the Variant returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

invokev

public static Variant invokev(Object pDispatch, int dispid, int wFlags,
        Variant vArg[], int uArgErr[]);

Invokes a method or accesses a property on an ActiveX Automation object. This method is essentially a direct wrapper around the IDispatch::Invoke method. This method is easier to call than the full invokev method. However, it does not enable you to specify the interface IID or the locale, and the method must be identified by dispid.

Return Value:

Returns the Variant object returned by the method or property access.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispID | The identifier of the method or property.
wFlags | The type of access, which must be Dispatch.Method, Dispatch.Get, Dispatch.Put, or Dispatch.PutRef.
vArg | The arguments of the method or property.
uArgErr | An optional one-element array. If an error occurs, uArgErr receives the index of the offending parameter.

put

public static void put(Object pDispatch, String dispName, Object val);

Sets a property on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the property that is set by this method.
val | The value to assign to the property.

put

public static void put(Object pDispatch, int dispid, Object val);

Sets a property on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the property that is set by this method.
val | The value to assign to the property.

put_casesensitive

public static void put_casesensitive(Object pDispatch, String dispName,
        Object val);

Sets a property on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the property that is set by this method.
val | The value to assign to the property.

putRef

public static void putRef(Object pDispatch, String dispName, Object val);

Sets an object property on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispName | The name of the property that is set by this method.
val | The value to assign to the property.

putRef

public static void putRef(Object pDispatch, int dispid, Object val);

Sets an object property on an ActiveX Automation object.

Return Value:

No return value.

Parameter | Description
pDispatch | The Java proxy of the ActiveX Automation object.
dispid | The identifier of the property that is set by this method.
val | The value to assign to the property.

Fields

DISPID_ABOUTBOX
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_APPEARANCE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_AUTOCLIP
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_BACKCOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_CHARSET
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_CODEPAGE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_DISPLAYASDEFAULT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_DISPLAYNAME
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_FONT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_FORECOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_LOCALEID
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_MESSAGEREFLECT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_PALETTE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_SCALEUNITS
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_SHOWGRABHANDLES
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_SHOWHATCHING
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_SUPPORTSMNEMONICS
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_TEXTALIGN
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_TRANSFERPRIORITY
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_UIDEAD
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AMBIENT_USERMODE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_APPEARANCE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_AUTOSIZE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BACKCOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BACKSTYLE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BORDERCOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BORDERSTYLE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BORDERVISIBLE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_BORDERWIDTH
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_CAPTION
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_CLICK
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_COLLECT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK .
DISPID_CONSTRUCTOR
The DISPID that indicates the constructor function.
DISPID_DBLCLICK
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_DESTRUCTOR
The DISPID that indicates the destructor function.
DISPID_DOCLICK
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_DRAWMODE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_DRAWSTYLE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_DRAWWIDTH
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_ENABLED
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_ERROREVENT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_EVALUATE
The DISPID that indicates the evaluate method.
DISPID_FILLCOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_FILLSTYLE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_FONT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_FORECOLOR
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_HWND
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_KEYDOWN
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_KEYPRESS
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_KEYUP
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_MOUSEDOWN
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_MOUSEICON
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_MOUSEMOVE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_MOUSEPOINTER
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_MOUSEUP
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_NEWENUM
The DISPID that indicates the _NEWENUM property.
DISPID_PICTURE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_PROPERTYPUT
The DISPID that indicates the parameter that receives the value of an assignment in a PROPERTYPUT.
DISPID_READYSTATE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_READYSTATECHANGE
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_REFRESH
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_TABSTOP
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_TEXT
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_UNKNOWN
The DISPID returned by IDispatch::GetIDsOfNames to indicate that a member or parameter name was not found.
DISPID_VALID
A standard DISPID defined in OLECTL.H in the Microsoft® Platform SDK.
DISPID_VALUE
The DISPID that indicates the default member for the object.
fdexNameCaseSensitive
The value that corresponds to IDispatchEx flag fdexNameCaseSensitive
Get
The value that corresponds to the ActiveX constant DISPATCH_GET.
LOCALE_SYSTEM_DEFAULT
The value that corresponds to the ActiveX constant LOCALE_SYSTEM_DEFAULT; it functions as the default value for locale-id.
Method
The value that corresponds to the ActiveX constant DISPATCH_METHOD.
Put
The value that corresponds to the ActiveX constant DISPATCH_PUT.
PutRef
The value that corresponds to the ActiveX constant DISPATCH_PUTREF.


Class DispatchProxy

public final class DispatchProxy
{
  // Constructors
  public DispatchProxy(Class exposedInterface, Object dispatch);
  public DispatchProxy(Class exposedInterface, Object dispatch,
        _Guid iid, Method dispIDMethods[], int dispIDs[]);
  public DispatchProxy(Class exposedInterface, Object dispatch,
        _Guid iid, Method dispIDMethods[], int dispIDs[], boolean
        filterNonDispatchErrors);

  // Methods
  public void disconnectAsEventSink();
  protected native void finalize();
  public Class getExposedInterface();
  public Object getUnderlyingObject();
}

This class wraps a dispatchable object with a Java interface.

Constructors

DispatchProxy

public DispatchProxy(Class exposedInterface, Object dispatch);

Allocates a new DispatchProxy object.

Parameter | Description
exposedInterface | The signature of the IDispatch call.
dispatch | The object that IDispatch calls.

Remarks:

Calls against the object on the exposed interface are translated to IDispatch::Invoke calls on the supplied dispatchable object. For this constructor, the first call to each method calls IDispatch::GetIDsOfNames to find the DISPID of the method, which is then cached. The IDispatch calls are made on the object's IID_IDispatch identity.

DispatchProxy

public DispatchProxy(Class exposedInterface, Object dispatch, _Guid iid,
        Method dispIDMethods[], int dispIDs[]);

Allocates a new DispatchProxy object. All calls against this object on the exposed interface are translated to IDispatch::Invoke calls on the supplied dispatchable object.

The lists of methods and DISPIDs supplied by the dispIDMethods and DispIDs parameters are used to pre-assign the DISPIDs to the methods in the exposed interface. Unassigned methods call IDispatch::GetIDsOfNames to find the DISPID of the method, which is then cached. IDispatch calls are made on the supplied interface identifier, which defaults to IID_IDispatch.

Parameter | Description
exposedInterface | The signature of the IDispatch call.
dispatch | The object that IDispatch calls.
iid | The supplied interface identifier, which defaults to IID_IDispatch.
dispIDMethods | The list of methods used to pre-assign the DISPIDs to the methods of the exposed interface.
dispIDs | The list of DISPIDs used to pre-assign the DISPIDs to the methods of the exposed interface.

DispatchProxy

public DispatchProxy(Class exposedInterface, Object dispatch, _Guid iid,
        Method dispIDMethods[], int dispIDs[],
        boolean filterNonDispatchErrors);

Allocates a new DispatchProxy object. All calls against this object on the exposed interface are translated to IDispatch::Invoke calls on the supplied dispatchable object.

The lists of methods and DISPIDs supplied by the dispIDMethods and dispIDs parameters are used to pre-assign the DISPIDs to the methods in the exposed interface. Unassigned methods call IDispatch::GetIDsOfNames to find the DISPID of the method, which is then cached. IDispatch calls are made on the supplied interface identifier, which defaults to IID_IDispatch.

Parameter | Description
exposedInterface | The signature of the IDispatch call.
dispatch | The object that IDispatch calls.
iid | The dispatch interface identifier, which defaults to IID_IDispatch if null is passed.
dispIDMethods | The list of methods used to pre-assign the DISPIDs to the methods of the exposed interface.
dispIDs | The list of DISPIDs used to pre-assign the DISPIDs to the methods of the exposed interface.
filterNonDispatchErrors | Indicates whether an error HRESULT besides DISP_E_EXCEPTION should generate Java exceptions when calling IDispatch.

Methods

disconnectAsEventSink

public void disconnectAsEventSink();

Disconnects the current object from the underlying object. (The underlying object is the object that was originally passed to the DispatchProxy constructor via the dispatch parameter.)

Return Value:

No return value.

finalize

protected native void finalize();

Releases native resources associated with the current object.

Return Value:

No return value.

getExposedInterface

public Class getExposedInterface();

Retrieves the Java interface that is used as the template for IDispatch calls.

Return Value:

Returns the Java interface that is used as the template for IDispatch calls.

getUnderlyingObject

public Object getUnderlyingObject();

Retrieves the underlying dispatch object that is called by IDispatch. This object was passed to the DispatchProxy constructor via the dispatch parameter.

Return Value:

Returns the underlying dispatchable object.


Class LicenseMgr

public final class LicenseMgr implements IUnknown,ILicenseMgr
{
  // Methods
  public native IUnknown createFromPackage(int index,
        IUnknown punkOuter, int ctxFlags);
  public native IUnknown createInstance(String clsid,
        IUnknown punkOuter, int ctxFlags);
  public native IUnknown createWithLic(String lic, String clsid,
        IUnknown punkOuter, int ctxFlags);
  public native void setPackage(String url);
}

This class works with the ILicenseMgr interface to enable you to use licensed Component Object Model (COM) components or controls in your Java application.

In the LicenseMgr class, methods are not called directly. Instead, you create an instance of LicenseMgr and use the ILicenseMgr interface to manipulate the instance, as in the following example:

ILicenseMgr licmgr = (ILicenseMgr)new LicenseMgr();
   // use licmgr interface

For more information on how to use licensed COM components, see the ILicenseMgr interface.

Methods

createFromPackage

public native IUnknown createFromPackage(int index, IUnknown punkOuter, int
        ctxFlags);

Creates a package. This method cannot be invoked directly. You must first cast the LicenseMgr object to the ILicenseMgr interface and invoke the method through the interface.

Return Value:

Returns the newly created package.

Parameter | Description
index | The index of the package.
punkOuter | The aggregating object if the object is created as part of an aggregate; otherwise, the value is null.
ctxFlags | The ComContext value that represents the context that the new object should be created in.

createInstance

public native IUnknown createInstance(String clsid, IUnknown punkOuter, int
        ctxFlags);

Creates an instance of a specific COM class. This method cannot be invoked directly. You must first cast the LicenseMgr object to the ILicenseMgr interface and invoke the method through the interface.

Warning In general, this method should not be called. The best way to create an instance of a COM class is to use the new operator on the Java wrapper generated by the jactivex tool.

Return Value:

Returns an instance of the specified COM class.

Parameter | Description
clsid | The class identifier (CLSID) of the instantiated COM class.
punkOuter | The aggregating object if the object is being created as part of an aggregate; otherwise, the value is null.
ctxFlags | The ComContext value that represents the context that the new object is created in.

Exceptions:

com.ms.com.ComFailException if an error occurs while instantiating the class.

createWithLic

public native IUnknown createWithLic(String lic, String clsid,
        IUnknown punkOuter, int ctxFlags);

Creates an instance of a licensed control. This method cannot be invoked directly. You must first cast the LicenseMgr object to the ILicenseMgr interface and invoke the method through the interface.

Return Value:

Returns a new instance of the specified licensed COM class.

Parameter | Description
lic | The license for the instantiated COM class.
clsid | The class identifier (CLSID) of the instantiated COM class.
punkOuter | The aggregating object if the object is being created as part of an aggregate; otherwise, the value is null.
ctxFlags | The ComContext value that represents the context that the new object is created in.

Exceptions:

com.ms.com.ComFailException if an error occurs while instantiating the class.

setPackage

public native void setPackage(String url);

Sets the package for a specific URL. This method cannot be invoked directly. You must first cast the LicenseMgr object to the ILicenseMgr interface and invoke the method through the interface.

Return Value:

No return value.

Parameter | Description
url | The Uniform Resource Locator (URL) of the package.


Class SafeArray

public final class SafeArray
{
  // Constructors
  public SafeArray(int vt);
  public SafeArray(int vt, int celems);
  public SafeArray(int vt, int celems1, int celems2);
  public SafeArray(int vt, int lbounds[], int celems[]);
  public SafeArray(String s);
  public native int getPhysicalSafeArray();

  // Methods
  public native String asString();
  public Object clone();
  public void destroy();
  protected void finalize();
  public void fromBooleanArray(boolean ja[]);
  public void fromByteArray(byte ja[]);
  public void fromCharArray(char ja[]);
  public void fromDoubleArray(double ja[]);
  public void fromFloatArray(float ja[]);
  public void fromIntArray(int ja[]);
  public void fromShortArray(short ja[]);
  public void fromStringArray(String ja[]);
  public void fromVariantArray(Variant ja[]);
  public native boolean getBoolean(int sa_idx);
  public boolean getBoolean(int sa_idx1, int sa_idx2);
  public void getBooleans(int sa_idx, int nelems, boolean ja[], int
        ja_start);
  public byte getByte(int sa_idx);
  public byte getByte(int sa_idx1, int sa_idx2);
  public void getBytes(int sa_idx, int nelems, byte ja[],
        int ja_start);
  public char getChar(int sa_idx);
  public char getChar(int sa_idx1, int sa_idx2);
  public void getChars(int sa_idx, int nelems, char ja[],
        int ja_start);
  public native double getDouble(int sa_idx);
  public double getDouble(int sa_idx1, int sa_idx2);
  public void getDoubles(int sa_idx, int nelems, double ja[],
        int ja_start);
  public int getElemSize();
  public int getFeatures();
  public native float getFloat(int sa_idx);
  public float getFloat(int sa_idx1, int sa_idx2);
  public void getFloats(int sa_idx, int nelems, float ja[],
        int ja_start);
  public native int getInt(int sa_idx);
  public int getInt(int sa_idx1, int sa_idx2);
  public void getInts(int sa_idx, int nelems, int ja[],
        int ja_start);
  public int getLBound();
  public int getLBound(int dim);
  public int getNumDim();
  public int getNumLocks();
  public short getShort(int sa_idx);
  public short getShort(int sa_idx1, int sa_idx2);
  public void getShorts(int sa_idx, int nelems, short ja[],
        int ja_start);
  public String getString(int sa_idx);
  public String getString(int sa_idx1, int sa_idx2);
  public void getStrings(int sa_idx, int nelems, String ja[],
        int ja_start);
  public int getUBound();
  public int getUBound(int dim);
  public Variant getVariant(int sa_idx);
  public Variant getVariant(int sa_idx1, int sa_idx2);
  public void getVariants(int sa_idx, int nelems, Variant ja[], int
        ja_start);
  public int getvt();
  public void reinit(SafeArray sa);
  public void reinterpretType(int vt);
  public native void setBoolean(int idx, boolean val);
  public void setBoolean(int idx1, int idx2, boolean val);
  public void setBooleans(int sa_idx, int nelems, boolean ja[], int
        ja_start);
  public void setByte(int idx, byte val);
  public void setByte(int idx1, int idx2, byte val);
  public void setBytes(int sa_idx, int nelems, byte ja[],
        int ja_start);
  public void setChar(int idx, char val);
  public void setChar(int idx1, int idx2, char val);
  public void setChars(int sa_idx, int nelems, char ja[],
        int ja_start);
  public native void setDouble(int idx, double val);
  public void setDouble(int idx1, int idx2, double val);
  public void setDoubles(int sa_idx, int nelems, double ja[],
        int ja_start);
  public native void setFloat(int idx, float val);
  public void setFloat(int idx1, int idx2, float val);
  public void setFloats(int sa_idx, int nelems, float ja[],
        int ja_start);
  public native void setInt(int idx, int val);
  public void setInt(int idx1, int idx2, int val);
  public void setInts(int sa_idx, int nelems, int ja[],
        int ja_start);
  public void setShort(int idx, short val);
  public void setShort(int idx1, int idx2, short val);
  public void setShorts(int sa_idx, int nelems, short ja[],
        int ja_start);
  public void setString(int idx, String val);
  public void setString(int idx1, int idx2, String val);
  public void setStrings(int sa_idx, int nelems, String ja[],
        int ja_start);
  public void setVariant(int idx, Variant val);
  public void setVariant(int idx1, int idx2, Variant val);
  public void setVariants(int sa_idx, int nelems, Variant ja[], int
        ja_start);
  public boolean[] toBooleanArray();
  public byte[] toByteArray();
  public char[] toCharArray();
  public double[] toDoubleArray();
  public float[] toFloatArray();
  public int[] toIntArray();
  public short[] toShortArray();
  public String toString();
  public String[] toStringArray();
  public Variant[] toVariantArray();
}

This class wraps a Microsoft® ActiveX® Automation SAFEARRAY data structure. It bridges Java with the Automation object by wrapping a pointer to the native SAFEARRAY data structure. It does not duplicate the array data in Java form. This approach minimizes translation overhead but imposes extra rules on SafeArray usage.

The rules for using this class are simple, but they must be followed:

  1. A Java method that receives a SafeArray object as a parameter can use that object only for the duration of the method call. If a longer-term copy is needed, either the SafeArray object must be converted to a Java array, or the clone method must be used to create an independent copy of the object.
  2. If a Java method returns a SafeArray object, that object is owned by the caller; the Java method must no longer use that SafeArray instance. The simplest way to follow this rule is to have the called method construct a new SafeArray object each time it is called.

In addition to maintaining a pointer to a native SAFEARRAY data structure, a SafeArray instance separately maintains the exact variant type of SAFEARRAY data structure elements. The variant type is determined by an argument to the SafeArray class constructor or is bound into the .java file by the jactivex tool. The system class com.ms.com.Variant defines public constants (Variant.VariantXXX) for all of the valid variant types. It is important to note that neither the VariantByref nor the VariantArray modifier should be set in the element variant type; setting either of these modifiers will cause a run-time error to occur.

The SAFEARRAY data structure does not have reference counts, so the process of creating and destroying SAFEARRAY data structures cannot be made completely transparent to the Java programmer. Therefore, the SafeArray class can only be loaded by a trusted applet.

SafeArrays of type VT_UNKNOWN or VT_DISPATCH can be manipulated by using variant-typed manipulators and then extracting the COM object from the variant, as in the following example.

   SafeArray sa;
   Object elem = sa.getVariant(index).toObject();

However, support for this technique is limited to cases where the variant was obtained from an object whose threading model is either free or both. In most other cases, a WrongThreadException is thrown. The conflicting requirements of COM's apartment threading model and Java's non-message-based model preclude an efficient representation of SafeArrays of Objects.

Note for JavaTLB users: The JavaTLB tool (which has been superceded by the jactivex tool) emits an older class file format that does not provide the exact variant type. This means in some cases, the SAFEARRAY data structure will not provide enough information to determine an exact variant type. In this case, the Java runtime will choose a default variant type based on the following heuristics:

  • SAFEARRAY data structures with elements of type VT_BSTR, VT_UNKNOWN, VT_DISPATCH or VT_VARIANT are explicitly flagged as such in the SAFEARRAY data structure; thus, these will always marshal correctly.
  • If not explicitly flagged, a SAFEARRAY data structure whose element size is 1 is presumed to be of type VT_UI1. Similarly, if the element size is 2, the SAFEARRAY is presumed to be of type VT_I2. If the element size is 4, type VT_I4 is presumed, and if the element size is 8, VT_R8 is presumed. Otherwise, a ClassCastException is thrown.
  • If a variant type other than the default is needed, the interface .java files must either be rebuilt using the jactivex tool or the reinterpretType method must be used to override the default variant type.

Constructors

SafeArray

public SafeArray(int vt);

Creates a SafeArray instance that wraps the NULL pointer. The main purpose of this constructor is to pass NULL to Component Object Model (COM) methods that accept SAFEARRAYs.

The variant type of the element must be one of the Variant.VariantXXX constants. Neither the VariantByref nor the VariantArray modifier should be set in the element variant type; setting either of these modifiers will cause a run-time error to occur.

Parameter | Description
vt | The variant type of the element.

SafeArray

public SafeArray(int vt, int celems);

Creates a one-dimensional SafeArray object. Valid indices range from zero (inclusive) to celems (exclusive). Note that this convention follows the C language practice of indicating the number of elements rather than the Microsoft® Visual Basic® convention of indicating the upper bound.

The variant type of the element must be one of the Variant.VariantXXX constants. Neither the VariantArray nor the VariantByref modifier may be set.

Parameter | Description
vt | The variant type of the element.
celems | The number of elements.

SafeArray

public SafeArray(int vt, int celems1, int celems2);

Creates a two-dimensional SafeArray object. The constructor follows the C language practice of indicating the number of elements rather than the Microsoft® Visual Basic® convention of indicating the upper bound.

The expression:

new SafeArray(Variant.VariantVariant, 21, 11);

is equivalent to the Visual Basic declaration:

Option Base 0
Dim A(20, 10)

The variant type of the element must be one of the Variant.VariantXXX constants. Neither the VariantByref nor the VariantArray modifier should be set in the element variant type; setting either of these modifiers will cause a run-time error to occur.

Parameter | Description
vt | The variant type of the element.
celems1 | The number of elements in the first dimension.
celems2 | The number of elements in the second dimension.

SafeArray

public SafeArray(int vt, int lbounds[], int celems[]);

Creates a SafeArray object of arbitrary shape. The lbounds array indicates the lower bound of each dimension. The celems array (which must have the same length as lbounds) gives the number of elements that are in each dimension. If lbounds is null, all the lower bound values default to zero. The variant type of the element must be one of the Variant.VariantXXX constants. Neither the VariantArray nor VariantByref modifier may be set.

The following Java code creates a 3-dimensional SafeArray:

int lbounds[] = {-1,-3, -4};
int celems[] = {10, 20, 30};
SafeArray A = new SafeArray(Variant.VariantVariant, lbounds,
celems);

This Visual Basic declaration creates an array with the same shape as the SafeArray created above:

Dim A(-1 To 8, -3 To 16, -4 To 25)

Parameter | Description
vt | The variant type of the element.
lbounds | The lower bounds of each dimension.
celems | The number of elements in each dimension.

SafeArray

public SafeArray(String s);

Creates a VT_UI1 SafeArray object from a string. Each character of the string occupies two elements of the array to form a single Unicode character. The array is not null terminated. This constructor corresponds to the standard Automation conversion from VT_BSTR to VT_ARRAY|VT_UI1.

Parameter | Description
s | The string used to initialize the new SafeArray object.

getPhysicalSafeArray

public native int getPhysicalSafeArray();

Retrieves the linear address of the actual SAFEARRAY data structure, which is packaged as a Java integer. This method is provided only to aid in debugging. Other than displaying information, there are no useful operations that can be performed with this value from Java.

Return Value:

Returns the linear address of the represented SAFEARRAY.

Methods

asString

public native String asString();

Converts a VT_UI1 SafeArray to a string. This method corresponds to the VariantChangeType conversion from VT_ARRAY|VT_UI1 to VT_BSTR.

Return Value:

Returns the converted value.

clone

public Object clone();

Creates an exact and independent duplicate of the SafeArray object. This method is a wrapper around the Microsoft® Win32® SafeArrayCopy function.

Return Value:

Returns a new SafeArray object that contains an independent duplicate.

destroy

public void destroy();

Forcefully invokes the Win32 function SafeArrayDestroy.

Caution This is a potentially dangerous routine that should be used with extreme caution. It is not necessary to invoke this method when following standard COM memory ownership rules. This is because the Java/COM integration subsystem and the Java garbage collector work together to ensure correct disposal of SafeArrays.

Return Value:

No return value.

finalize

protected void finalize();

Performs cleanup tasks before garbage collection.

Return Value:

No return value.

fromBooleanArray

public void fromBooleanArray(boolean ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note If you are modifying a large number of elements, it may be more efficient to use fromCharArray rather than fromBooleanArray. Since boolean SafeArrays use two bytes per element, the fromBooleanArray method cannot optimize itself to a memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromByteArray

public void fromByteArray(byte ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromCharArray

public void fromCharArray(char ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromDoubleArray

public void fromDoubleArray(double ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromFloatArray

public void fromFloatArray(float ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromIntArray

public void fromIntArray(int ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromShortArray

public void fromShortArray(short ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromStringArray

public void fromStringArray(String ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

fromVariantArray

public void fromVariantArray(Variant ja[]);

Initializes SafeArray elements from a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is initialized from element zero of the Java array.

If the Java array is shorter than the number of SafeArray elements, the remaining SafeArray elements are left unmodified. If the Java array is longer than the number of SafeArray elements, the extra elements are ignored.

Note Although Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the element type. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

No return value.

Parameter | Description
ja | The Java array that contains the new values.

getBoolean

public native boolean getBoolean(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a boolean.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if sa_idx is not between the lower bound and the upper bound of the array (inclusive).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getBoolean

public boolean getBoolean(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a boolean.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if neither index is between the lower bound and the upper bound of the array (inclusive).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getBooleans

public void getBooleans(int sa_idx, int nelems, boolean ja[], int ja_start);

Extracts multiple elements as booleans. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note If you extract a large number of elements, it may be more efficient to use getChars rather than getBooleans. Since boolean SafeArray objects use two bytes per element, the getBooleans method cannot optimize itself to a memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getByte

public byte getByte(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a byte.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if sa_idx lies outside the defined range (LBound() to UBound()).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getByte

public byte getByte(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a byte.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getBytes

public void getBytes(int sa_idx, int nelems, byte ja[], int ja_start);

Extracts multiple elements as bytes. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | Java The array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getChar

public char getChar(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a character.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if sa_idx lies outside the defined range (LBound() to UBound()).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getChar

public char getChar(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional array as a character.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getChars

public void getChars(int sa_idx, int nelems, char ja[], int ja_start);

Extracts multiple elements of a SafeArray as characters. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getDouble

public native double getDouble(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a double.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx lies outside the defined range (LBound() to UBound()).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getDouble

public double getDouble(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a double.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getDoubles

public void getDoubles(int sa_idx, int nelems, double ja[], int ja_start);

Extracts multiple elements of a SafeArray as doubles. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getElemSize

public int getElemSize();

Retrieves the size of a single element.

Return Value:

Returns the size of a single element, measured in bytes.

getFeatures

public int getFeatures();

Retrieves the contents of the fFeatures bitmask. This bitmask (defined as part of the OLE SAFEARRAY data structure) provides various types of information about the SAFEARRAY.

Return Value:

Returns the fFeatures field.

getFloat

public native float getFloat(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a float.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx lies outside the defined range (LBound()..UBound()).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getFloat

public float getFloat(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a float.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getFloats

public void getFloats(int sa_idx, int nelems, float ja[], int ja_start);

Extracts multiple elements of a SafeArray as floats. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getInt

public native int getInt(int sa_idx);

Extracts an element of a one-dimensional SafeArray as an integer.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

ClassCastException if the SafeArray element cannot be converted to the correct type using the Win32 VariantChangeType function.

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx lies outside the defined range (LBound() to UBound()).

getInt

public int getInt(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional array as an integer.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

getInts

public void getInts(int sa_idx, int nelems, int ja[], int ja_start);

Extracts multiple elements of the SafeArray as integers. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getLBound

public int getLBound();

Retrieves the smallest valid index of the array's first dimension. This method is identical to the Visual Basic LBound function.

Return Value:

Returns the smallest valid index.

getLBound

public int getLBound(int dim);

Retrieves the smallest valid index of an arbitrary dimension. (Dimensions are numbered, starting with 1.) This method is identical to the Visual Basic LBound function.

Return Value:

Returns the smallest valid index.

Parameter | Description
dim | The dimension.

getNumDim

public int getNumDim();

Obtains the number of SafeArray dimensions.

Return Value:

Returns the number of dimensions in the SafeArray (2 for two-dimensional SafeArrays, for example).

getNumLocks

public int getNumLocks();

Retrieves the number of outstanding locks on the SafeArray object. This value (which is usually zero) is only useful for debugging purposes.

Return Value:

Returns the outstanding lock count.

getShort

public short getShort(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a short integer.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx lies outside the defined range (LBound() to UBound()).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getShort

public short getShort(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a short integer.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getShorts

public void getShorts(int sa_idx, int nelems, short ja[], int ja_start);

Extracts multiple elements as short integers. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getString

public String getString(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a string.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx does not lie between the lower bound and the upper bound of the array (inclusive).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getString

public String getString(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a string.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index does not lie between the lower bound and the upper bound of the array (inclusive).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getStrings

public void getStrings(int sa_idx, int nelems, String ja[], int ja_start);

Extracts multiple elements of a SafeArray as strings. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getUBound

public int getUBound();

Returns the largest valid index of the array's first dimension. This method is identical to the Microsoft® Visual Basic® UBound function.

Return Value:

Returns the largest valid index.

getUBound

public int getUBound(int dim);

Retrieves the largest valid index of an arbitrary dimension. (Dimensions are numbered starting with 1.) This method is identical to the Visual Basic UBound function.

Return Value:

Returns the largest valid index.

Parameter | Description
dim | The dimension.

getVariant

public Variant getVariant(int sa_idx);

Extracts an element of a one-dimensional SafeArray as a Variant.

Note Although the Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the SafeArray type rather than to extract first as a Variant,and then to coerce the Variant. This is true even if the SafeArray is a SafeArray of Variant.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if sa_idx does not lie between the lower bound of the array and the upper bound of the array (inclusive).

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getVariant

public Variant getVariant(int sa_idx1, int sa_idx2);

Extracts an element of a two-dimensional SafeArray as a Variant.

Note Although the Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the SafeArray type rather than to extract first as a Variant, and then to coerce the Variant. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

Returns the converted element value.

Parameter | Description
sa_idx1 | The first dimension index of the element that is extracted, which ranges from LBound(1) to UBound(1).
sa_idx2 | The second dimension index of the element that is extracted, which ranges from LBound(2) to UBound(2).

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the SafeArray element cannot be converted to the correct type by using the Win32 VariantChangeType function.

getVariants

public void getVariants(int sa_idx, int nelems, Variant ja[], int ja_start);

Extracts multiple elements as Variant objects. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note Although the Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the SafeArray type rather than to extract first as a Variant, and then to coerce the Variant. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to retrieve. This index is always zero-based.
nelems | The number of elements to retrieve.
ja | The Java array that receives the values.
ja_start | The index of the first element in ja that receives a value.

getvt

public int getvt();

Retrieves the variant type of the SafeArray elements. This corresponds to a public constant, com.ms.com.VariantXXX.

Note If JavaTLB is used to generate the Java method information that passes a SafeArray from COM to Java, the variant type may be inexact. (The element size, however, will always be correct.) JavaTLB has been superceded by the jactivex tool, which binds the exact variant type into the .class file.

Return Value:

Returns the variant type of the element.

reinit

public void reinit(SafeArray sa);

Reinitializes the SafeArray object.

Return Value:

No return value.

Parameter | Description
sa | The SafeArray object that is reinitialized.

reinterpretType

public void reinterpretType(int vt);

Forces the SafeArray to interpret elements as another variant type.

Return Value:

No return value.

Parameter | Description
vt | The new variant type of the element.

setBoolean

public native void setBoolean(int idx, boolean val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setBoolean

public void setBoolean(int idx1, int idx2, boolean val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setBooleans

public void setBooleans(int sa_idx, int nelems, boolean ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Note If you are modifying a large number of elements, it may be more efficient to use setChars rather than setBooleans. Since boolean SafeArrays use two bytes per element, the setBooleans method cannot optimize itself to a memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of first element in ja to use.

setByte

public void setByte(int idx, byte val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The index of the element to set, which ranges from the lower bound to the upper bound of the SafeArray.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setByte

public void setByte(int idx1, int idx2, byte val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setBytes

public void setBytes(int sa_idx, int nelems, byte ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimize to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of the first element in ja to use.

setChar

public void setChar(int idx, char val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The index of the element to set, which ranges from the lower bound to the upper bound of the SafeArray.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setChar

public void setChar(int idx1, int idx2, char val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setChars

public void setChars(int sa_idx, int nelems, char ja[], int ja_start);

Sets multiple elements. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of the first element in ja that is used.

setDouble

public native void setDouble(int idx, double val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from the lower bound to the upper bound of the SafeArray.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setDouble

public void setDouble(int idx1, int idx2, double val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setDoubles

public void setDoubles(int sa_idx, int nelems, double ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that provides the values.
ja_start | The index of the first element to use in ja.

setFloat

public native void setFloat(int idx, float val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not one-dimensional or if idx is not between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setFloat

public void setFloat(int idx1, int idx2, float val);

Sets an element of a two-dimensional array.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setFloats

public void setFloats(int sa_idx, int nelems, float ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element set in the SafeArray is located sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of the first element in ja to use.

setInt

public native void setInt(int idx, int val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

IndexOutOfBoundsException is thrown if the SafeArray is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setInt

public void setInt(int idx1, int idx2, int val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setInts

public void setInts(int sa_idx, int nelems, int ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element retrieved from the SafeArray is retrieved from the location that is sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that provides the values.
ja_start | The index of the first element in ja.

setShort

public void setShort(int idx, short val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if idx is not between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setShort

public void setShort(int idx1, int idx2, short val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the SafeArray is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setShorts

public void setShorts(int sa_idx, int nelems, short ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element set in the SafeArray is located sa_idx elements away from index zero.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly so that the method optimizes to a straight memory copy (memcpy).

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of the first element in ja to use.

setString

public void setString(int idx, String val);

Sets an element of a one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

IndexOutOfBoundsException if the array is not one-dimensional or if idx is not between the lower bound and the upper bound of the SafeArray (inclusive).

setString

public void setString(int idx1, int idx2, String val);

Sets an element of a two-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
idx1 | The first dimension index of the element to set, which ranges from LBound(1) to UBound(1).
idx2 | The second dimension index of the element to set, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type using the Win32 VariantChangeType function.

setStrings

public void setStrings(int sa_idx, int nelems, String ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that contains the new values.
ja_start | The index of the first element to use in ja.

setVariant

public void setVariant(int idx, Variant val);

Sets an element of a one-dimensional SafeArray.

Note Although Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the element type. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

No return value.

Parameter | Description
idx | The element index, which ranges from the index of the lower bound to the index of the upper bound.
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not one-dimensional or if idx does not lie between the lower bound and the upper bound of the SafeArray (inclusive).

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setVariant

public void setVariant(int idx1, int idx2, Variant val);

Sets an element of a two-dimensional SafeArray.

Note Although Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the element type. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

No return value.

Parameter | Description
idx1 | The first element index, which ranges from LBound(1) to UBound(1).
idx2 | The first element index, which ranges from LBound(2) to UBound(2).
val | The new element value.

Exceptions:

IndexOutOfBoundsException if the array is not two-dimensional or if either index lies outside the defined range.

ClassCastException if the Java value cannot be converted to the SafeArray element type by using the Win32 VariantChangeType function.

setVariants

public void setVariants(int sa_idx, int nelems, Variant ja[], int ja_start);

Sets multiple elements of a SafeArray. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method. The first element to be set in the SafeArray is located sa_idx elements away from index zero.

Note Although the Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the element type. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

No return value.

Parameter | Description
sa_idx | The index of the first element to set. This index is always zero-based.
nelems | The number of elements to set.
ja | The Java array that provides the values.
ja_start | The index of the first element to use in ja.

toBooleanArray

public boolean[] toBooleanArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note If you are extracting a large number of elements, it may be more efficient to use toCharArray rather than toBooleanArray. Since SafeArray objects use two bytes per element, the toBooleanArray method cannot optimize itself to a memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toByteArray

public byte[] toByteArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toCharArray

public char[] toCharArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toDoubleArray

public double[] toDoubleArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toFloatArray

public float[] toFloatArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toIntArray

public int[] toIntArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method will optimize to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toShortArray

public short[] toShortArray();

Converts the entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note This method attempts all the usual type conversions. To achieve optimal performance, ensure that the element size of the source and destination arrays match exactly, so that the method optimizes to a straight memory copy (memcpy).

Return Value:

Returns the flattened contents of the array.

toString

public String toString();

Defines the printed representation of a SafeArray object.

Return Value:

Returns the printed representation.

toStringArray

public String[] toStringArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter what the index of the lower bound of the SafeArray is, the first element is stored in element zero of the Java array.

Return Value:

Returns the flattened contents of the array.

toVariantArray

public Variant[] toVariantArray();

Converts an entire SafeArray to a Java array. If the SafeArray is multidimensional, it is treated as if it were a single linear array stored in column order. No matter where in the SafeArray the first element is located, that location is called index zero for the purposes of this method.

Note Although the Variant methods can operate on any SafeArray type, it is usually much more efficient to use the specific method for the SafeArray type rather than to extract first as a Variant, and then coerce the Variant. This is true even if the SafeArray is a SafeArray of Variants.

Return Value:

Returns the flattened contents of the array.


Class STATSTG

public final class STATSTG
{
  // Fields
  public long atime;
  public long cbSize;
  public byte clsid_b0;
  public byte clsid_b1;
  public byte clsid_b10;
  public byte clsid_b11;
  public byte clsid_b12;
  public byte clsid_b13;
  public byte clsid_b14;
  public byte clsid_b15;
  public byte clsid_b2;
  public byte clsid_b3;
  public byte clsid_b4;
  public byte clsid_b5;
  public byte clsid_b6;
  public byte clsid_b7;
  public byte clsid_b8;
  public byte clsid_b9;
  public int clsid_data1;
  public short clsid_data2;
  public short clsid_data3;
  public long ctime;
  public int grfLocksSupported;
  public int grfMode;
  public int grfStateBits;
  public long mtime;
  public String pwcsName;
  public int reserved;
  public final static int STGTY_LOCKBYTES;
  public final static int STGTY_PROPERTY;
  public final static int STGTY_STORAGE;
  public final static int STGTY_STREAM;
  public int type;
}

This class represents an STATSTG structure, which contains statistical information about an open storage, stream or byte array object.

Fields

atime
The last access time for the storage, stream, or byte array.
cbSize
The size, in bytes, of the stream or byte array.
clsid_b0
A byte field of the CLSID structure that represents the class identifier.
clsid_b1
A byte field of the CLSID structure that represents the class identifier.
clsid_b10
A byte field of the CLSID structure that represents the class identifier.
clsid_b11
A byte field of the CLSID structure that represents the class identifier.
clsid_b12
A byte field of the CLSID structure that represents the class identifier.
clsid_b13
A byte field of the CLSID structure that represents the class identifier.
clsid_b14
A byte field of the CLSID structure that represents the class identifier.
clsid_b15
A byte field of the CLSID structure that represents the class identifier.
clsid_b2
A byte field of the CLSID structure that represents the class identifier.
clsid_b3
A byte field of the CLSID structure that represents the class identifier.
clsid_b4
A byte field of the CLSID structure that represents the class identifier.
clsid_b5
A byte field of the CLSID structure that represents the class identifier.
clsid_b6
A byte field of the CLSID structure that represents the class identifier.
clsid_b7
A byte field of the CLSID structure that represents the class identifier.
clsid_b8
A byte field of the CLSID structure that represents the class identifier.
clsid_b9
A byte field of the CLSID structure that represents the class identifier.
clsid_data1
An integer field of the CLSID structure that represents the class identifier.
clsid_data2
A short integer field of the CLSID structure that represents the class identifier.
clsid_data3
A short integer field of the CLSID structure that represents the class identifier.
ctime
The creation time for the storage, stream, or byte array.
grfLocksSupported
The types of region locking supported by the stream or byte array. The value must be LOCK_WRITE, LOCK_EXCLUSIVE, or LOCK_ONLYONCE. This member is not used for storage objects.
grfMode
The access mode specified when the object was opened. This member is valid only in calls to Stat methods.
grfStateBits
The current state bits of the storage object. This member is not valid for streams or byte arrays. It is the value most recently set by the IStorage::SetStateBits method.
mtime
The last modification time for the storage, stream, or byte array.
pwcsName
The name of the structure.
reserved
Reserved.
STGTY_LOCKBYTES
The value indicating that the storage element is a byte array object.
STGTY_PROPERTY
The value indicating that the storage element is a property storage object.
STGTY_STORAGE
The value indicating that the storage element is a storage object.
STGTY_STREAM
The value indicating that the storage element is a stream object.
type
The type of storage object described by the structure. The value must be STGTY_STORAGE, STGTY_STREAM, STGTY_LOCKBYTES, or STGTY_PROPERTY.


Class Variant

public final class Variant
{
  // Fields
  public static final short VariantArray;
  public static final short VariantBoolean;
  public static final short VariantByref;
  public static final short VariantByte;
  public static final short VariantCurrency;
  public static final short VariantDate;
  public static final short VariantDispatch;
  public static final short VariantDouble;
  public static final short VariantEmpty;
  public static final short VariantError;
  public static final short VariantFloat;
  public static final short VariantInt;
  public static final short VariantNull;
  public static final short VariantObject;
  public static final short VariantShort;
  public static final short VariantString;
  public static final short VariantTypeMask;
  public static final short VariantVariant;

  // Constructors
  public Variant();
  public Variant(int val);
  public Variant(double val);
  public Variant(boolean val);
  public Variant(String val);
  public Variant(SafeArray val, boolean fByRef);
  public Variant(Object value);
  public Variant(int vartype, int val);
  public Variant(int vartype, boolean val);
  public Variant(int vartype, double val);
  public Variant(int vartype, Object val);

  // Methods
  public native void changeType (short vartype);
  public void changeType (int vartype);
  public Object clone ();
  public Variant cloneIndirect ();
  protected void finalize();
  public native boolean getBoolean ();
  public native boolean getBooleanRef ();
  public byte getByte ();
  public native byte getByteRef ();
  public long getCurrency ();
  public native long getCurrencyRef();
  public double getDate ();
  public native double getDateRef ();
  public native Object getDispatch ();
  public native Object getDispatchRef();
  public double getDouble ();
  public native double getDoubleRef ();
  public void getEmpty ();
  public int getError ();
  public native int getErrorRef ();
  public float getFloat ();
  public native float getFloatRef ();
  public int getInt ();
  public native int getIntRef ();
  public void getNull ();
  public native Object getObject ();
  public native Object getObjectRef ();
  public short getShort ();
  public native short getShortRef ();
  public native String getString ();
  public native String getStringRef ();
  public native Variant[] getVariantArray();
  public native Variant[] getVariantArrayRef();
  public short getvt ();
  public void noParam ();
  public void putBoolean (boolean val);
  public native void putBooleanRef(boolean val);
  public void putByte (byte val);
  public native void putByteArray(Object ba);
  public native void putByteRef (byte val);
  public native void putCharArray(Object ca);
  public void putCurrency (long val);
  public native void putCurrencyRef(long val);
  public void putDate (double val);
  public native void putDateRef (double val);
  public native void putDispatch (Object val);
  public native void putDispatchRef(Object val);
  public void putDouble (double val);
  public native void putDoubleRef(double val);
  public void putEmpty ( );
  public void putError (int val);
  public native void putErrorRef (int val);
  public void putFloat (float val);
  public native void putFloatRef (float val);
  public void putInt (int val);
  public native void putIntRef (int val);
  public void putNull ( );
  public native void putObject (Object val);
  public native void putObjectRef(Object val);
  public void putSafeArray(SafeArray sa);
  public void putSafeArrayRef(SafeArray sa);
  public void putShort (short val);
  public native void putShortRef (short val);
  public native void putString (String val);
  public native void putStringRef(String val);
  public native void putVariantArray(Variant v[]);
  public native void putVariantArrayRef(Variant v[]);
  public native boolean toBoolean () throws ClassCastException;
  public native byte toByte () throws ClassCastException;
  public native Object toByteArray();
  public native Object toCharArray();
  public native long toCurrency () throws ClassCastException;
  public native double toDate () throws ClassCastException;
  public native Object toDispatch () throws ClassCastException;
  public native double toDouble () throws ClassCastException;
  public native int toError () throws ClassCastException;
  public native float toFloat () throws ClassCastException;
  public native int toInt () throws ClassCastException;
  public native Object toObject () throws ClassCastException;
  public SafeArray toSafeArray() throws ClassCastException;
  public native short toShort () throws ClassCastException;
  public String toString ();
  public native Variant[] toVariantArray();
  public void VariantClear();
}

This class is used to bridge Java with Microsoft® ActiveX® components that manipulate VARIANT data types.

Most Variant methods fall into one of three categories:

  • toXXX methods, which attempt to coerce the Variant object to type XXX and return the converted value. The results of the coercion are not copied back to the Variant object. Coercion is performed by using the Microsoft® Win32® VariantChangeType function. If the Variant object cannot be converted to the requested type, a ClassCastException is thrown.
  • getXXX methods, which succeed only if the Variant object is already the correct type. If not, a ClassCastException is thrown.
  • putXXX methods, which change the type of a Variant object and initialize it to a new value. In general, it is better to construct and initialize the Variant object atomically by using an overloaded constructor rather than to use one of these methods.

Constructors

Variant

public Variant();

Creates a Variant object of type VT_EMPTY.

Variant

public Variant(int val);

Creates a Variant object of type VT_I4.

Parameter | Description
val | The initial value of the Variant object.

Variant

public Variant(double val);

Creates a Variant object of type VT_R8.

Parameter | Description
val | The initial value of the Variant object.

Variant

public Variant(boolean val);

Creates a Variant object of type VT_BOOL.

Parameter | Description
val | The initial value of the Variant object.

Variant

public Variant(String val);

Creates a Variant object of type VT_BSTR.

Parameter | Description
val | The initial value of the Variant object.

Variant

public Variant(SafeArray val, boolean fByRef);

Creates a Variant object of type VT_ARRAY or VT_BYREF|VT_ARRAY.

Typically, fByRef is set to true when you create a Variant object to pass as a parameter, and it is false when you create a Variant object that is used as a return value.

Parameter | Description
val | The initial SafeArray value.
fByRef | Indicates how to set the VT_BYREF modifier.

Remarks:

If fByRef is true, any changes made to the SAFEARRAY data structure through the new Variant object will be visible to the SafeArray instance used to initialize the Variant object.

If fByRef is false, the method revokes the SafeArray instance's ownership. Any further operations on that instance will throw an exception. This is because ownership of the SAFEARRAY data structure has been transferred to the new Variant object. To retrieve any changes made through the Variant object, you must call the toSafeArray method to obtain a new proxy.

Variant

public Variant(Object value);

Creates a Variant object of type VT_DISPATCH or VT_BYREF|VT_ARRAY.

If the argument is a Java SafeArray object, this constructor is equivalent to the following code.

Variant(value, true)

Otherwise, this constructor creates a VT_DISPATCH.

Parameter | Description
value | The initial value.

Variant

public Variant(int vartype, int val);

Creates a Variant object of the type indicated by vartype. The type can be VariantShort, VariantInt, or VariantByte. The VariantByref modifier can be set on any of these types.

Parameter | Description
vartype | The variant type.
val | The initial value.

Variant

public Variant(int vartype, boolean val);

Creates a Variant object of the type indicated by vartype. The type can be VariantBoolean, or VariantByref|VariantBoolean.

Parameter | Description
vartype | The variant type.
val | The initial value.

Variant

public Variant(int vartype, double val);

Creates a Variant object of the type indicated by vartype. The type can be VariantDouble, VariantFloat, or VariantDate. The VariantByref modifier can be set on any of these types.

Parameter | Description
vartype | The variant type.
val | The initial value.

Variant

public Variant(int vartype, Object val);

Creates a Variant object of the type indicated by vartype. The type can be VariantString, VariantObject, or VariantDispatch. The VariantByref modifier can be set on any of these types.

Parameter | Description
vartype | The variant type.
val | The initial value.

Methods

changeType

public native void changeType (short vartype);

Invokes the Win32 VariantChangeType function.

Return Value:

No return value.

changeType

public void changeType (int vartype);

Invokes the Win32 VariantChangeType function.

Return Value:

No return value.

clone

public Object clone ();

Invokes the Win32 VariantCopy function.

Return Value:

Returns the cloned Variant object.

cloneIndirect

public Variant cloneIndirect ();

Invokes the Win32 VariantCopyInd function.

Return Value:

Returns the cloned Variant object.

finalize

protected void finalize();

Performs cleanup before garbage collection.

Return Value:

No return value.

getBoolean

public native boolean getBoolean ();

Retrieves the value of a VT_BOOL Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java boolean.

Exceptions:

ClassCastException if the variant type is not VT_BOOL.

getBooleanRef

public native boolean getBooleanRef ();

Retrieves the referenced value of a VT_BYREF|VT_BOOL Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java boolean.

Exceptions:

ClassCastException if the Variant is of any other type.

getByte

public byte getByte ();

Retrieves the value of a VT_UI1 Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java byte.

Exceptions:

ClassCastException if the variant type is not VT_UI1.

getByteRef

public native byte getByteRef ();

Retrieves the referenced value of a VT_BYREF|VT_UI1 Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java byte.

Exceptions:

ClassCastException if the Variant is of any other type.

getCurrency

public long getCurrency ();

Retrieves the value of a VT_CY Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java long.

Exceptions:

ClassCastException if the variant type is not VT_CY.

getCurrencyRef

public native long getCurrencyRef();

Retrieves the referenced value of a VT_BYREF|VT_CY Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java long.

Exceptions:

ClassCastException if the Variant is of any other type.

getDate

public double getDate ();

Retrieves the value of a VT_DATE Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java double.

Exceptions:

ClassCastException if the variant type is not VT_DATE.

getDateRef

public native double getDateRef ();

Retrieves the referenced value of a VT_BYREF|VT_DATE Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java double.

Exceptions:

ClassCastException if the Variant is of any other type.

getDispatch

public native Object getDispatch ();

Retrieves the value of a VT_DISPATCH Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java object.

Exceptions:

ClassCastException if the variant type is not VT_DISPATCH.

getDispatchRef

public native Object getDispatchRef();

Retrieves the referenced value of a VT_BYREF|VT_DISPATCH Variant.

Return Value:

Returns the Variantobject's referenced value, which is converted to a Java object.

Exceptions:

ClassCastException if the Variant is of any other type.

getDouble

public double getDouble ();

Retrieves the value of a VT_R8 Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java double.

Exceptions:

ClassCastException if the variant type is not VT_R8.

getDoubleRef

public native double getDoubleRef ();

Retrieves the referenced value of a VT_BYREF|VT_R8 Variant object.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java double.

Exceptions:

ClassCastException if the Variant is of any other type.

getEmpty

public void getEmpty ();

Verifies that the variant type is VT_EMPTY. This method has no other purpose; there is no value associated with a null Variant.

Return Value:

No return value.

Exceptions:

ClassCastException if the variant type is not VT_EMPTY.

getError

public int getError ();

Retrieves the value of a VT_ERROR Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java integer.

Exceptions:

ClassCastException if the variant type is not VT_ERROR.

getErrorRef

public native int getErrorRef ();

Retrieves the referenced value of a VT_BYREF|VT_ERROR Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java integer.

Exceptions:

ClassCastException if the Variant is of any other type.

getFloat

public float getFloat ();

Retrieves the value of a VT_R4 Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java float.

Exceptions:

ClassCastException if the variant type is not VT_R4.

getFloatRef

public native float getFloatRef ();

Retrieves the referenced value of a VT_BYREF|VT_R4 Variant object.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java float.

Exceptions:

ClassCastException if the Variant is of any other type.

getInt

public int getInt ();

Retrieves the value of a VT_I4 Variant.

Return Value:

Returns the Variant object's value converted to a Java integer.

Exceptions:

ClassCastException if the variant type is not VT_I4.

getIntRef

public native int getIntRef ();

Retrieves the referenced value of a VT_BYREF|VT_I4 Variant object.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java integer.

Exceptions:

ClassCastException if the Variant is of any other type.

getNull

public void getNull ();

Verifies that the variant type is VT_NULL. This method has no other purpose; there is no value associated with a null Variant.

Return Value:

No return value.

Exceptions:

ClassCastException if the variant type is not VT_NULL.

getObject

public native Object getObject ();

Retrieves the value of a VT_UNKNOWN Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java object.

Exceptions:

ClassCastException if the variant type is not VT_UNKNOWN.

getObjectRef

public native Object getObjectRef ();

Retrieves the referenced value of a VT_BYREF|VT_UNKNOWN Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java object.

Exceptions:

ClassCastException if the Variant is of any other type.

getShort

public short getShort ();

Retrieves the value of a VT_I2 Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java short.

Exceptions:

ClassCastException if the variant type is not VT_I2.

getShortRef

public native short getShortRef ();

Retrieves the referenced value of a VT_BYREF|VT_I2 Variant object.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java short.

Exceptions:

ClassCastException if the Variant is of any other type.

getString

public native String getString ();

Retrieves the value of a VT_BSTR Variant.

Return Value:

Returns the Variant object's value, which is converted to a Java string.

Exceptions:

ClassCastException if the variant type is not VT_BSTR.

getStringRef

public native String getStringRef ();

Retrieves the referenced value of a VT_BYREF|VT_BSTR Variant.

Return Value:

Returns the Variant object's referenced value, which is converted to a Java string.

Exceptions:

ClassCastException if the Variant is of any other type.

getVariantArray

public native Variant[] getVariantArray();

Retrieves the value of a VT_ARRAY|VT_VARIANT Variant. The embedded array must be one-dimensional. This is an "expensive" method, which has been superceded by the toSafeArray method.

Return Value:

Returns the Variant's value converted to a Java array of Variants.

getVariantArrayRef

public native Variant[] getVariantArrayRef();

Retrieves the referenced value of a VT_BYREF|VT_ARRAY|VT_VARIANT Variant. The embedded array must be one-dimensional. This is an "expensive" method, which has been superceded by the toSafeArray method.

Return Value:

Returns the Variant's referenced value converted to a Java array of Variant objects.

getvt

public short getvt ();

Extracts the variant type of the Variant object.

Return Value:

Returns the variant type.

noParam

public void noParam ();

Sets a Variant object to represent a missing optional parameter. This method is equivalent to the expression

putError(0x80020004) //DISP_E_PARAMNOTFOUND

Return Value:

No return value.

putBoolean

public void putBoolean (boolean val);

Sets the Variant object to type VT_BOOL and clears the previous contents.

Note The preferred way to create a VT_BOOL Variant is to use the following expression.

new Variant(val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putBooleanRef

public native void putBooleanRef(boolean val);

Replaces a value referenced by a VT_BYREF|VT_BOOL Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantBoolean,val).

Return Value:

No return value.

Parameter | Description
val | The new value.

putByte

public void putByte (byte val);

Sets the Variant object to be type VT_UI1 and clears the previous contents.

Note The preferred way to create a VT_UI1 Variant is to use the following expression.

new Variant(Variant.VariantByte, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putByteArray

public native void putByteArray(Object ba);

Sets a Variant object to type VT_ARRAY|VT_UI1 and clears the previous contents.

Return Value:

No return value.

Parameter | Description
ba | The initial values of the elements, which must be byte[].

putByteRef

public native void putByteRef (byte val);

Replaces a value referenced by a VT_BYREF|VT_UI1 Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantByte,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putCharArray

public native void putCharArray(Object ca);

Sets Variant to type VT_ARRAY|VT_I2 and clears the previous contents.

Return Value:

No return value.

Parameter | Description
ca | The initial values of the elements, which must be char[].

putCurrency

public void putCurrency (long val);

Sets the Variant object to type VT_CY and clears the previous contents.

Return Value:

No return value.

Parameter | Description
val | The new value.

putCurrencyRef

public native void putCurrencyRef(long val);

Replaces a value referenced by a VT_BYREF|VT_CY Variant object.

Return Value:

No return value.

Parameter | Description
val | The new value.

putDate

public void putDate (double val);

Sets the Variant object to type VT_DATE and clears the previous contents.

Note The preferred way to create a VT_DATE Variant is to use the following expression.

new Variant(Variant.VariantDate, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putDateRef

public native void putDateRef (double val);

Replaces a value referenced by a VT_BYREF|VT_DATE Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantDate,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putDispatch

public native void putDispatch (Object val);

Sets the Variant object to type VT_DISPATCH and clears the previous contents.

Note The preferred way to create a VT_DISPATCH Variant is to use the following expression.

new Variant(val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putDispatchRef

public native void putDispatchRef(Object val);

Replaces a value referenced by a VT_BYREF|VT_DISPATCH Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantDispatch,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putDouble

public void putDouble (double val);

Sets the Variant object to type VT_R8 and clears the previous contents.

Note The preferred way to create a VT_R8 Variant is to use the following expression.

new Variant(val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putDoubleRef

public native void putDoubleRef(double val);

Replaces a value referenced by a VT_BYREF|VT_R8 Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantDouble,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putEmpty

public void putEmpty ( );

Sets the Variant object to type VT_EMPTY and clears the previous contents. The expression

new Variant()

creates a new Variant object that is already type VT_EMPTY, so it is not necessary to invoke the putEmpty method on such an object.

Return Value:

No return value.

putError

public void putError (int val);

Sets the Variant object to type VT_ERROR and clears the previous contents. This object is normally passed as a placeholder for a missing optional parameter.

Note The preferred way to generate a missing parameter is to use the following code.

Variant v = new Variant(val);
v.noParam();

Return Value:

No return value.

Parameter | Description
val | The new value.

putErrorRef

public native void putErrorRef (int val);

Replaces a value referenced by a VT_BYREF|VT_ERROR Variant.

Return Value:

No return value.

Parameter | Description
val | The new value.

putFloat

public void putFloat (float val);

Sets the Variant object to type VT_R4 and clears the previous contents.

Note The preferred way to create a VT_R4 Variant is to use the following expression.

new Variant(Variant.VariantFloat, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putFloatRef

public native void putFloatRef (float val);

Replaces a value referenced by a VT_BYREF|VT_R4 Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantFloat,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putInt

public void putInt (int val);

Sets the Variant object to type VT_I4 and clears the previous contents.

Note The preferred way to create a VT_I4 Variant is to use the following expression.

new Variant(val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putIntRef

public native void putIntRef (int val);

Replaces a value referenced by a VT_BYREF|VT_I4 Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantInt,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putNull

public void putNull ( );

Sets the Variant object to type VT_NULL and clears the previous contents.

Return Value:

No return value.

putObject

public native void putObject (Object val);

Sets the Variant object to be type VT_UNKNOWN and clears the previous contents.

Note The preferred way to create a VT_UNKNOWN Variant is to use the following expression.

new Variant(Variant.VariantObject, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putObjectRef

public native void putObjectRef(Object val);

Replaces a value referenced by a VT_BYREF|VT_UNKNOWN Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantObject, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putSafeArray

public void putSafeArray(SafeArray sa);

Sets the Variant object to type SAFEARRAY and clears the previous contents. This method sets the variant type to VT_ARRAY.

Return Value:

No return value.

Parameter | Description
sa | The SafeArray object.

putSafeArrayRef

public void putSafeArrayRef(SafeArray sa);

Replaces a SafeArray object referenced by the Variant. This method sets the variant type to VT_BYREF|VT_ARRAY.

Return Value:

No return value.

Parameter | Description
sa | The new SafeArray.

putShort

public void putShort (short val);

Sets the Variant object to type VT_I2 and clears the previous contents.

Note The preferred way to create a VT_I2 Variant is to use the following expression.

new Variant(Variant.VariantShort, val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putShortRef

public native void putShortRef (short val);

Replaces a value referenced by a VT_BYREF|VT_I2 Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is to use the following expression.

new Variant(Variant.VariantByref|Variant.VariantShort,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putString

public native void putString (String val);

Sets the Variant object to type VT_BSTR and clears the previous contents.

Note The preferred way to create a VT_BSTR Variant is to use the following expression.

new Variant(val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putStringRef

public native void putStringRef(String val);

Replaces a value referenced by a VT_BYREF|VT_BSTR Variant object.

Note This method can also be used to initialize a Variant, but the preferred method is use the following expression.

new Variant(Variant.VariantByref|Variant.VariantString,val)

Return Value:

No return value.

Parameter | Description
val | The new value.

putVariantArray

public native void putVariantArray(Variant v[]);

Sets a Variant object to a typeVT_ARRAY|VT_VARIANT Variant object, which holds a zero-based, one-dimensional SafeArray.

Return Value:

No return value.

Parameter | Description
v | Provides initial values for the SAFEARRAY elements.

putVariantArrayRef

public native void putVariantArrayRef(Variant v[]);

Replaces a SAFEARRAY data structure, which is referenced by a VT_BYREF|VT_ARRAY|VT_VARIANT Variant.

Note This method can also be used to initialize a Variant object, but the preferred method is to pass a SafeArray object to the Variant constructor.

Return Value:

No return value.

Parameter | Description
v | Provides initial values for the SAFEARRAY elements.

toBoolean

public native boolean toBoolean () throws ClassCastException;

Coerces the Variant object to a VT_BOOL and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java boolean.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toByte

public native byte toByte () throws ClassCastException;

Coerces the Variant object to a VT_UI1 and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java byte.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toByteArray

public native Object toByteArray();

Retrieves the value of a VT_ARRAY|VT_UI1 or VT_BYREF|VT_ARRAY|VT_UI1 as a one-dimensional byte[] array. This method has been superceded by the toSafeArray method.

Return Value:

Returns a byte array.

toCharArray

public native Object toCharArray();

Retrieves the value of a VT_ARRAY|VT_I2 or VT_BYREF|VT_ARRAY|VT_I2 as a one-dimensional char[] array. This method has been superceded by the toSafeArray method.

Return Value:

Returns a character array.

toCurrency

public native long toCurrency () throws ClassCastException;

Coerces the Variant object to a VT_CY and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value converted to a Java long.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toDate

public native double toDate () throws ClassCastException;

Coerces the Variant object to a VT_DATE and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java double.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toDispatch

public native Object toDispatch () throws ClassCastException;

Coerces the Variant object to a VT_DISPATCH and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java object.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toDouble

public native double toDouble () throws ClassCastException;

Coerces the Variant object to a VT_R8 and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value converted to a Java double.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toError

public native int toError () throws ClassCastException;

Coerces the Variant object to a VT_ERROR and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java integer.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toFloat

public native float toFloat () throws ClassCastException;

Coerces the Variant object to a VT_R4 and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value converted to a Java float.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toInt

public native int toInt () throws ClassCastException;

Coerces the Variant object to a VT_I4 and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value converted to a Java integer.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toObject

public native Object toObject () throws ClassCastException;

Coerces the Variant object to a VT_UNKNOWN and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java object.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toSafeArray

public SafeArray toSafeArray() throws ClassCastException;

Extracts a SafeArray object from a Variant object that has the VT_ARRAY modifier set. This operation does not create an independent SafeArray object, so it can be used to modify the elements of the SafeArray object that is referenced by the Variant.

Return Value:

Returns the coerced value that is converted to a Java SafeArray object.

Exceptions:

ClassCastException if the object's type cannot be coerced.

toShort

public native short toShort () throws ClassCastException;

Coerces the Variant object to a VT_I2 and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value converted to a Java short.

Exceptions:

ClassCastException if the Variant object's type cannot be coerced.

toString

public String toString ();

Coerces the Variant object to a VT_BSTR and returns the coerced result. The results of the coercion are not stored in the Variant.

Return Value:

Returns the coerced value that is converted to a Java string.

Remarks:

Unlike the other toXXX methods, no exception is thrown if the variant cannot be coerced to a string. Instead, the toString method of the Object class is called. This is because toString is also the method used for diagnostic printing of all Java objects.

toVariantArray

public native Variant[] toVariantArray();

Retrieves the value of either a VT_ARRAY|VT_VARIANT or VT_BYREF|VT_ARRAY|VT_VARIANT Variant. The embedded array must be one-dimensional. This is an "expensive" method, which has been superceded by the toSafeArray method.

Return Value:

Returns the coerced value converted to a Java array of Variants.

VariantClear

public void VariantClear();

Forces the Microsoft® Win32® VariantClear function to be called and resets the Variant object to VT_EMPTY.

Return Value:

No return value.

Fields

VariantArray
Corresponds to the VT_ARRAY modifier.
VariantBoolean
Corresponds to the VT_BOOL variant type.
VariantByref
Corresponds to the VT_BYREF modifier.
VariantByte
Corresponds to the VT_UI1 variant type.
VariantCurrency
Corresponds to the VT_CY variant type.
VariantDate
Corresponds to the VT_DATE variant type.
VariantDispatch
Corresponds to the VT_DISPATCH variant type.
VariantDouble
Corresponds to the VT_R8 variant type.
VariantEmpty
Corresponds to the VT_EMPTY variant type.
VariantError
Corresponds to the VT_ERROR variant type.
VariantFloat
Corresponds to the VT_R4 variant type.
VariantInt
Corresponds to the VT_I4 variant type.
VariantNull
Corresponds to the VT_NULL variant type.
VariantObject
Corresponds to the VT_UNKNOWN variant type.
VariantShort
Corresponds to the VT_I2 variant type.
VariantString
Corresponds to the VT_BSTR variant type.
VariantTypeMask
Masks off variant type modifiers.
VariantVariant
Corresponds to the VT_VARIANT variant type.


Class WrongThreadException

public class WrongThreadException extends RuntimeException
{
  // Constructors
  public WrongThreadException();
  public WrongThreadException(String s);
}

This class represents objects that are thrown when a method call cannot be made because it was called on the wrong thread. Typically, WrongThreadException objects are thrown when an operation invokes an Apartment Model Component Object Model (COM) object on the wrong thread.

RuntimeException
  |
  +--WrongThreadException

Constructors

WrongThreadException

public WrongThreadException();

Creates an instance of the WrongThreadException class.

WrongThreadException

public WrongThreadException(String s);

Creates an instance of the WrongThreadException class that contains a description of the exception.

Parameter | Description
s | A description of the exception.


Interface ComContext

public interface ComContext
{
  // Fields
  public static final int INPROC_HANDLER;
  public static final int INPROC_HANDLER16;
  public static final int INPROC_HANDLERX86;
  public static final int INPROC_SERVER;
  public static final int INPROC_SERVER16;
  public static final int INPROC_SERVERX86;
  public static final int LOCAL_SERVER;
  public static final int REMOTE_SERVER;
}

This class defines constants that specify the contexts that a Component Object Model (COM) class can run in.

Fields

INPROC_HANDLER
A handler DLL that runs in the same process as the caller.
INPROC_HANDLER16
A 16-bit handler DLL that runs in the same process as the caller.
INPROC_HANDLERX86
An x86 handler DLL that runs in the same process as the caller.
INPROC_SERVER
A server DLL that runs in the same process as the caller.
INPROC_SERVER16
A 16-bit server DLL that runs in the same process as the caller.
INPROC_SERVERX86
An x86 server DLL that runs in the same process as the caller.
LOCAL_SERVER
A server .exe file that runs on the same computer as the caller but in a different process.
REMOTE_SERVER
A remote server .exe file that runs on a different computer than the caller does.


Interface IAccessible

public interface IAccessible extends IUnknown
{
  // Fields
  public static final _Guid iid;

  // Methods
  public void accDoDefaultAction(Variant varChild);
  public Variant accHitTest(int xLeft, int yTop);
  public void accLocation(int[] pxLeft, int[] pyTop,
        int[] pcxWidth, int[] pcyHeight, Variant varChild);
  public Variant accNavigate(int navDir, Variant varStart);
  public void accSelect(int flagsSelect, Variant varChild);
  public Object getAccChild(Variant varChild);
  public int getAccChildCount();
  public String getAccDefaultAction(Variant varChild);
  public String getAccDescription(Variant varChild);
  public Variant getAccFocus();
  public String getAccHelp(Variant varChild);
  public int getAccHelpTopic(String[] pszHelpFile,
        Variant varChild);
  public String getAccKeyboardShortcut(Variant varChild);
  public String getAccName(Variant varChild);
  public Object getAccParent();
  public Variant getAccRole(Variant varChild);
  public Variant getAccSelection();
  public Variant getAccState(Variant varChild);
  public String getAccValue(Variant varChild);
  public void setAccName(Variant varChild, String pszName);
  public void setAccValue(Variant varChild, String pszValue);
}

This interface provides methods that enable users to request selection and focus information, perform hit tests, and navigate by using object and child identifiers.

Accessible objects maintain properties that help describe the object's appearance, nature, and purpose. The IAccessible interface extends methods that enable a client application to retrieve these properties. By using the information that these properties provide, an accessibility aid can determine useful information and convey it as needed.

In the following methods, the Variant object varChild identifies a child of the IAccessible object or indicates the object itself. This value of this parameter can be the child ID value (provided by the object), CHILDID_SELF for the object itself, or a string identifying the child ( such as "A1").

If a container object does not support the IEnumVariant interface, its child ID numbers must be sequential positive integers starting with 1. If the object supports IEnumVariant, it can use any method to assign its child ID numbers.

IUnknown
  |
  +--IAccessible

Methods

accDoDefaultAction

public void accDoDefaultAction(Variant varChild);

Performs the object's default action.

Return Value:

No return value.

Parameter | Description
varChild | A value that identifies the child object whose default action is performed.

accHitTest

public Variant accHitTest(int xLeft, int yTop);

Retrieves the child object at a specified location on the screen. That is, a point on the screen is tested to see if there is a child object (a hit) located at that point.

Return Value:

Returns a Variant object that describes the child object located at the specified coordinates.

Parameter | Description
xLeft | The x coordinate of the point on the screen that is hit-tested.
yTop | The y coordinate of the point on the screen that is hit-tested.

accLocation

public void accLocation(int[] pxLeft, int[] pyTop, int[] pcxWidth,
        int[] pcyHeight, Variant varChild);

Retrieves the screen location of an accessibility object. The varChild parameter indicates whether this method will retrieve the coordinates of the container itself or of one of its children.

Return Value:

No return value.

Parameter | Description
pxLeft | The retrieved x coordinate of the object's screen location.
pyTop | The retrieved y coordinate of the object's screen location.
pcxWidth | The object's retrieved width, measured in pixels.
pcyHeight | The object's retrieved height, measured in pixels.
varChild | A value that identifies the child object whose location is retrieved.

accNavigate

public Variant accNavigate(int navDir, Variant varStart);

Retrieves the sibling or child object that is navigated to in a specified direction.

Return Value:

Returns a Variant object that contains information about the object that is navigated to.

Parameter | Description
navDir | The navigation code that specifies the navigation direction.
varStart | A Variant object that specifies the type of navigation desired. If the variant type is VT_EMPTY, the method retrieves a sibling object. If the variant type is VT_I4 and the value is CHILDID_SELF, the method retrieves a child object.

accSelect

public void accSelect(int flagsSelect, Variant varChild);

Changes focus and modifies selection according to specified flags.

Return Value:

No return value.

Parameter | Description
flagsSelect | The selection flags, which indicate how to change the focus and selection. They must be set to some combination of the following: SELFLAG_NONE, SELFLAG_TAKEFOCUS, SELFLAG_TAKESELECTION, SELFLAG_EXTENDSELECTION, SELFLAG_ADDSELECTION, and SELFLAG_REMOVESELECTION.
varChild | A value that identifies the child object that is selected.

getAccChild

public Object getAccChild(Variant varChild);

Retrieves a specified child object.

Return Value:

Returns the requested child object.

Parameter | Description
varChild | A Variant object that identifies the child to retrieve.

getAccChildCount

public int getAccChildCount();

Retrieves the number of components in the parent container.

Return Value:

Returns the number of components in the parent container.

getAccDefaultAction

public String getAccDefaultAction(Variant varChild);

Retrieves the default action for a specified child object.

Return Value:

Returns a string that describes the default action of the child object.

Parameter | Description
varChild | A value that identifies the child object for which the default action is requested.

getAccDescription

public String getAccDescription(Variant varChild);

Retrieves a description of the child object.

Return Value:

Returns a description of the child object.

Parameter | Description
varChild | The value that identifies the child whose description is retrieved.

getAccFocus

public Variant getAccFocus();

Retrieves the child object that currently has the keyboard focus. If the object itself has the keyboard focus, this method returns zero as a VT_14 type. If a child has the focus but isn't an accessible object, it returns the child ID as a VT_14 type. If a child has the focus and is an accessible object, this method returns its IDispatch interface.

Return Value:

Returns the Variant object that contains information about the retrieved child object.

getAccHelp

public String getAccHelp(Variant varChild);

Provides Help text associated with the object.

Return Value:

Returns a string that describes the object's function.

Parameter | Description
varChild | A value that identifies the child object for which the Help text is requested.

getAccHelpTopic

public int getAccHelpTopic(String[] pszHelpFile, Variant varChild);

Retrieves the full path of the Help file associated with the object, as well as a value that identifies the Help file topic. This method is not implemented at this time.

Return Value:

Returns a value that identifies the object's Help topic.

Parameter | Description
pszHelpFile | The retrieved Help file path for the object.
varChild | A value that identifies the child object for which the Help topic is requested.

getAccKeyboardShortcut

public String getAccKeyboardShortcut(Variant varChild);

Retrieves the keyboard shortcut that selects the object.

Return Value:

Returns a string that describes a sequence of keystrokes for selecting the object.

Parameter | Description
varChild | A value that identifies the child object for which the keyboard shortcut is requested.

Exceptions:

com.ms.com.ComFailException if the specified object is not valid.

getAccName

public String getAccName(Variant varChild);

Retrieves the name property of the child object.

Return Value:

Returns the name of the child object.

Parameter | Description
varChild | The value that identifies the child whose name is retrieved.

getAccParent

public Object getAccParent();

Retrieves the parent object (the container) of the child object.

Return Value:

Returns the parent of the object.

getAccRole

public Variant getAccRole(Variant varChild);

Retrieves the role property of a specified child object.

Return Value:

Returns a Variant object that contains a role constant or a string that describes the object's role.

Parameter | Description
varChild | The value that identifies the child object whose role is requested.

getAccSelection

public Variant getAccSelection();

Retrieves the selected children of the object.

Return Value:

Returns a Variant object that identifies the child object or objects that are selected.

getAccState

public Variant getAccState(Variant varChild);

Retrieves the current state code of the object.

Return Value:

Returns a Variant object that describes the state of the object, either a string or a value equal to one or more of the object state constants.

Parameter | Description
varChild | The value that identifies the child object for which the state code is requested.

getAccValue

public String getAccValue(Variant varChild);

Retrieves the value property of the child object.

Return Value:

Returns the value of the child object.

Parameter | Description
varChild | The Variant object that identifies the child whose value is retrieved.

setAccName

public void setAccName(Variant varChild, String pszName);

Sets the name of a child object.

Return Value:

No return value.

Parameter | Description
varChild | A value that identifies the child object whose name is set by this method.
pszName | The child object's new name.

setAccValue

public void setAccValue(Variant varChild, String pszValue);

Sets the value of a child object.

Return Value:

No return value.

Parameter | Description
varChild | The Variant object that identifies the child whose value is set by this method.
pszValue | The new value.

Fields

iid
The interface identifier.


Interface IAccessibleDefault

public interface IAccessibleDefault extends IAccessible
{
  // Fields
  public static final _Guid iid;

  // Methods
  public void accDoDefaultAction(Variant varChild);
  public Variant accHitTest(int xLeft, int yTop);
  public void accLocation(int[] pxLeft, int[] pyTop,
        int[] pcxWidth, int[] pcyHeight, Variant varChild);
  public Variant accNavigate(int navDir, Variant varStart);
  public void accSelect(int flagsSelect, Variant varChild);
  public Object getAccChild(Variant varChild);
  public int getAccChildCount();
  public String getAccDefaultAction(Variant varChild);
  public String getAccDescription(Variant varChild);
  public Variant getAccFocus();
  public String getAccHelp(Variant varChild);
  public int getAccHelpTopic(String[] pszHelpFile,
        Variant varChild);
  public String getAccKeyboardShortcut(Variant varChild);
  public String getAccName(Variant varChild);
  public Object getAccParent();
  public Variant getAccRole(Variant varChild);
  public Variant getAccSelection();
  public Variant getAccState(Variant varChild);
  public String getAccValue(Variant varChild);
  public void setAccName(Variant varChild, String pszName);
  public void setAccValue(Variant varChild, String pszValue);
}

This interface provides methods that enable users to request selection and focus information, perform hit tests, and navigate by using object and child identifiers. IAccessibleDefault extends the IAccessible interface.

In the following methods, the Variant object varChild identifies a child of the IAccessible object or indicates the object itself. This value of this parameter can be the child ID value (provided by the object), CHILDID_SELF for the object itself, or a string identifying the child (such as "A1").

If a container object does not support the IEnumVariant interface, its child ID numbers must be sequential positive integers starting with 1. If the object supports IEnumVariant, it can use any method to assign its child ID numbers.

IUnknown
  |
  +--IAccessible
    |
    +--IAccessibleDefault

Methods

accDoDefaultAction

public void accDoDefaultAction(Variant varChild);

Performs the object's default action.

Return Value:

No return value.

Parameter | Description
varChild | A value that identifies the child object whose default action is performed.

Overrides:

accDoDefaultAction(Variant) in IAccessible.

accHitTest

public Variant accHitTest(int xLeft, int yTop);

Retrieves the child object at a specified location on the screen. That is, a point on the screen is tested to see if there is a child object (a hit) located at that point.

Return Value:

Returns a Variant object that describes the child object located at the specified coordinates.

Parameter | Description
xLeft | The x coordinate of the point on the screen that is hit-tested.
yTop | The y coordinate of the point on the screen that is hit-tested

Overrides:

accHitTest(int,int) in IAccessible.

accLocation

public void accLocation(int[] pxLeft, int[] pyTop, int[] pcxWidth,
        int[] pcyHeight, Variant varChild);

Retrieves the screen location of an accessibility object. The varChild parameter indicates whether this method will retrieve the coordinates of the container itself or of one of its children.

Return Value:

No return value.

Parameter | Description
pxLeft | The retrieved x coordinate of the object's screen location.
pyTop | The retrieved y coordinate of the object's screen location.
pcxWidth | The object's retrieved width, measured in pixels.
pcyHeight | The object's retrieved height, measured in pixels.
varChild | A value that identifies the child object whose location is retrieved.

Overrides:

accLocation(int[],int[],int[],int[],Variant) in IAccessible.

accNavigate

public Variant accNavigate(int navDir, Variant varStart);

Retrieves the sibling or child object that is navigated to in a specified direction.

Return Value:

Returns a Variant object that contains information about the object that is navigated to.

Parameter | Description
navDir | The navigation code that specifies the navigation direction.
varStart | The Variant object that specifies the type of navigation needed. If the variant type is VT_EMPTY, the method retrieves a sibling object. If the variant type is VT_I4 and the value is CHILDID_SELF, the method retrieves a child object.

Overrides:

accNavigate(int,Variant) in IAccessible.

accSelect

public void accSelect(int flagsSelect, Variant varChild);

Changes focus and modifies selection according to specified flags.

Return Value:

No return value.

Parameter | Description
flagsSelect | The selection flags, which indicate how to change the focus and selection. They must be set to some combination of the following: SELFLAG_NONE, SELFLAG_TAKEFOCUS, SELFLAG_TAKESELECTION, SELFLAG_EXTENDSELECTION, SELFLAG_ADDSELECTION, and SELFLAG_REMOVESELECTION.
varChild | A value that identifies the child object that is selected.

Overrides:

accSelect(int,Variant) in IAccessible.

getAccChild

public Object getAccChild(Variant varChild);

Retrieves a specified child object.

Return Value:

Returns the requested child object.

Parameter | Description
varChild | A Variant object that identifies the child to retrieve.

Overrides:

getAccChild(Variant) in IAccessible.

getAccChildCount

public int getAccChildCount();

Retrieves the number of components in the parent container.

Return Value:

Returns the number of components in the parent container.

Overrides:

getAccChildCount() in IAccessible.

getAccDefaultAction

public String getAccDefaultAction(Variant varChild);

Retrieves the default action for a specified child object.

Return Value:

Returns a string that describes the default action of the child object.

Parameter | Description
varChild | A value that identifies the child object that the default action is requested for.

Overrides:

getAccDefaultAction(Variant) in IAccessible.

getAccDescription

public String getAccDescription(Variant varChild);

Retrieves a description of the child object.

Return Value:

Returns a description of the child object.

Parameter | Description
varChild | The value that identifies the child whose description is retrieved.

Overrides:

getAccDescription(Variant) in IAccessible.

getAccFocus

public Variant getAccFocus();

Retrieves the child object that currently has the keyboard focus. If the object itself has the keyboard focus, this method returns zero as a VT_14 type. If a child has the focus but isn't an accessible object, it returns the child ID as a VT_14 type. If a child has the focus and is an accessible object, this method returns its IDispatch interface.

Return Value:

Returns the Variant object that contains information about the retrieved child object.

Overrides:

getAccFocus() in IAccessible.

getAccHelp

public String getAccHelp(Variant varChild);

Provides Help text associated with the object.

Return Value:

Returns a string that describes the object's function.

Parameter | Description
varChild | A value that identifies the child object that the Help text is requested for.

Overrides:

getAccHelp(Variant) in IAccessible.

getAccHelpTopic

public int getAccHelpTopic(String[] pszHelpFile, Variant varChild);

Retrieves the full path of the Help file associated with the object, as well as a value that identifies the Help file topic. This method is not implemented at this time.

Return Value:

Returns a value that identifies the object's Help topic.

Parameter | Description
pszHelpFile | The retrieved Help file path for the object.
varChild | A value that identifies the child object that the Help topic is requested for.

Overrides:

getAccHelpTopic(String[],Variant) in IAccessible.

getAccKeyboardShortcut

public String getAccKeyboardShortcut(Variant varChild);

Retrieves the keyboard shortcut that selects the object.

Return Value:

Returns a string that describes a sequence of keystrokes for selecting the object.

Parameter | Description
varChild | A value that identifies the child object that the keyboard shortcut is requested for.

Overrides:

getAccKeyboardShortcut(Variant) in IAccessible.

Exceptions:

com.ms.com.ComFailException if the specified object is not valid.

getAccName

public String getAccName(Variant varChild);

Retrieves the name property of the child object.

Return Value:

Returns the name of the child object.

Parameter | Description
varChild | The value that identifies the child whose name is retrieved.

Overrides:

getAccName(Variant) in IAccessible.

getAccParent

public Object getAccParent();

Retrieves the parent object (the container) of the child object.

Return Value:

Returns the parent of the object.

Overrides:

getAccParent() in IAccessible.

getAccRole

public Variant getAccRole(Variant varChild);

Retrieves the role property of a specified child object.

Return Value:

Returns a Variant object that contains a role constant or a string that describes the object's role.

Parameter | Description
varChild | The value that identifies the child object whose role is requested.

Overrides:

getAccRole(Variant) in IAccessible.

getAccSelection

public Variant getAccSelection();

Retrieves the selected children of the object.

Return Value:

Returns a Variant object that identifies the object or objects that are selected.

Overrides:

getAccSelection() in IAccessible.

getAccState

public Variant getAccState(Variant varChild);

Retrieves the current state code of the object.

Return Value:

Returns a Variant that describes the state of the object, either a string or a value equal to one or more of the object state constants.

Parameter | Description
varChild | The value that identifies the child object that the state code is requested for.

Overrides:

getAccState(Variant) in IAccessible.

getAccValue

public String getAccValue(Variant varChild);

Retrieves the value property of the child object.

Return Value:

Returns the value of the child object.

Parameter | Description
varChild | The Variant object that identifies the child whose value is retrieved.

Overrides:

getAccValue(Variant) in IAccessible.

setAccName

public void setAccName(Variant varChild, String pszName);

Sets the name of a child object.

Return Value:

No return value.

Parameter | Description
varChild | A value that identifies the child object whose name is set by this method.
pszName | The child object's new name.

Overrides:

setAccName(Variant,String) in IAccessible.

setAccValue

public void setAccValue(Variant varChild, String pszValue);

Sets the value of a child object.

Return Value:

No return value.

Parameter | Description
varChild | The Variant object that identifies the child whose value is set by this method.
pszValue | The new value.

Overrides:

setAccValue(Variant,String) in IAccessible.

Fields

iid
The interface identifier.


Interface IEnumVariant

public interface IEnumVariant extends IUnknown
{
  // Methods
  public IEnumVariant Clone();
  public void Next(int celt, Variant[] rgvar, int[] pceltFetched);
  public void Reset();
  public void Skip(int celt);
}

This interface provides methods for enumerating a collection of variants. You do not need to know the specific type (or types) of elements in the collection. This interface wraps the Component Object Model (COM) interface, IEnumVARIANT.

IUnknown
  |
  +--IEnumVariant

Methods

Clone

public IEnumVariant Clone();

Clones the IEnumVariant object.

Return Value:

Returns an IEnumVariant object identical to the current object.

Next

public void Next(int celt, Variant[] rgvar, int[] pceltFetched);

Retrieves elements from the enumeration sequence.

Return Value:

No return value.

Parameter | Description
celt | The number of elements to retrieve.
rgvar | The elements retrieved.
pceltFetched | The number of elements retrieved.

Reset

public void Reset();

Resets the index to the start of the enumeration.

Return Value:

No return value.

Skip

public void Skip(int celt);

Skips elements in the enumeration.

Return Value:

No return value.

Parameter | Description
celt | The number of elements to skip.


Interface IExternalConnectionSink

public interface IExternalConnectionSink
{
  // Methods
  public void OnAddConnection(int exconn, int reserved,
        int refcount);
  public void OnReleaseConnection(int exconn, int reserved, boolean
        fLastReleaseCloses, int refcount);
}

This interface provides methods that allow Java objects exposed as Component Object Model (COM) objects to receive notifications about calls made to the IExternalConnection interface that is exposed by the Microsoft® Win32® VM for Java. The methods in this interface are notifications, not overrides. The virtual machine always processes the IExternalConnection methods first to manage the lifetime of the objects.

Methods

OnAddConnection

public void OnAddConnection(int exconn, int reserved, int refcount);

Notifies the object that a connection has been added. Both exconn and reserved correspond to the similarly named parameters of the IExternalConnection::AddConnection method.

Caution The value of refcount is advisory only; it is guaranteed to be zero if and only if the last external lock on the object has been released. However, refcount can be printed out for diagnostic purposes.

Return Value:

No return value.

Parameter | Description
exconn | The type of external connection.
reserved | Used by Microsoft® ActiveX® to pass connection information.
refcount | The new reference count of the COM proxy.

OnReleaseConnection

public void OnReleaseConnection(int exconn, int reserved,
        boolean fLastReleaseCloses, int refcount);

Notifies the object that a connection has been released. Both exconn and reserved correspond to the similarly named parameters of the IExternalConnection::AddConnection method.

Caution The value of refcount is advisory only; it is guaranteed to be zero if and only if the last external lock on the object has been released. However, refcount can be printed out for diagnostic purposes.

Return Value:

No return value.

Parameter | Description
exconn | The type of external connection.
reserved | Used by ActiveX to pass connection information.
refcount | The new reference count of the COM proxy.
fLastReleaseCloses | If set to true and if refcount is zero, the close action for the object is initiated.


Interface ILicenseMgr

public interface ILicenseMgr extends IUnknown
{
  // Methods
  public IUnknown createFromPackage(int index, IUnknown punkOuter,
        int ctxFlags);
  public IUnknown createInstance(String clsid, IUnknown punkOuter,
        int ctxFlags);
  public IUnknown createWithLic(String lic, String clsid,
        IUnknown punkOuter, int ctxFlags);
  public void setPackage(String url);
}

This interface supports the use of licensed Component Object Model (COM) components or controls in a Java application. A licensed control cannot be instantiated except by legal users. Using a design-time license, however, enables you to embed the control in your applications. When you distribute the application, a run-time license allows the control to be instantiated when the application is run.

An HTML page containing licensed controls must include an associated license package (.lpk) file, which stores the run-time control licenses. Use the License Package Authoring Tool (lpk_tool.exe) included with the Microsoft® ActiveX® SDK to create a .lpk file. For further information on the ActiveX licensing scheme, refer to the ActiveX SDK.

To use the ILicenseMgr class with a licensed control, call the createWithLic method and specify the license string explicitly to create an instance of the control.

An example of a licensed component is the _DBEngine component in Data Access Objects (DAO). You must use the ILicenseMgr class when you use DAO.

Note For compatibility with the Microsoft SDK for Java 1.0, the following methods instantiate all COM objects on the main apartment thread of the process. Because of the significant thread-switching overhead, these methods should not be used unless the object requires licensing information.

IUnknown
  |
  +--ILicenseMgr

Methods

createFromPackage

public IUnknown createFromPackage(int index, IUnknown punkOuter,
        int ctxFlags);

Creates a package.

Return Value:

Returns the new package.

Parameter | Description
index | The index of the package.
punkOuter | The aggregating object if the object is created as part of an aggregate; otherwise, null.
ctxFlags | The ComContext value that represents the context that the new object is created in.

createInstance

public IUnknown createInstance(String clsid, IUnknown punkOuter,
        int ctxFlags);

Creates an instance of the specified COM class.

Warning In general, this method should not be called. The best way to create an instance of a COM class is to use the new operator on the Java wrapper generated by the jactivex tool.

Return Value:

Returns an instance of the specified COM class.

Parameter | Description
clsid | The class identifier (CLSID) of the instantiated COM class.
punkOuter | The aggregating object if the object is being created as part of an aggregate; otherwise, null.
ctxFlags | The ComContext value that represents the context that the new object is created in.

Exceptions:

com.ms.com.ComFailException if there is an error instantiating the class.

createWithLic

public IUnknown createWithLic(String lic, String clsid, IUnknown punkOuter,
        int ctxFlags);

Creates a new instance of a licensed COM class.

Return Value:

Returns a new instance of the specified licensed COM class.

Parameter | Description
lic | The license for the COM class that is instantiated.
clsid | The class identifier (CLSID) of the instantiated COM class.
punkOuter | The aggregating object if the object is being created as part of an aggregate; otherwise, null.
ctxFlags | The value that represents the context that the new object is created in.

Remarks:

The following example shows a helper class with a single method called create that wraps a call to createWithLic. Using this method, you can create an instance of the _DBEngine licensed component without having to specify the license or the class identifier (CLSID).

import dao3032.*;
import com.ms.com.*;
public class dao_dbengine

{
  static public _DBEngine create()
  {
  _DBEngine result;
  ILicenseMgr mgr = new LicenseMgr();
  result = (_DBEngine) mgr.createWithLic(
  "mjgcqcejfchcijecpdhckcdjqigdejfccjri",   // BSTR lic
  "{00025E15-0000-0000-C000-000000000046}", // BSTR clsid,
     null,ComContext.INPROC_SERVER); // IUnknown* punkOuter,
                                     // ComContext ctxFlags
     return result;
     }
}

Exceptions:

com.ms.com.ComFailException if there is an error instantiating the class.

setPackage

public void setPackage(String url);

Sets the package specified by the URL.

Return Value:

No return value.

Parameter | Description
url | The Uniform Resource Locator (URL) of the package.


Interface IPropertyNotifySink

public interface IPropertyNotifySink extends IUnknown
{
  // Fields
  public static final _Guid iid;

  // Methods
  public void OnChanged(int dispID);
  public void OnRequestEdit(int dispID);
}

This interface provides methods that allow a sink object to receive notifications about property changes from another object. The notifying object must support IPropertyNotifySink as an outgoing interface. The client that needs to receive notifications creates a sink with this interface and connects it to the connectable object by using the connection point mechanism.

The notifying object is required to call the methods of IPropertyNotifySink when it changes a property marked with the bindable attribute or when it is about to change a property marked with the requestedit attribute. There is one exception: no notifications are sent to the sink object as a result of an object's initialization or loading procedures. Therefore, notifications to the IPropertyNotifySink interface are meaningful only in the context of a fully loaded and initialized object.

The sink object throws a ComException object (either a ComFailException or a ComSuccessException) to signal that it does not want a requestedit property to be changed. The notifying object must honor the sink object's request not to change the property.

This interface wraps the Component Object Model (COM) IPropertyNotifySink interface.

IUnknown
  |
  +--IPropertyNotifySink

Methods

OnChanged

public void OnChanged(int dispID);

Notifies a sink object that a bindable property has changed.

Return Value:

No return value.

Parameter | Description
dispID | The identifier of the object that is notified.

OnRequestEdit

public void OnRequestEdit(int dispID);

Notifies a sink object that a requestedit property is about to change.

Return Value:

No return value.

Parameter | Description
dispID | The identifier of the object that is notified.

Remarks:

On return from a call to this method, the notifying object must honor the action specified by the sink object. For example, if the sink object does not allow the property change, the notifying object cannot make the change.

Fields

iid
The interface identifier.


Interface IServiceProvider

public interface IServiceProvider extends IUnknown
{
  // Fields
  public static final _Guid iid;

  // Methods
  public void QueryService(_Guid guidService, _Guid riid,
        Object[] ppvObject);
}

This interface provides a method that locates a service specified by a GUID and returns the interface pointer for a requested interface on the service. An object that provides services could implement the IServiceProvider interface as a general way to supply its clients with pointers to the interfaces on the service.

Sometimes, the QueryService method returns an interface pointer from an object other than the site object. This happens when a service is provided through a separate control or through some other object that the client communicates with.

This interface wraps the Component Object Model (COM) IServiceProvider interface.

IUnknown
  |
  +--IServiceProvider

Methods

QueryService

public void QueryService(_Guid guidService, _Guid riid, Object[] ppvObject);

Retrieves the interface pointer for a requested interface on a service.

Return Value:

No return value.

Parameter | Description
guidService | The GUID for the service.
riid | The identifier of the requested interface.
ppvObject | The returned interface.

Fields

iid
The interface identifier.


Interface IStream

public interface IStream extends IUnknown
{
  // Fields
  public static final _Guid iid;
  public static final int LOCK_EXCLUSIVE;
  public static final int LOCK_ONLYONCE;
  public static final int LOCK_WRITE;
  public static final int STATFLAG_DEFAULT;
  public static final int STATFLAG_NONAME;
  public static final int STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE;
  public static final int STGC_DEFAULT;
  public static final int STGC_ONLYIFCURRENT;
  public static final int STGC_OVERWRITE;
  public static final int STREAM_SEEK_CUR;
  public static final int STREAM_SEEK_END;
  public static final int STREAM_SEEK_SET;

  // Methods
  public IStream Clone();
  public void Commit(int grfCommitFlags);
  public void CopyTo(IStream pstm, long cb, long[] pcbRead,
        long[] pcbWritten);
  public void LockRegion(long libOffset, long cb, int dwLockType);
  public int Read(byte buf[], int off, int len);
  public void Revert();
  public long Seek(long dlibMove, int dwOrigin);
  public void SetSize(long libNewSize);
  public void Stat(STATSTG pstatstg, int grfStatFlag);
  public void UnlockRegion(long libOffset, long cb, int dwLockType);
  public int Write(byte buf[], int off, int len);
}

This interface provides methods for reading and writing data to stream objects. Each stream has its own access rights and seek pointer. The main difference between a stream object and an MS-DOS file is that streams are opened through an IStream interface pointer instead of using a file handle. Simple data can be written directly to a stream. Usually, however, streams are elements nested within a storage object.

This interface wraps the Component Object Model (COM) IStream interface.

IUnknown
  |
  +--IStream

Methods

Clone

public IStream Clone();

Creates a new stream object with its own seek pointer that references the same bytes as the original stream.

Return Value:

Returns the new stream object.

Remarks:

Because both the original object and its clone access the same data, changes written to one object are immediately visible in the other.

Commit

public void Commit(int grfCommitFlags);

Ensures that any changes made to a stream object opened in transacted mode are reflected in the parent storage object.

Return Value:

No return value.

Parameter | Description
grfCommitFlags | Flags that indicate conditions for the commit operation; the value must be STGC_DEFAULT or some combination of the following: STGC_OVERWRITE, STGC_ONLYIFCURRENT, and STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE.

CopyTo

public void CopyTo(IStream pstm, long cb, long[] pcbRead,
        long[] pcbWritten);

Copies a specific number of bytes from the current seek pointer in the stream to the current seek pointer in another stream.

Return Value:

No return value.

Parameter | Description
pstm | The stream that is copied to.
cb | The number of bytes to copy.
pcbRead | A pointer to the number of bytes actually read.
pcbWritten | A pointer to the number of bytes actually written.

LockRegion

public void LockRegion(long libOffset, long cb, int dwLockType);

Restricts access to a range of bytes in the stream.

Return Value:

No return value.

Parameter | Description
libOffset | The offset of the current seek pointer (measured in bytes) that indicates where to start the restriction.
cb | The number of bytes to restrict.
dwLocktype | A flag that indicates the type of restriction that is placed; the value must be LOCK_WRITE, LOCK_EXCLUSIVE, or LOCK_ONLYONCE.

Read

public int Read(byte buf[], int off, int len);

Reads bytes from the stream object into a byte array, starting at a specified offset from the current seek pointer.

Return Value:

Returns the number of bytes actually read.

Parameter | Description
buf | The buffer that the bytes are read into.
off | The offset in the stream to begin reading from.
len | The number of bytes to read.

Revert

public void Revert();

Discards all changes made to a transacted stream since the last Commit call.

Return Value:

No return value.

Remarks:

This method has no effect on streams open in direct mode or streams using the OLE compound file Revert implementation.

Seek

public long Seek(long dlibMove, int dwOrigin);

Changes the seek pointer to a new location relative to the beginning of the stream, the end of the stream, or the current seek pointer.

Return Value:

Returns the new seek pointer of the stream.

Parameter | Description
dlibMove | The offset relative to dwOrigin.
dwOrigin | The origin of the offset; must be STREAM_SEEK_CUR, STREAM_SEEK_END, or STREAM_SEEK_SET.

SetSize

public void SetSize(long libNewSize);

Changes the size of the stream object.

Return Value:

No return value.

Parameter | Description
libNewSize | The new size of the stream, measured in bytes.

Stat

public void Stat(STATSTG pstatstg, int grfStatFlag);

Retrieves the STATSTG structure for the current stream. (This structure contains statistical information about the current stream.)

Return Value:

No return value.

Parameter | Description
pstatstg | A STATSTG structure that contains the returned statistical information.
grfStatFlag | A flag that indicates whether to return a name in the STATSTG structure; the value must be STATFLAG_DEFAULT or STATFLAG_NONAME.

UnlockRegion

public void UnlockRegion(long libOffset, long cb, int dwLockType);

Removes the access restriction on a range of bytes that was previously restricted with the LockRegion method.

Return Value:

No return value.

Parameter | Description
libOffset | The offset of the current seek pointer (measured in bytes) that indicates where to start removing the restriction.
cb | The number of bytes removed from the restriction.
dwlockType | A flag that indicates the type of restriction removed; the value must be LOCK_WRITE, LOCK_EXCLUSIVE, or LOCK_ONLYONCE.

Write

public int Write(byte buf[], int off, int len);

Writes bytes from a byte array into the stream object, starting at a specified offset from the current seek pointer.

Return Value:

Returns The number of bytes actually written.

Parameter | Description
buf | The buffer to write from.
off | The offset in the array to begin writing from.
len | The number of bytes to write.

Fields

iid
The interface identifier.
LOCK_EXCLUSIVE
Indicates a type of locking for the LockRegion and UnlockRegion methods. If this type of lock is granted, writing to the specified range of bytes is prohibited to everyone except for the owner, who was granted the lock.
LOCK_ONLYONCE
Indicates a type of locking for the LockRegion and UnlockRegion methods. If this type of lock is granted, other LOCK_ONLYONCE locks cannot be obtained on the range.
LOCK_WRITE
Indicates a type of locking for the LockRegion and UnlockRegion methods. If this type of lock is granted, the specified range of bytes can be opened and read any number of times. Writing to the locked range, however, is prohibited to everyone except the owner, who was granted the lock.
STATFLAG_DEFAULT
Indicates that the name field should be included in the STATSTG structure returned by the Stat method.
STATFLAG_NONAME
Indicates that the name field should not be included in the STATSTG structure returned by the Stat method.
STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE
Specifies that changes are committed to a write-behind disk cache, but that the cache is not saved to the disk.

Caution The cache is eventually written to disk, but usually not until after the write operation has already returned. You risk losing data if a problem occurs before the cache is saved and the data in the cache is lost.

STGC_DEFAULT
Specifies the default condition for the Commit method. This value indicates that none of the other values apply.
STGC_ONLYIFCURRENT
Specifies that the commit operation occurs only if there have been no changes to the saved storage object since the user most recently opened the storage object. Prevents multiple users of a storage object from overwriting one another's changes.
STGC_OVERWRITE
Specifies that the Commit method can overwrite existing data to reduce overall space requirements.

Caution This value is not recommended for typical use because it is not as robust as the default case. Data loss can occur when the STGC_OVERWRITE value is specified and the commit operation fails due to some reason other than lack of space.

STREAM_SEEK_CUR
Specifies that the origin of the offset in the Seek method is the location of the current seek pointer.
STREAM_SEEK_END
Specifies that the origin of the offset in the Seek method is the end of the stream.
STREAM_SEEK_SET
Specifies that the origin of the offset in the Seek method is the beginning of the stream.


Interface IUnknown

public interface IUnknown
{
}

This interface is used as the return type for Component Object Model (COM) methods that return arbitrary COM interfaces. To achieve backward compatibility, the jactivex tool is used to translate references in the IUnknown COM interface to the IUnknown Java interface.


Interface NoAutoScripting

public interface NoAutoScripting
{
}

When used in the implements clause of a class definition, this interface prevents the Microsoft Win32 VM for Java from including its own IDispatch implementation for the class. For example:

// A.func is exposed to scripting engines such as
// VB or VBScript, which operate on IDispatch
objects.

class A
{
  public void func() {
    ...
  }
}

// B.func is not exposed to scripting engines.

class B implements com.ms.com.AutoNoScripting
{
  public void func() {
    ...
  }
}


About com.ms.directX

The Microsoft® DirectX™ package provides the classes and interfaces needed by Java programs and applets to access the services and features of the DirectX Component Object Model (COM) interface for Microsoft® Windows®. This article presents the DirectX classes, and identifies and provides detailed information about the methods and fields of these classes.

Note This article does not explain how to use the DirectX classes. For overview information about how to use DirectX, see the DirectX Software Development Kit (SDK). In some cases, you may need to refer to the Microsoft® Platform SDK for full details about selected structures.

Important Unlike their counterparts in COM, DirectX methods in Java do not return HRESULT error values. At best, a method will indicate whether a call to it succeeded or failed; the exact cause of an error is not available. Although you can catch the ComException exception to determine whether a DirectX method failed, the getHResult method of this exception does not specify the exact cause of the error.

Classes

Class _Guid
Specifies a globally unique identifier in the initialize method.
Class D3dDeviceDesc
Contains a description of the current device.
Class D3dExecuteBufferDesc
Describes the execute buffer for such methods as createExecuteBuffer and lock.
Class D3dExecuteData
Specifies data for the execute method.
Class D3dFindDeviceResult
Contains a description of the current device.
Class D3dFindDeviceSearch
Contains a description of a device to search for.
Class D3dLightDesc
Defines the light type in calls to methods such as setLight and getLight.
Class D3dLVertex
Defines an untransformed and lit vertex (screen coordinates with color).
Class D3dMaterialDesc
Specifies material properties in calls to the getMaterial and setMaterial methods.
Class D3dMatrix
Describes a matrix for such methods as Direct3dDevice.getMatrix and Direct3dDevice.setMatrix.
Class D3dPickRecord
Returns information about picked primitives in an execute buffer for the getPickRecords method.
Class D3dRect
Rectangle definition.
Class D3dRMBox
Defines the bounding box retrieved by the Direct3dRMMesh.getBox and Direct3dRMMeshBuilder.getBox methods.
Class D3dRMImage
Describes an image that is attached to a texture by the Direct3dRM.createTexture method.
Class D3dRMPickDesc
Contains the pick position and face and group identifiers of the objects retrieved by the getPick method.
Class D3dRMQuaternion
Describes the rotation used by the addRotateKey method.
Class D3dRMVector4d
Describes the screen coordinates used as the destination of a transformation by the transform method and as the source of a transformation by the inverseTransform method.
Class D3dRMVertex
Defines an untransformed and unlit vertex (model coordinates with normal direction vector).
Class D3dStats
Contains statistics used by the getStats method.
Class D3dTLVertex
Defines a transformed and lit vertex (screen coordinates with color).
Class D3dTriangle
A class that describes a base type for all triangles.
Class D3dVector
Defines a vector for many Direct3D and Direct3DRM methods and classes.
Class D3dVertex
Defines an untransformed and unlit vertex (screen coordinates with color).
Class D3dViewportDesc
Defines the visible 3D volume and the 2D screen area that a 3D volume projects onto for the getViewport and setViewport methods.
Class DDBltFx
Passes blit operations to the bltFx method.
Class DDCaps
Represents the capabilities of the hardware exposed through the DirectDraw object.
Class DDCapsFx
Represents the capabilities of the hardware exposed through the DirectDraw object.
Class DDColorKey
Describes a source color key, destination color key or color space.
Class DDPixelFormat
Describes the pixel format of a DirectDrawSurface object for the getPixelFormat method.
Class DDSurfaceDesc
Contains a description of the surface to be created.
Class Direct3d
Applications use the methods of the Direct3d class to create Direct3D objects and set up the environment.
Class Direct3dDevice
Applications use the methods of the Direct3dDevice class to retrieve and set the capabilities of Microsoft® Direct3D® devices.
Class Direct3dExecuteBuffer
Applications use the methods of the Direct3dExecuteBuffer class to set up and control a Microsoft® Direct3D® execute buffer.
Class Direct3dLight
Applications use the methods of the Direct3dLight class to retrieve and set the capabilities of lights.
Class Direct3dMaterial
Applications use the methods of the Direct3dMaterial class to retrieve and set the properties of materials.
Class Direct3dRM
Applications use the methods of the Direct3dRM class to create Direct3dRM objects and work with system-level variables.
Class Direct3dRMAnimation
Applications use the methods of the Direct3dRMAnimation class to animate the position, orientation, and scaling of visuals, lights, and viewports.
Class Direct3dRMAnimationSet
Applications use the methods of the Direct3dRMAnimationSet class to group Direct3dRMAnimation objects together, which can simplify the playback of complex animation sequences.
Class Direct3dRMArray
The Direct3dRMArray class organizes groups of objects.
Class Direct3dRMDevice
Applications use the methods of the Direct3dRMDevice class to interact with the output device.
Class Direct3dRMDeviceArray
Applications use the methods of the Direct3dRMDeviceArray class to organize device objects.
Class Direct3dRMFace
Applications use the methods of the Direct3dRMFace class to interact with a single polygon in a mesh.
Class Direct3dRMFaceArray
Applications use the methods of the Direct3dRMFaceArray class to organize faces in a mesh.
Class Direct3dRMFrame
Applications use the methods of the Direct3dRMFrame class to interact with frames—an object's frame of reference.
Class Direct3dRMFrameArray
Applications use the methods of the Direct3dRMFrameArray class to organize frame objects.
Class Direct3dRMLight
Applications use the methods of the Direct3dRMLight class to interact with light objects.
Class Direct3dRMLightArray
Applications use the methods of the Direct3dRMLightArray class to organize light objects.
Class Direct3dRMMaterial
Applications use the methods of the Direct3dRMMaterial class to interact with material objects.
Class Direct3dRMMesh
Applications use the methods of the Direct3dRMMesh class to interact with groups of meshes.
Class Direct3dRMMeshBuilder
Applications use the methods of the Direct3dRMMeshBuilder class to interact with mesh objects.
Class Direct3dRMObject
Applications use the methods of the Direct3dRMObject class to work with the object superclass of Direct3dRM objects.
Class Direct3dRMPickArray
Applications use the methods of the Direct3dRMPickArray class to organize pick objects.
Class Direct3dRMTexture
Applications use the methods of the Direct3dRMTexture class to work with textures, which are rectangular arrays of pixels.
Class Direct3dRMUserVisual
Applications use the Direct3dRMUserVisual class to manage user visual objects.
Class Direct3dRMViewport
Applications use the methods of the Direct3dRMViewport class to work with viewport objects.
Class Direct3dRMViewportArray
Applications use the methods of the Direct3dRMViewportArray class to organize viewport objects.
Class Direct3dRMVisual
Applications use the Direct3dRMVisual class when creating shadows or adding visuals to a frame.
Class Direct3dRMVisualArray
Applications use the methods of the Direct3dRMVisualArray class to organize groups of visual objects.
Class Direct3dRMWinDevice
Applications use the methods of the Direct3dRMWinDevice class to respond to window messages in a window procedure.
Class Direct3dRMWrap
Applications use the methods of the Direct3dRMWrap class to work with wrap objects.
Class Direct3dTexture
Applications use the methods of the Direct3dTexture class to retrieve and set texture properties.
Class Direct3dViewport
Applications use the methods of the Direct3dViewport class to retrieve and set the properties of viewports.
Class DirectDraw
Applications use the methods of the DirectDraw class to create Microsoft® DirectDraw® objects and work with system-level variables.
Class DirectDrawBitmap
Applications use the DirectDrawBitmap class to create and manage bitmaps.
Class DirectDrawClipper
Applications use the methods of the DirectDrawClipper class to manage clip lists.
Class DirectDrawPalette
Applications use the methods of the DirectDrawPalette class to create Microsoft® DirectDraw® palette objects and work with system-level variables.
Class DirectDrawSurface
Applications use the methods of the DirectDrawSurface class to create Microsoft® DirectDraw® surface objects and work with system-level variables.
Class DirectInput
Class DirectPlay2
Applications use the methods of the DirectPlay2 class to create Microsoft® DirectPlay®2 objects and work with system-level variables.
Class DirectPlayLobby
Class DirectSound
Applications use the methods of the DirectSound class to create DirectSound objects and set up the environment.
Class DirectSound3dBuffer
Class DirectSound3dListener
Class DirectSoundBuffer
Applications use the methods of the DirectSoundBuffer class to create DirectSoundBuffer objects and set up the environment.
Class DirectSoundResource
Applications use the DirectSoundResource class to load wave format objects.
Class DPCaps
Contains the capabilities of a DirectPlay object after a call to the getCaps or getPlayerCaps methods.
Class DPSessionDesc
Contains a description of the capabilities of an DirectPlay session.
Class DS3dBuffer
Class DS3dListener
Class DSBCaps
Specifies the capabilities of a DirectSound buffer object, for use by the getCaps method.
Class DSBufferDesc
Describes the necessary characteristics of a new DirectSoundBuffer object.
Class DSCaps
Specifies the capabilities of a DirectSound device for use by the getCaps method.
Class DSCursors
Contains the play and write positions in a DirectSoundBuffer object.
Class DSResourceDesc
Contains information about a loaded resource.
Class JoyCaps
Class JoyInfo
Class PaletteEntry
Specifies a color palette entry when creating palettes using the createPalette method.
Class Rect
Specifies the corners of a rectangle.
Class WaveFormatEx
Specifies the format of data in a sound buffer.

Interfaces

Interface DirectXConstants
The DirectXConstants interface defines all the constants used in DirectX for Java.
Interface Id3dEnumDevicesCallback
Use with enumDevices method to set the callback function to be called for each device.
Interface Id3drmCallback
Use with Direct3dRMObject.addDestroyCallback and Direct3dRMObject.deleteDestroyCallback to set or remove the callback function to be called when an object is destroyed.
Interface IDeviceUpdateCallback
Use with addUpdateCallback and deleteUpdateCallback to set or remove the callback function that is called whenever a device is updated.
Interface IDirect3d
For a description of methods and parameters, see Direct3d.
Interface IDirect3dDevice
For a description of methods and parameters, see Direct3dDevice
Interface IDirect3dExecuteBuffer
For a description of methods and parameters, see Direct3dExecuteBuffer.
Interface IDirect3dLight
For a description of methods and parameters, see Direct3dLight
Interface IDirect3dMaterial
For a description of methods and parameters, see Direct3dMaterial.
Interface IDirect3dRM
For a description of methods and parameters, see Direct3dRM.
Interface IDirect3dRMAnimation
For a description of methods and parameters, see Direct3dRMAnimation.
Interface IDirect3dRMAnimationSet
For a description of methods and parameters, see Direct3dRMAnimationSet.
Interface IDirect3dRMArray
For a description of methods and parameters, see Direct3dRMArray.
Interface IDirect3dRMDevice
For a description of methods and parameters, see Direct3dRMDevice.
Interface IDirect3dRMDeviceArray
For a description of methods and parameters, see Direct3dRMDeviceArray.
Interface IDirect3dRMFace
For a description of methods and parameters, see Direct3dRMFace.
Interface IDirect3dRMFaceArray
For a description of methods and parameters, see Direct3dRMFaceArray.
Interface IDirect3dRMFrame
For a description of methods and parameters, see Direct3dRMFrame
Interface IDirect3dRMFrameArray
For a description of methods and parameters, see Direct3dRMFrameArray.
Interface IDirect3dRMLight
For a description of methods and parameters, see Direct3dRMLight.
Interface IDirect3dRMLightArray
For a description of methods and parameters, see Direct3dRMLightArray.
Interface IDirect3dRMMaterial
For a description of methods and parameters, see Direct3dRMMaterial.
Interface IDirect3dRMMesh
For a description of methods and parameters, see Direct3dRMMesh.
Interface IDirect3dRMMeshBuilder
For a description of methods and parameters, see Direct3dRMMeshBuilder.
Interface IDirect3dRMObject
For a description of methods and parameters, see Direct3dRMObject.
Interface IDirect3dRMPickArray
For a description of methods and parameters, see Direct3dRMPickArray.
Interface IDirect3dRMTexture
For a description of methods and parameters, see Direct3dRMTexture.
Interface IDirect3dRMUserVisual
For a description of methods and parameters, see Direct3dRMUserVisual
Interface IDirect3dRMViewport
For a description of methods and parameters, see Direct3dRMViewport.
Interface IDirect3dRMViewportArray
For a description of methods and parameters, see Direct3dRMViewportArray.
Interface IDirect3dRMVisual
For a description of methods and parameters, see Direct3dRMVisual.
Interface IDirect3dRMVisualArray
For a description of methods and parameters, see Direct3dRMVisualArray.
Interface IDirect3dRMWinDevice
For a description of methods and parameters, see Direct3dRMWinDevice.
Interface IDirect3dRMWrap
For a description of methods and parameters, see Direct3dRMWrap.
Interface IDirect3dTexture
For a description of methods and parameters, see Direct3dTexture.
Interface IDirect3dViewport
For a description of methods and parameters, see Direct3dViewport.
Interface IDirectDraw
For a description of methods and parameters, see DirectDraw.
Interface IDirectDrawBitmap
For a description of methods and parameters, see DirectDrawBitmap.
Interface IDirectDrawClipper
For a description of methods and parameters, see DirectDrawClipper.
Interface IDirectDrawPalette
For a description of methods and parameters, see DirectDrawPalette.
Interface IDirectDrawSurface
For a description of methods and parameters, see DirectDrawSurface.
Interface IDirectInput
For a description of methods and parameters, see DirectInput.
Interface IDirectPlay2
For a description of methods and parameters, see DirectPlay2.
Interface IDirectPlayLobby
For a description of methods and parameters, see DirectPlayLobby.
Interface IDirectSound
For a description of methods and parameters, see DirectSound.
Interface IDirectSound3dBuffer
For a description of methods and parameters, see DirectSound3dBuffer.
Interface IDirectSound3dListener
For a description of methods and parameters, see DirectSound3dListener.
Interface IDirectSoundBuffer
For a description of methods and parameters, see DirectSoundBuffer.
Interface IDirectSoundResource
For a description of methods and parameters, see DirectSoundResource.
Interface IEnumAddressCallback
Interface IEnumAddressTypesCallback
Interface IEnumerateObjectsCallback
Use with Direct3dRM.enumerateObjects to set the callback function to be called for each active Direct3dRM object.
Interface IEnumLocalApplicationsCallback
Interface IEnumModesCallback
Use with enumDisplayModes to set the callback function to be called for each display mode exposed by the hardware.
Interface IEnumPlayersCallback2
Use with the DirectPlay2.enumGroupPlayers, DirectPlay2.enumGroups, and DirectPlay2.enumPlayers methods to set the callback function to be called for each group or player.
Interface IEnumServiceProvidersCallback
Use with the DirectPlay2.enumServiceProviders method to enumerate service providers installed on the system.
Interface IEnumSessionsCallback2
Use with DirectPlay2.enumSessions to set the callback function to be called for each active session.
Interface IEnumSoundDriversCallback
Interface IEnumSurfacesCallback
Use with DirectDraw.enumSurfaces and DirectDrawSurface.enumAttachedSurfaces to set the callback function to be called for each specified surface.
Interface IEnumTextureFormatsCallback
Use with Direct3dDevice.enumTextureFormats to set the callback function to be called for each texture format for a device.
Interface IEnumZOrdersCallback
Use with DirectDrawSurface.enumOverlayZOrders to set the callback function to be called for each overlay on the given surface.
Interface IFrameMoveCallback
Use with Direct3dRMFrame.addMoveCallback and Direct3dRMFrame.deleteMoveCallback to set or remove the callback function to be called when a frame is moved.
Interface ILoadCallback
Use with Direct3dRM.loadFromFileByPos to set the callback function to be called when an object is loaded.
Interface ILoadTextureCallback
Use with methods, such as Direct3dRM.loadFromFileByPos to set the callback function to be called when loading a texture.
Interface IUserVisualCallback
Use with Direct3dRM.createUserVisual and Direct3dRMUserVisual.init to set the callback function to be called to render an application-defined visual.

Hierarchy

Object
  |
  +--D3dLVertex
  |
  +--D3dDeviceDesc
  |
  +--D3dExecuteBufferDesc
  |
  +--D3dExecuteData
  |
  +--D3dFindDeviceResult
  |
  +--D3dFindDeviceSearch
  |
  +--D3dLightDesc
  |
  +--_Guid
  |
  +--D3dMaterialDesc
  |
  +--D3dMatrix
  |
  +--D3dPickRecord
  |
  +--D3dRect
  |
  +--D3dRMBox
  |
  +--D3dRMImage
  |
  +--D3dRMPickDesc
  |
  +--D3dRMQuaternion
  |
  +--D3dRMVector4d
  |
  +--D3dRMVertex
  |
  +--D3dStats
  |
  +--D3dTLVertex
  |
  +--D3dTriangle
  |
  +--D3dVector
  |
  +--D3dVertex
  |
  +--D3dViewportDesc
  |
  +--DDBltFx
  |
  +--DDCaps
  |
  +--DDCapsFx
  |
  +--DDColorKey
  |
  +--DDPixelFormat
  |
  +--DDSurfaceDesc
  |
  +--DPCaps
  |
  +--DPSessionDesc
  |
  +--DS3dBuffer
  |
  +--DS3dListener
  |
  +--DSBCaps
  |
  +--DSBufferDesc
  |
  +--DSCaps
  |
  +--DSCursors
  |
  +--DSResourceDesc
  |
  +--JoyCaps
  |
  +--JoyInfo
  |
  +--PaletteEntry
  |
  +--Rect
  |
  +--WaveFormatEx
  |
  +--Direct3dRMArray (IDirect3dRMArray)
  |
  +--Direct3dDevice (IDirect3dDevice)
  |
  +--Direct3dExecuteBuffer (IDirect3dExecuteBuffer)
  |
  +--Direct3dLight (IDirect3dLight)
  |
  +--Direct3dMaterial (IDirect3dMaterial)
  |
  +--Direct3dRM (IDirect3dRM)
  |
  +--Direct3dRMAnimation (IDirect3dRMAnimation)
  |
  +--Direct3dRMAnimationSet (IDirect3dRMAnimationSet)
  |
  +--Direct3d (IDirect3d)
  |
  +--Direct3dRMDevice (IDirect3dRMDevice)
  |
  +--Direct3dRMDeviceArray (IDirect3dRMDeviceArray)
  |
  +--Direct3dRMFace (IDirect3dRMFace)
  |
  +--Direct3dRMFaceArray (IDirect3dRMFaceArray)
  |
  +--Direct3dRMFrame (IDirect3dRMFrame)
  |
  +--Direct3dRMFrameArray (IDirect3dRMFrameArray)
  |
  +--Direct3dRMLight (IDirect3dRMLight)
  |
  +--Direct3dRMLightArray (IDirect3dRMLightArray)
  |
  +--Direct3dRMMaterial (IDirect3dRMMaterial)
  |
  +--Direct3dRMMesh (IDirect3dRMMesh)
  |
  +--Direct3dRMMeshBuilder (IDirect3dRMMeshBuilder)
  |
  +--Direct3dRMObject (IDirect3dRMObject)
  |
  +--Direct3dRMPickArray (IDirect3dRMPickArray)
  |
  +--Direct3dRMTexture (IDirect3dRMTexture)
  |
  +--Direct3dRMUserVisual (IDirect3dRMUserVisual)
  |
  +--Direct3dRMViewport (IDirect3dRMViewport)
  |
  +--Direct3dRMViewportArray (IDirect3dRMViewportArray)
  |
  +--Direct3dRMVisual (IDirect3dRMVisual)
  |
  +--Direct3dRMVisualArray (IDirect3dRMVisualArray)
  |
  +--Direct3dRMWinDevice (IDirect3dRMWinDevice)
  |
  +--Direct3dRMWrap (IDirect3dRMWrap)
  |
  +--Direct3dTexture (IDirect3dTexture)
  |
  +--Direct3dViewport (IDirect3dViewport)
  |
  +--DirectDraw (IDirectDraw)
  |
  +--DirectDrawBitmap (IDirectDrawBitmap)
  |
  +--DirectDrawClipper (IDirectDrawClipper)
  |
  +--DirectDrawPalette (IDirectDrawPalette)
  |
  +--DirectDrawSurface (IDirectDrawSurface)
  |
  +--DirectInput (IDirectInput)
  |
  +--DirectPlay2 (IDirectPlay2)
  |
  +--DirectPlayLobby (IDirectPlayLobby)
  |
  +--DirectSound (IDirectSound)
  |
  +--DirectSound3dBuffer (IDirectSound3dBuffer)
  |
  +--DirectSound3dListener (IDirectSound3dListener)
  |
  +--DirectSoundBuffer (IDirectSoundBuffer)
  |
  +--DirectSoundResource (IDirectSoundResource)

IDirect3dRMFace
IDirect3dDevice
IDirect3dExecuteBuffer
IDirect3dLight
IDirect3dMaterial
IDirect3dRM
IDirect3dRMAnimation
IDirect3dRMAnimationSet
IDirect3dRMArray
IDirect3dRMDevice
IDirect3dRMDeviceArray
IDirect3d
IDirect3dRMFaceArray
IDirect3dRMFrame
IDirect3dRMFrameArray
IDirect3dRMLight
IDirect3dRMLightArray
IDirect3dRMMaterial
IDirect3dRMMesh
IDirect3dRMMeshBuilder
IDirect3dRMObject
IDirect3dRMPickArray
IDirect3dRMTexture
IDirect3dRMUserVisual
IDirect3dRMViewport
IDirect3dRMViewportArray
IDirect3dRMVisual
IDirect3dRMVisualArray
IDirect3dRMWinDevice
IDirect3dRMWrap
IDirect3dTexture
IDirect3dViewport
IDirectDraw
IDirectDrawBitmap
IDirectDrawClipper
IDirectDrawPalette
IDirectDrawSurface
IDirectInput
IDirectPlay2
IDirectPlayLobby
IDirectSound
IDirectSound3dBuffer
IDirectSound3dListener
IDirectSoundBuffer
IDirectSoundResource
DirectXConstants
Id3drmCallback
IDeviceUpdateCallback
IEnumAddressCallback
IEnumAddressTypesCallback
Id3dEnumDevicesCallback
IEnumerateObjectsCallback
IEnumLocalApplicationsCallback
IEnumModesCallback
IEnumPlayersCallback2
IEnumServiceProvidersCallback
IEnumSessionsCallback2
IEnumSoundDriversCallback
IEnumSurfacesCallback
IEnumTextureFormatsCallback
IEnumZOrdersCallback
IFrameMoveCallback
ILoadCallback
ILoadTextureCallback
IUserVisualCallback


Class _Guid

public final class _Guid
{
  // Fields
  public int data1;
  public short data2;
  public short data3;
  public Generic data4;
}

Specifies a globally unique identifier in the initialize method.

Fields

data1
A data member for a globally unique identifier (GUID).
data2
A data member for a globally unique identifier (GUID).
data3
A data member for a globally unique identifier (GUID).
data4
A data member for a globally unique identifier (GUID).


Class D3dDeviceDesc

public final class D3dDeviceDesc
{
  // Fields
  public int clipping;
  public int dcmColorModel;
  public int devCaps;
  public int deviceRenderBitDepth;
  public int deviceZBufferBitDepth;
  public int dlcLightingCaps;
  public int dlcLightingModel;
  public int dlcLightingNumber;
  public int dtcTransformCaps;
  public int flags;
  public int maxBufferSize;
  public int maxVertexCount;
}

Contains a description of the current device. This class is used to query the current device by such methods as getCaps.

See also Direct3dDevice.

Fields

clipping
TRUE if the device can perform 3D clipping.
dcmColorModel
One value of D3DCOLOR_ type, specifying the color model for the device.
devCaps
One or more values of D3DDEVCAPS_ type, specifying the capabilities of the device.
deviceRenderBitDepth
A value of DDBD_ type (in the range DDBD_8 through DDBD_32), specifying the device's rendering bit-depth.
deviceZBufferBitDepth
A value of DDBD_ type (in the range DDBD_8 through DDBD_32), specifying the device's z-buffer bit-depth.
dlcLightingCaps
A value of D3DLIGHTCAPS_ type, specifying the lighting capabilities of the device.
dlcLightingModel
A value of D3DLIGHTINGMODEL_ type, specifying the lighting capabilities of the device.
dlcLightingNumber
Number of lights that can be handled.
dtcTransformCaps
A value indicating the transformation capabilities of the device. Can be zero or D3DTRANSFORMCAPS_CLIP to specify the system clips while transforming.
flags
One or more values of D3DDD_ type, specifying the fields of this class that contain valid data.
maxBufferSize
Maximum size of the execute buffer for this device. If this field is 0, the application can use any size.
maxVertexCount
Maximum vertex count for this device.


Class D3dExecuteBufferDesc

public final class D3dExecuteBufferDesc
{
  // Fields
  public int bufferSize;
  public int caps;
  public int flags;
}

Describes the execute buffer for such methods as createExecuteBuffer and lock.

See also Direct3dDevice, Direct3dExecuteBuffer.

Fields

bufferSize
Size of the execute buffer, in bytes.
caps
A value of D3DDEBCAPS_ type, specifying the location in memory of the execute buffer.
flags
One or more values of D3DDEB_ type, identifying the fields of this class that contain valid data.


Class D3dExecuteData

public final class D3dExecuteData
{
  // Fields
  public int flags;
  public int homogenousVertexOffset;
  public int instructionLength;
  public int instructionOffset;
  public int status;
  public int vertexCount;
  public int vertexOffset;
  public int x1;
  public int x2;
  public int y1;
  public int y2;
}

Specifies data for the execute method. When this method is called and the transformation has been done, the instruction list starting at the value specified in the instructionOffset field is parsed and rendered.

See also Direct3dDevice.

Fields

flags
homogenousVertexOffset
Offset into the list of vertices for the homogeneous vertex used when the application is supplying screen coordinate data that needs clipping.
instructionLength
Length of the instructions to execute.
instructionOffset
Offset into the list of instructions to execute.
status
Value storing the screen extent of the rendered geometry for use after the transformation is complete.
vertexCount
Number of vertices to execute.
vertexOffset
Offset into the list of vertices.
x1
x2
y1
y2


Class D3dFindDeviceResult

public final class D3dFindDeviceResult
{
  // Fields
  public int clipping;
  public int dcmColorModel;
  public int devCaps;
  public int deviceRenderBitDepth;
  public int deviceZBufferBitDepth;
  public int dlcLightingCaps;
  public int dlcLightingModel;
  public int dlcLightingNumber;
  public int dtcTransformCaps;
  public int flags;
  public int lineAlphaCmpCaps;
  public int lineDestBlendCaps;
  public int lineMiscCaps;
  public int lineRasterCaps;
  public int lineShadeCaps;
  public int lineSrcBlendCaps;
  public int lineStippleHeight;
  public int lineStippleWidth;
  public int lineTextureAddressCaps;
  public int lineTextureBlendCaps;
  public int lineTextureCaps;
  public int lineTextureFilterCaps;
  public int lineZCmpCaps;
  public int maxBufferSize;
  public int maxVertexCount;
  public int triAlphaCmpCaps;
  public int triDestBlendCaps;
  public int triMiscCaps;
  public int triRasterCaps;
  public int triShadeCaps;
  public int triSrcBlendCaps;
  public int triStippleHeight;
  public int triStippleWidth;
  public int triTextureAddressCaps;
  public int triTextureBlendCaps;
  public int triTextureCaps;
  public int triTextureFilterCaps;
  public int triZCmpCaps;

  // Methods
  public _Guid GetGuid();
}

Contains a description of the current device. This class is used to query the current device by such methods as Direct3dDevice.getCaps and Direct3d.findDevice.

Methods

GetGuid

public _Guid GetGuid();

Retrieves the globally unique identifier (GUID) for the device.

Return Value:

Returns the globally unique identifier.

Fields

clipping
TRUE if the hardware device can perform 3D clipping.
dcmColorModel
One value of D3DCOLOR_ type, specifying the color model for the hardware device.
devCaps
One or more flags of D3DDEVCAPS_ type, specifying the capabilities of the hardware device.
deviceRenderBitDepth
The device's rendering bit depth. This can be one or more of the following DirectDraw bit depth constants: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
deviceZBufferBitDepth
The device's z-buffer bit depth. This can be one or more of the following DirectDraw bit depth constants: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
dlcLightingCaps
A value of D3DLIGHTCAPS_ type, specifying the lighting capabilities of the hardware device.
dlcLightingModel
A value of D3DLIGHTINGMODEL_ type, specifying the lighting capabilities of the hardware device.
dlcLightingNumber
Number of lights that can be handled.
dtcTransformCaps
A value indicating the transformation capabilities of the hardware device. Can be zero or D3DTRANSFORMCAPS_CLIP to specify the system clips while transforming.
flags
Flags identifying the members of this class that contain valid data. These flags are D3DDD_ constants.
lineAlphaCmpCaps
Alpha-test comparison functions that a driver can perform. This member can be any of the combinations valid for lineZCmpCaps.
lineDestBlendCaps
Destination blending capabilities. This member can be any of the combinations valid for lineSrcBlendCaps.
lineMiscCaps
The general capabilities for this primitive. This may be one or more of the D3DPMISCCAPS_ types.
lineRasterCaps
Information on raster-drawing capabilities. This may be one or more of the D3DPRASTERCAPS_ types.
lineShadeCaps
Shading operations that the device can perform. It is assumed, in general, that if a device supports a given command (such as D3DOP_TRIANGLE) at all, it supports the D3DSHADE_FLAT mode (as specified in D3DSHADEMODE). This flag specifies whether the driver can also support Gouraud and Phong shading and whether alpha color components are supported for each of the three color-generation modes. When alpha components are not supported in a given mode, the alpha value of colors generated in that mode is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver. These are modified by the shade mode, color model, and by whether the alpha component of a color is blended or stippled.

This member can be one or more of D3DPSHADECAPS_ types.

lineSrcBlendCaps
Source blending capabilities. This member can be one or more of the D3DPBLENDCAPS_ types.
lineStippleHeight
The maximum height of the supported stipple (up to 32-by-32).
lineStippleWidth
The maximum width of the supported stipple (up to 32-by-32).
lineTextureAddressCaps
Texture-addressing capabilities. This member can be one or more of the D3DPTADDRESSCAPS_ types.
lineTextureBlendCaps
Texture-blending capabilities. This member can be one or more of the D3DPTBLENDCAPS_ types.
lineTextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the D3DPTEXTURECAPS_ types.
lineTextureFilterCaps
Texture-mapping capabilities. This member can be one or more of the D3DPTFILTERCAPS_ types.
lineZCmpCaps
The z-buffer comparison functions that a driver may perform. This member can be one or more of the D3DPCMPCAPS_ types.
maxBufferSize
The maximum size of the execute buffer for this device. If this member is 0, the application can use any size buffer.
maxVertexCount
The maximum vertex count for the device.
triAlphaCmpCaps
Alpha-test comparison functions that a driver can perform. This member can be any of the combinations valid for lineZCmpCaps.
triDestBlendCaps
Destination blending capabilities. This member can be any of the combinations valid for triSrcBlendCaps.
triMiscCaps
The general capabilities for this primitive. This member can be one or more of the D3DPMISCCAPS_ types.
triRasterCaps
Information on raster-drawing capabilities. This may be one or more of the D3DPRASTERCAPS_ types.
triShadeCaps
Shading operations that the device can perform. It is assumed, in general, that if a device supports a given command (such as D3DOP_TRIANGLE) at all, it supports the D3DSHADE_FLAT mode (as specified in D3DSHADEMODE). This flag specifies whether the driver can also support Gouraud and Phong shading and whether alpha color components are supported for each of the three color-generation modes. When alpha components are not supported in a given mode, the alpha value of colors generated in that mode is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver. These are modified by the shade mode, color model, and by whether the alpha component of a color is blended or stippled.

This member can be one or more of D3DPSHADECAPS_ types.

triSrcBlendCaps
Source blending capabilities. This member can be one or more of the D3DPBLENDCAPS_ types.
triStippleHeight
The maximum width and height of the supported stipple (up to 32-by-32).
triStippleWidth
triTextureAddressCaps
Texture-addressing capabilities. This member can be one or more of the D3DPTADDRESSCAPS_ types.
triTextureBlendCaps
Texture-blending capabilities. This member can be one or more of the D3DPTBLENDCAPS_ types.
triTextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the D3DPTEXTURECAPS_ types.
triTextureFilterCaps
Texture-mapping capabilities. This member can be one or more of the D3DPTFILTERCAPS_ types.
triZCmpCaps
The z-buffer comparison functions that a driver may perform. This member can be one or more of the D3DPCMPCAPS_ types.


Class D3dFindDeviceSearch

public final class D3dFindDeviceSearch
{
  // Fields
  public int alphaCmpCaps;
  public int caps;
  public int dcmColorModel;
  public int destBlendCaps;
  public int flags;
  public int hardware;
  public int miscCaps;
  public int rasterCaps;
  public int shadeCaps;
  public int srcBlendCaps;
  public int stippleHeight;
  public int stippleWidth;
  public int textureAddressCaps;
  public int textureBlendCaps;
  public int textureCaps;
  public int textureFilterCaps;
  public int zCmpCaps;

  // Methods
  public _Guid getGuid();
  public void setGuid(_Guid g);
}

Contains a description of a device to search for.

Also see com.ms.directX.D3dFindDeviceResult

Methods

getGuid

public _Guid getGuid();

Retrieves the globally unique identifier (GUID) for the device.

Return Value:

Returns the globally unique identifier.

setGuid

public void setGuid(_Guid g);

This method is currently not implemented.

Return Value:

No return value.

Parameter | Description
_Guid | The globally unique identifier.

Fields

alphaCmpCaps
One or more values of D3DPCMPCAPS_ type, specifying the alpha-test comparison functions that the driver can perform.
caps
One or more flags of D3DDEVCAPS_ type, specifying the capabilities of the device.
dcmColorModel
One value of D3DCOLOR_ type, specifying whether the device to find should use the ramp or RGB color model.
destBlendCaps
One or more values of D3DPBLENDCAPS_ type, specifying the destination blending capabilities.
flags
One or more values of D3DFDS_ type, defining the type of device the application wants to find.
hardware
Flag specifying whether the device to find is implemented as hardware or software. If this member is true, the device to search for has hardware rasterization and may also provide other hardware acceleration. Applications that use this flag should set the D3DFDS_HARDWARE bit in the flags field.
miscCaps
One or more values of D3DPMISCCAPS_ type, specifying the general capabilities for primitives.
rasterCaps
One or more values of D3DPRASTERCAPS_ type, specifying information on raster-drawing capabilities.
shadeCaps
One or more values of D3DPSHADECAPS_ type, specifying the shading operations that the device can perform.

It is assumed, in general, that if a device supports a given command (such as D3DOP_TRIANGLE) at all, it supports the D3DSHADE_FLAT mode. This flag specifies whether the driver can also support Gouraud and Phong shading and whether alpha color components are supported for each of the three color-generation modes. When alpha components are not supported in a given mode, the alpha value of colors generated in that mode is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver. These are modified by the shade mode, color model, and by whether the alpha component of a color is blended or stippled.

srcBlendCaps
One or more values of D3DPBLENDCAPS_ type, specifying the source blending capabilities.
stippleHeight
Maximum height of the supported stipple (up to 32).
stippleWidth
Maximum width of the supported stipple (up to 32).
textureAddressCaps
One or more values of D3DPTADDRESSCAPS_ type, specifying texture-addressing capabilities.
textureBlendCaps
One or more values of D3DPTBLENDCAPS_ type, specifying texture-blending capabilities.
textureCaps
One or more values of D3DPTEXTURECAPS_ type, specifying miscellaneous texture-mapping capabilities.
textureFilterCaps
One or more values of D3DPTFILTERCAPS_ type, specifying texture-mapping capabilities.
zCmpCaps
One or more values of D3DPCMPCAPS_ type, specifying the z-buffer comparison functions that the driver can perform.


Class D3dLightDesc

public final class D3dLightDesc
{
  // Fields
  public float attenuation0;
  public float attenuation1;
  public float attenuation2;
  public float colorA;
  public float colorB;
  public float colorG;
  public float colorR;
  public float directionx;
  public float directiony;
  public float directionz;
  public int dltType;
  public float falloff;
  public float phi;
  public float positionx;
  public float positiony;
  public float positionz;
  public float range;
  public float theta;
}

Defines the light type in calls to methods such as setLight and getLight.

Fields

attenuation0
Constant light intensity. Specifies a light level that does not decrease between the light and the cutoff point given by the range field.
attenuation1
Light intensity that decreases linearly. The light intensity is 50 percent of this value halfway between the light and the cutoff point given by the range field.
attenuation2
Light intensity that decreases according to a quadratic attenuation factor.
colorA
the alpha element of the color of the light.
colorB
The blue element of the color of the light.
colorG
The green element of the color of the light.
colorR
The red element of the color of the light.
directionx
The x axis element of the direction of the light in world space.
directiony
The y axis element of the direction of the light in world space.
directionz
The z axis element of the direction of the light in world space.
dltType
Type of the light source. This is one value of light type.
falloff
Decrease in illumination between the umbra (the angle specified by the theta field) and the outer edge of the penumbra (the angle specified by the phi field).
phi
Angle, in radians, defining the outer edge of the spotlight's penumbra. Points outside this cone are not lit by the spotlight.
positionx
The x axis element of the position of the light in world space.
positiony
The y axis element of the position of the light in world space.
positionz
The z axis element of the position of the light in world space.
range
Distance beyond which the light has no effect.
theta
Angle, in radians, of the spotlight's umbra—that is, the fully illuminated spotlight cone.


Class D3dLVertex

public final class D3dLVertex
{
  // Fields
  public int color;
  public int specular;
  public float tu;
  public float tv;
  public float x;
  public float y;
  public float z;

  // Constructors
  public D3dLVertex();
  public D3dLVertex(float x, float y, float z, int color,
        int specular, float tu, float tv);
}

Defines an untransformed and lit vertex (screen coordinates with color).

Constructors

D3dLVertex

public D3dLVertex();

Creates a D3dLVertex object with fields uninitialized.

D3dLVertex

public D3dLVertex(float x, float y, float z, int color, int specular, float
        tu, float tv);

Creates a D3dLVertex objects with fields set to values specified by the user.

Parameter | Description
x | A float value that initializes the x field.
y | A float value that initializes the y field.
z | A float value that initializes the z field.
color | An int value that initializes the color field.
specular | An int value that initializes the specular field.
tu | A float value that initializes the tu field.
tv | A float value that initializes the tv field.

Fields

color
Value describing the color component of the vertex.
specular
Value describing the specular component of the vertex.
tu
Value describing the texture coordinates of the vertex.
tv
Value describing the texture coordinates of the vertex.
x
The x screen coordinate of the vertex.
y
The y screen coordinate of the vertex.
z
The z screen coordinate of the vertex.


Class D3dMaterialDesc

public final class D3dMaterialDesc
{
  // Fields
  public float ambientA;
  public float ambientB;
  public float ambientG;
  public float ambientR;
  public float diffuseA;
  public float diffuseB;
  public float diffuseG;
  public float diffuseR;
  public float dvPower;
  public float emissiveA;
  public float emissiveB;
  public float emissiveG;
  public float emissiveR;
  public float power;
  public int rampSize;
  public float specularA;
  public float specularB;
  public float specularG;
  public float specularR;
  public int textureHandle;
}

Specifies material properties in calls to the getMaterial and setMaterial methods.

See also Direct3dMaterial.

Fields

ambientA
The alpha element of the material's ambient color.
ambientB
The blue element of the material's ambient color.
ambientG
The green element of the material's ambient color.
ambientR
The red element of the material's ambient color.
diffuseA
The alpha element of the material's diffuse color.
diffuseB
The blue element of the material's diffuse color.
diffuseG
The green element of the material's diffuse color.
diffuseR
The red element of the material's diffuse color.
dvPower
The sharpness of specular highlights.
emissiveA
The alpha element of the material's emissive color.
emissiveB
The blue element of the material's emissive color.
emissiveG
The green element of the material's emissive color.
emissiveR
The red element of the material's emissive color.
power
Value specifying the sharpness of specular highlights.
rampSize
Size of the color ramp. For the monochromatic (ramp) driver, this value must be less than or equal to 1 for materials assigned to the background; otherwise, the background is not displayed. This behavior also occurs when a texture that is assigned to the background has an associated material whose rampSize field is greater than 1.
specularA
The alpha element of the material's specular color.
specularB
The blue element of the material's specular color.
specularG
The green element of the material's specular color.
specularR
The red element of the material's specular color.
textureHandle
The handle of the texture map.


Class D3dMatrix

public final class D3dMatrix
{
  // Fields
  public float _11;
  public float _12;
  public float _13;
  public float _14;
  public float _21;
  public float _22;
  public float _23;
  public float _24;
  public float _31;
  public float _32;
  public float _33;
  public float _34;
  public float _41;
  public float _42;
  public float _43;
  public float _44;

  // Constructors
  public D3dMatrix(float _11, float _12, float _13, float _14,
        float _21, float _22, float _23, float _24, float _31,
        float _32, float _33, float _34, float _41, float _42,
        float _43, float _44);
}

Describes a matrix for such methods as Direct3dDevice.getMatrix and Direct3dDevice.setMatrix.

In Direct3D, the _44 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1, instead.

See also Direct3dDevice.

Constructors

D3dMatrix

public D3dMatrix(float _11, float _12, float _13, float _14, float _21,
        float _22, float _23, float _24, float _31, float _32, float _33,
        float _34, float _41, float _42, float _43, float _44);

Creates a D3dMatrix object with members set to values specified by the user.

Fields

_11
Floating point type used in the matrix.
_12
Floating point type used in the matrix.
_13
Floating point type used in the matrix.
_14
Floating point type used in the matrix.
_21
Floating point type used in the matrix.
_22
Floating point type used in the matrix.
_23
Floating point type used in the matrix.
_24
Floating point type used in the matrix.
_31
Floating point type used in the matrix.
_32
Floating point type used in the matrix.
_33
Floating point type used in the matrix.
_34
Floating point type used in the matrix.
_41
Floating point type used in the matrix.
_42
Floating point type used in the matrix.
_43
Floating point type used in the matrix.
_44
Floating point type used in the matrix.


Class D3dPickRecord

public final class D3dPickRecord
{
  // Fields
  public int offset;
  public byte opcode;
  public byte pad;
  public float z;
}

Returns information about picked primitives in an execute buffer for the getPickRecords method.

See also Direct3dDevice.

Fields

offset
Offset from the start of the execute buffer in which the picked primitive was found.
opcode
Opcode of the picked primitive.
pad
Pad byte.
z
Depth of the picked primitive.


Class D3dRect

public final class D3dRect
{
  // Fields
  public int x1;
  public int x2;
  public int y1;
  public int y2;
}

Rectangle definition.

See also Direct3dDevice, Direct3dViewport.

Fields

x1
The x coordinate of the upper-left corner of the rectangle.
x2
The x coordinate of the lower-right corner of the rectangle.
y1
The y coordinate of the upper-left corner of the rectangle.
y2
The y coordinate of the lower-right corner of the rectangle.


Class D3dRMBox

public final class D3dRMBox
{
  // Fields
  public float xMax;
  public float xMin;
  public float yMax;
  public float yMin;
  public float zMax;
  public float zMin;
}

Defines the bounding box retrieved by the Direct3dRMMesh.getBox and Direct3dRMMeshBuilder.getBox methods.

Fields

xMax
Value defining the x coordinate of the box's maximum bounds.
xMin
Value defining the x coordinate of the box's minimum bounds.
yMax
Value defining the y coordinate of the box's maximum bounds.
yMin
Value defining the y coordinate of the box's minimum bounds.
zMax
Value defining the z coordinate of the box's maximum bounds.
zMin
Value defining the z coordinate of the box's minimum bounds.


Class D3dRMImage

public final class D3dRMImage
{
  // Fields
  public int alpha_mask;
  public int aspectX;
  public int aspectY;
  public int blue_mask;
  public int bytes_per_line;
  public int depth;
  public int green_mask;
  public int height;
  public int palette_size;
  public int red_mask;
  public int rgb;
  public int width;
}

Describes an image that is attached to a texture by the Direct3dRM.createTexture method. The Direct3dRMTexture.getImage method returns this image.

See also Direct3dRM, Direct3dRMTexture.

Fields

alpha_mask
If rgb is true, these fields are masks for the red, green, and blue parts of a pixel. Otherwise, they are masks for the significant bits of the red, green, and blue elements in the palette. For example, most SVGA displays use 64 intensities of red, green, and blue, so the masks should all be set to 0xfc.
aspectX
X aspect ratio for nonsquare pixels.
aspectY
Y aspect ratio for nonsquare pixels.
blue_mask
Bitmask dependant on rgb.
bytes_per_line
Number of bytes of memory for a scanline. This value must be a multiple of four.
depth
Bits per pixel.
green_mask
Bitmask dependant on rgb.
height
Height of the image, in pixels.
palette_size
Number of entries in the palette.
red_mask
Bitmask dependant on rgb.
rgb
If this field false, pixels are indices into a palette. Otherwise, pixels encode RGB values.
width
Width of the image, in pixels.


Class D3dRMPickDesc

public final class D3dRMPickDesc
{
  // Fields
  public int faceIdx;
  public int groupIdx;
  public float x;
  public float y;
  public float z;
}

Contains the pick position and face and group identifiers of the objects retrieved by the getPick method.

See also Direct3dRMPickedArray.

Fields

faceIdx
Face index of the retrieved object.
groupIdx
Group index of the retrieved object.
x
Value describing the x coordinate of the retrieved object's position.
y
Value describing the y coordinate of the retrieved object's position.
z
Value describing the z coordinate of the retrieved object's position.


Class D3dRMQuaternion

public final class D3dRMQuaternion
{
  // Fields
  public float s;
  public float x;
  public float y;
  public float z;
}

Describes the rotation used by the addRotateKey method. It is also used in several of Direct3D's mathematical functions. Quaternions are an alternative to the matrix methods that are typically used for 3D rotations.

See also Direct3dRMAnimation.

Fields

s
A fourth element added to the x, y and z values that define a vector.
x
The x component of the vector.
y
The y component of the vector.
z
The z component of the vector.


Class D3dRMVector4d

public final class D3dRMVector4d
{
  // Fields
  public float w;
  public float x;
  public float y;
  public float z;
}

Describes the screen coordinates used as the destination of a transformation by the transform method and as the source of a transformation by the inverseTransform method.

See also Direct3dRMViewport.

Fields

w
Homogenous w.
x
The x screen coordinate of the vector.
y
The y screen coordinate of the vector.
z
The z screen coordinate of the vector.


Class D3dRMVertex

public final class D3dRMVertex
{
  // Fields
  public int color;
  public float nx;
  public float ny;
  public float nz;
  public float tu;
  public float tv;
  public float x;
  public float y;
  public float z;
}

Defines an untransformed and unlit vertex (model coordinates with normal direction vector).

Fields

color
Vertex color.
nx
Value describing the normal x coordinate of the vertex.
ny
Value describing the normal y coordinate of the vertex.
nz
Value describing the normal z coordinate of the vertex.
tu
Value describing the texture u coordinate of the vertex.
tv
Value describing the texture v coordinate of the vertex.
x
Value describing the homogeneous x coordinate of the vertex.
y
Value describing the homogeneous y coordinate of the vertex.
z
Value describing the homogeneous z coordinate of the vertex.


Class D3dStats

public final class D3dStats
{
  // Fields
  public int linesDrawn;
  public int pointsDrawn;
  public int spansDrawn;
  public int trianglesDrawn;
  public int verticesProcessed;
}

Contains statistics used by the getStats method.

See also Direct3dDevice.

Fields

linesDrawn
Number of lines drawn since the device was created.
pointsDrawn
Number of points drawn since the device was created.
spansDrawn
Number of spans drawn since the device was created.
trianglesDrawn
Number of triangles drawn since the device was created.
verticesProcessed
Number of vertices processed since the device was created.


Class D3dTLVertex

public final class D3dTLVertex
{
  // Fields
  public int color;
  public float rhw;
  public int specular;
  public float sx;
  public float sy;
  public float sz;
  public float tu;
  public float tv;

  // Constructors
  public D3dTLVertex();
  public D3dTLVertex(float sx, float sy, float sz, float rhw,
        int color, int specular float tu, float tv);
}

Defines a transformed and lit vertex (screen coordinates with color).

Constructors

D3dTLVertex

public D3dTLVertex();

Creates a D3DTLVertex object with uninitialized fields.

D3dTLVertex

public D3dTLVertex(float sx, float sy, float sz, float rhw, int color,
        int specular float tu, float tv);

Creates a D3dTLVertex object with fields set to values specified by the user.

Parameter | Description
sx | A float that initializes the sx field.
sy | A float that initializes the sy field.
sz | A float that initializes the sz field.
rhw | A float that initializes the rhw field.
color | An int that initializes the color field.
specular | An int that initializes the specular field.
tu | A float that initializes the tu field.
tv | A float that initializes the tv field.

Fields

color
Value describing the color component of the vertex.
rhw
The value that is the reciprocal of homogenous w. This value is 1 divided by the distance from the origin to the object along the z-axis.
specular
Value describing the specular component of the vertex.
sx
The x screen coordinate of the vertex.
sy
The y screen coordinate of the vertex.
sz
The z screen coordinate of the vertex.
tu
Value describing the texture u-coordinate of the vertex.
tv
Value describing the texture v-coordinate of the vertex.


Class D3dTriangle

public final class D3dTriangle
{
  // Fields
  public char flags;
  public char v1;
  public char v2;
  public char v3;

  // Constructors
  public D3dTriangle(int v1, int v2, int v3, short flags);
  public D3dTriangle(short v1, short v2, short v3, short flags);
}

A class that describes a base type for all triangles. The triangle is the main rendering primitive.

Constructors

D3dTriangle

public D3dTriangle(int v1, int v2, int v3, short flags);

Creates a D3dTriangle object with the members passed as ints and a short (flags) cast to chars.

Parameter | Description
v1 | The v1 field cast as an int.
v2 | The v2 field cast as an int.
v3 | The v3 field cast as an int.
flags | The flags field cast as a short.

D3dTriangle

public D3dTriangle(short v1, short v2, short v3, short flags);

Creates a D3dTriangle object with the members passed as shorts cast to chars.

Parameter | Description
v1 | The v1 field cast as a short.
v2 | The v2 field cast as a short.
v3 | The v3 field cast as a short.
flags | The flags field cast as a short.

Fields

flags
Flags describing which edges of the triangle to enable (this information is useful only in wireframe mode). This value can be a combination of the following edge and strip flags:
Edge Flags
D3DTRIFLAG_EDGEENABLE1
Edge defined by v1-v2.
D3DTRIFLAG_EDGEENABLE2
Edge defined by v2-v3.
D3DTRIFLAG_EDGEENABLE3
Edge defined by v3-v1.
D3DTRIFLAG_EDGEENABLETRIANGLE
All edges.
Strip and Fan Flags
D3DTRIFLAG_EVEN
The v1-v2 edge of the current triangle is adjacent to the v3-v1 edge of the previous triangle; that is, v1 is the previous v1, and v2 is the previous v3.
D3DTRIFLAG_ODD
The v1-v2 edge of the current triangle is adjacent to the v2-v3 edge of the previous triangle; that is, v1 is the previous v3, and v2 is the previous v2.
D3DTRIFLAG_START
Begin the strip or fan, loading all three vertices.
D3DTRIFLAG_STARTFLAT(len)
If this triangle is culled, also cull the specified number of subsequent triangles. This length must be greater than zero and less than 30.
v1
Vertex describing the triangle.
v2
Vertex describing the triangle.
v3
Vertex describing the triangle.


Class D3dVector

public final class D3dVector
{
  // Fields
  public float x;
  public float y;
  public float z;
}

Defines a vector for many Direct3D and Direct3DRM methods and classes.

Fields

x
The x component of the vector.
y
The y component of the vector.
z
The z component of the vector.


Class D3dVertex

public final class D3dVertex
{
  // Fields
  public float nx;
  public float ny;
  public float nz;
  public float tu;
  public float tv;
  public float x;
  public float y;
  public float z;

  // Constructors
  public D3dVertex();
  public D3dVertex(float x, float y, float z, float nx, float ny,
        float nz, float tu, float tv);
}

Defines an untransformed and unlit vertex (screen coordinates with color).

Constructors

D3dVertex

public D3dVertex();

Creates a D3dVertex object with fields uninitialized.

D3dVertex

public D3dVertex(float x, float y, float z, float nx, float ny, float nz,
        float tu, float tv);

Creates a D3dVertex objects with fields set to values specified by the user.

Parameter | Description
x | A floating point value that sets the x field.
y | A floating point value that sets the y field.
x | A floating point value that sets the z field.
nx | A floating point value that sets the nx field.
ny | A floating point value that sets the ny field.
nz | A floating point value that sets the nz field.
tu | A floating point value that sets the tu field.
tv | A floating point value that sets the tv field.

Fields

nx
Value describing the normal x coordinate of the vertex.
ny
Value describing the normal y coordinate of the vertex.
nz
Value describing the normal z coordinate of the vertex.
tu
Value describing the texture u coordinate of the vertex.
tv
Value describing the texture v coordinate of the vertex.
x
Value describing the homogeneous x coordinate of the vertex.
y
Value describing the homogeneous y coordinate of the vertex.
z
Value describing the homogeneous z coordinate of the vertex.


Class D3dViewportDesc

public final class D3dViewportDesc
{
  // Fields
  public int height;
  public float maxX;
  public float maxY;
  public float maxZ;
  public float minZ;
  public float scaleX;
  public float scaleY;
  public int width;
  public int x;
  public int y;
}

Defines the visible 3D volume and the 2D screen area that a 3D volume projects onto for the getViewport and setViewport methods.

When the viewport is changed, the driver builds a new transformation matrix.

The coordinates and dimensions of the viewport are given, relative to the top-left of the device.

See also Direct3dViewport.

Fields

height
The height of the viewport.
maxX
Value describing the maximum homogeneous x coordinate.
maxY
Value describing the maximum homogeneous y coordinate.
maxZ
Value describing the maximum homogeneous z coordinate.
minZ
Value describing the minimum homogeneous z coordinate.
scaleX
Values describing the scaling quantities homogeneous to the screen.
scaleY
Values describing the scaling quantities homogeneous to the screen.
width
The width of the viewport.
x
The x coordinate of the top-left corner of the viewport.
y
The y coordinate of the top-left corner of the viewport.


Class DDBltFx

public final class DDBltFx
{
  // Fields
  public int alphaDestConst;
  public int alphaDestConstBitDepth;
  public int alphaEdgeBlend;
  public int alphaEdgeBlendBitDepth;
  public int alphaSrcConst;
  public int alphaSrcConstBitDepth;
  public int ddfx;
  public int ddrop;
  public int destColorSpaceHighValue;
  public int destColorSpaceLowValue;
  public int fillValue;
  public int rop;
  public int rotationAngle;
  public int srcColorSpaceHighValue;
  public int srcColorSpaceLowValue;
  public int zbufferBaseDest;
  public int zbufferHigh;
  public int zbufferLow;
  public int zbufferOpCode;
  public int zDestConst;
  public int zDestConstBitDepth;
  public int zSrcConst;
  public int zSrcConstBitDepth;
}

Passes blit operations to the bltFx method. The information in this class includes raster operations, effects, and override information.

See also DirectDrawSurface.

Fields

alphaDestConst
Constant used as the alpha channel destination.
alphaDestConstBitDepth
Bit depth of the destination alpha constant.
alphaEdgeBlend
Alpha constant used for edge blending.
alphaEdgeBlendBitDepth
Bit depth of the constant for an alpha edge blend.
alphaSrcConst
Constant used as the alpha channel source.
alphaSrcConstBitDepth
Bit depth of the source alpha constant.
ddfx
One or more values of DDBLTFX_ type, specifying FX operations.
ddrop
Specifies the DirectDraw raster operations.
destColorSpaceHighValue
The destination high value of the color range that is to be used as the color key.
destColorSpaceLowValue
The destination low value of the color range that is to be used as the color key.
fillValue
Color used to fill a surface when DDBLT_COLORFILL is specified. This value can be either an RGB triple or a palette index, depending on the surface type.
rop
Specifies the Win32 raster operations.
rotationAngle
Rotation angle for the blit.
srcColorSpaceHighValue
The source high value of the color range that is to be used as the color key.
srcColorSpaceLowValue
The source low value of the color range that is to be used as the color key.
zbufferBaseDest
Destination base value of a z-buffer.
zbufferHigh
High limit of a z-buffer.
zbufferLow
Low limit of a z-buffer.
zbufferOpCode
Z-buffer compares.
zDestConst
Constant used as the z-buffer destination.
zDestConstBitDepth
Bit depth of the destination z-constant.
zSrcConst
Constant used as the z-buffer source.
zSrcConstBitDepth
Bit depth of the source z-constant.


Class DDCaps

public final class DDCaps
{
  // Fields
  public int alignBoundaryDest;
  public int alignBoundarySrc;
  public int alignSizeDest;
  public int alignSizeSrc;
  public int alignStrideAlign;
  public int alphaBltConstBitDepths;
  public int alphaBltPixelBitDepths;
  public int alphaBltSurfaceBitDepths;
  public int alphaOverlayConstBitDepths;
  public int alphaOverlayPixelBitDepths;
  public int alphaOverlaySurfaceBitDepths;
  public int caps;
  public int caps2;
  public int colorkeyCaps;
  public int currVisibleOverlays;
  public int ddsCaps;
  public int fxAlphaCaps;
  public int fxCaps;
  public int maxVisibleOverlays;
  public int numFourCCCodes;
  public int palCaps;
  public int rops1;
  public int rops2;
  public int rops3;
  public int rops4;
  public int rops5;
  public int rops6;
  public int rops7;
  public int rops8;
  public int stereovisionCaps;
  public int vidMemFree;
  public int vidMemTotal;
  public int zbufferBitDepths;
}

Represents the capabilities of the hardware exposed through the DirectDraw object. This class contains the ddsCaps field that describes what kinds of DirectDrawSurface objects can be created. It may not be possible to simultaneously create all of the surfaces described by these capabilities. This class is used with the DirectDraw.getCaps and DirectDrawPalette.getCaps methods.

Note The original DDCaps class is a combination of the current DDCaps and DDCapsFx classes.

Fields

alignBoundaryDest
Destination rectangle alignment.
alignBoundarySrc
Source rectangle alignment.
alignSizeDest
Destination rectangle byte size.
alignSizeSrc
Source rectangle byte size.
alignStrideAlign
Stride alignment.
alphaBltConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicates 2-, 4-, or 8-bits per pixel.)
alphaBltPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1-, 2-, 4-, or 8-bits per pixel.)
alphaBltSurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1-, 2-, 4-, or 8-bits per pixel.)
alphaOverlayConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicates 2-, 4-, or 8-bits per pixel.)
alphaOverlayPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1-, 2-, 4-, or 8-bits per pixel.)
alphaOverlaySurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1-, 2-, 4-, or 8-bits per pixel.)
caps
One or more values of DDCaps_ type, specifying driver-specific capabilities.
caps2
One or more values of DDCaps2_ type, specifying driver-specific capabilities.
colorkeyCaps
One or more values of DDCKEYCAPS_ type, specifying color-key capabilities.
currVisibleOverlays
Current number of visible overlays.
ddsCaps
One or more values of DDSCAPS_ type, specifying general capabilities.
fxAlphaCaps
One or more values of DDFXALPHACAPS_ type, specifying driver-specific alpha capabilities.
fxCaps
One or more values of DDFXCAPS_ type, specifying driver-specific stretching and effects capabilities.
maxVisibleOverlays
Maximum number of visible overlays.
numFourCCCodes
Number of FourCC codes.
palCaps
One or more values of DDPCAPS_ type, specifying palette capabilities.
rops1
Raster operations supported.
rops2
Raster operations supported.
rops3
Raster operations supported.
rops4
Raster operations supported.
rops5
Raster operations supported.
rops6
Raster operations supported.
rops7
Raster operations supported.
rops8
Raster operations supported.
stereovisionCaps
One or more values of DDSVCAPS_ type, specifying stereo vision capabilities.
vidMemFree
Amount of free display memory.
vidMemTotal
Total amount of display memory.
zbufferBitDepths
DDBD_8, DDBD_16, DDBD_24, or DDBD_32. (Indicates 8-, 16-, 24-, or 32-bits per pixel.)


Class DDCapsFx

public final class DDCapsFx
{
  // Fields
  public int maxHwCodecStretch;
  public int maxLiveVideoStretch;
  public int maxOverlayStretch;
  public int minHwCodecStretch;
  public int minLiveVideoStretch;
  public int minOverlayStretch;
  public int ssbCaps;
  public int ssbCFXCaps;
  public int ssbCKeyCaps;
  public int ssbRops1;
  public int ssbRops2;
  public int ssbRops3;
  public int ssbRops4;
  public int ssbRops5;
  public int ssbRops6;
  public int ssbRops7;
  public int ssbRops8;
  public int svbCaps;
  public int svbCKeyCaps;
  public int svbFXCaps;
  public int svbRops1;
  public int svbRops2;
  public int svbRops3;
  public int svbRops4;
  public int svbRops5;
  public int svbRops6;
  public int svbRops7;
  public int svbRops8;
  public int vsbCaps;
  public int vsbCKeyCaps;
  public int vsbFXCaps;
  public int vsbRops1;
  public int vsbRops2;
  public int vsbRops3;
  public int vsbRops4;
  public int vsbRops5;
  public int vsbRops6;
  public int vsbRops7;
  public int vsbRops8;
}

Represents the capabilities of the hardware exposed through the DirectDraw object. It may not be possible to simultaneously create all of the surfaces described by these capabilities. This class is used with the DirectDraw.getCaps and DirectDrawPalette.getCaps methods.

Note The original DDCaps class is a combination of the current DDCaps and DDCapsFx classes.

Fields

maxHwCodecStretch
Maximum hardware codec stretch factor multiplied by 1000. For example 1.3 = 1300.
maxLiveVideoStretch
Maximum live video stretch factor multiplied by 1000. For example, 1.3 = 1300.
maxOverlayStretch
Maximum overlay stretch factor multiplied by 1000. For example, 1.3 = 1300.
minHwCodecStretch
Minimum hardware codec stretch factor multiplied by 1000.
minLiveVideoStretch
Minimum live video stretch factor multiplied by 1000.
minOverlayStretch
Minimum overlay stretch factor multiplied by 1000.
ssbCaps
Driver-specific capabilities for system-memory-to-system-memory blits.
ssbCFXCaps
Driver FX capabilities for system-memory-to-system-memory blits.
ssbCKeyCaps
Driver color-key capabilities for system-memory-to-system-memory blits.
ssbRops1
Raster operations supported for system-memory-to-system-memory blits.
ssbRops2
Raster operations supported for system-memory-to-system-memory blits.
ssbRops3
Raster operations supported for system-memory-to-system-memory blits.
ssbRops4
Raster operations supported for system-memory-to-system-memory blits.
ssbRops5
Raster operations supported for system-memory-to-system-memory blits.
ssbRops6
Raster operations supported for system-memory-to-system-memory blits.
ssbRops7
Raster operations supported for system-memory-to-system-memory blits.
ssbRops8
Raster operations supported for system-memory-to-system-memory blits.
svbCaps
Driver-specific capabilities for system-memory-to-display-memory blits.
svbCKeyCaps
Driver color-key capabilities for system-memory-to-display-memory blits.
svbFXCaps
Driver FX capabilities for system-memory-to-display-memory blits.
svbRops1
Raster operations supported for system-memory-to-display-memory blits.
svbRops2
Raster operations supported for system-memory-to-display-memory blits.
svbRops3
Raster operations supported for system-memory-to-display-memory blits.
svbRops4
Raster operations supported for system-memory-to-display-memory blits.
svbRops5
Raster operations supported for system-memory-to-display-memory blits.
svbRops6
Raster operations supported for system-memory-to-display-memory blits.
svbRops7
Raster operations supported for system-memory-to-display-memory blits.
svbRops8
Raster operations supported for system-memory-to-display-memory blits.
vsbCaps
Driver-specific capabilities for display-memory-to-system-memory blits.
vsbCKeyCaps
Driver color-key capabilities for display-memory-to-system-memory blits.
vsbFXCaps
Driver FX capabilities for display-memory-to-system-memory blits.
vsbRops1
Supports raster operations for display-memory-to-system-memory blits.
vsbRops2
Supports raster operations for display-memory-to-system-memory blits.
vsbRops3
Supports raster operations for display-memory-to-system-memory blits.
vsbRops4
Supports raster operations for display-memory-to-system-memory blits.
vsbRops5
Supports raster operations for display-memory-to-system-memory blits.
vsbRops6
Supports raster operations for display-memory-to-system-memory blits.
vsbRops7
Supports raster operations for display-memory-to-system-memory blits.
vsbRops8
Supports raster operations for display-memory-to-system-memory blits.


Class DDColorKey

public final class DDColorKey
{
  // Fields
  public int colorSpaceHighValue;
  public int colorSpaceLowValue;
}

Describes a source color key, destination color key or color space. A color key is specified if the low and high range values are the same. This class is used with the getColorKey and setColorKey methods.

Fields

colorSpaceHighValue
High value, inclusive, of the color range that is to be used as the color key.
colorSpaceLowValue
Low value, inclusive, of the color range that is to be used as the color key.


Class DDPixelFormat

public final class DDPixelFormat
{
  // Fields
  public int alphaBitDepth;
  public int alphaBitMask;
  public int blueBitMask;
  public int flags;
  public int fourCC;
  public int greenBitMask;
  public int redBitMask;
  public int rgbBitCount;
  public int uBitMask;
  public int vBitMask;
  public int yBitMask;
  public int yuvAlphaBitMask;
  public int yuvBitCount;
  public int zbufferBitDepth;
}

Describes the pixel format of a DirectDrawSurface object for the getPixelFormat method.

Fields

alphaBitDepth
Depth of alpha buffer.
alphaBitMask
Mask for alpha channel.
blueBitMask
Mask for blue bits.
flags
Optional control flags. These include the following:
DDPF_ALPHA
The pixel format describes an alpha-only surface.
DDPF_ALPHAPIXELS
The surface has alpha channel information in the pixel format.
DDPF_COMPRESSED
The surface will accept pixel data in the specified format and compress it during the write operation.
DDPF_FOURCC
The FourCC code is valid.
DDPF_PALETTEINDEXED1
DDPF_PALETTEINDEXED2
DDPF_PALETTEINDEXED4
DDPF_PALETTEINDEXED8
The surface is 1-, 2-, 4-, or 8-bit color indexed.
DDPF_PALETTEINDEXEDTO8
The surface is 1-, 2-, or 4-bit color indexed to an 8-bit palette.
DDPF_RGB
The RGB data in the pixel format structure is valid.
DDPF_RGBTOYUV
The surface will accept RGB data and translate it during the write operation to YUV data. The format of the data to be written will be contained in the pixel format structure. The DDPF_RGB flag will be set.
DDPF_YUV
The YUV data in the pixel format structure is valid.
DDPF_ZBUFFER
The pixel format describes a z-buffer-only surface.
fourCC
FourCC code.
greenBitMask
Mask for green bits.
redBitMask
Mask for red bits.
rgbBitCount
RGB bits per pixel (4, 8, 16, 24, or 32).
uBitMask
Mask for U bits.
vBitMask
Mask for V bits.
yBitMask
Mask for Y bits.
yuvAlphaBitMask
Mask for alpha channel.
yuvBitCount
YUV bits per pixel (DDBD_4, DDBD_8, DDBD_16, DDBD_24, or DDBD_32).
zbufferBitDepth
Z-buffer bit depth (8, 16, 24, or 32).


Class DDSurfaceDesc

public final class DDSurfaceDesc
{
  // Fields
  public int alphaBitDepth;
  public int alphaBitMask;
  public int backBufferCount;
  public int blueBitMask;
  public int colorkeyDestBltHigh;
  public int colorkeyDestBltLow;
  public int colorkeyDestOverlayHigh;
  public int colorkeyDestOverlayLow;
  public int colorkeySrcBltHigh;
  public int colorkeySrcBltLow;
  public int colorkeySrcOverlayHigh;
  public int colorkeySrcOverlayLow;
  public int ddsCaps;
  public int flags;
  public int fourCC;
  public int greenBitMask;
  public int height;
  public int mipmapCount;
  public int pitch;
  public int pixelFormatFlags;
  public int redBitMask;
  public int refreshRate;
  public int rgbBitCount;
  public int uBitMask;
  public int vBitMask;
  public int width;
  public int yBitMask;
  public int yuvAlphaBitMask;
  public int yuvBitCount;
  public int zbufferBitDepth;
}

Contains a description of the surface to be created. This class is passed to the createSurface method. The relevant fields differ for each potential type of surface.

Fields

alphaBitDepth
The depth of the alpha buffer.
alphaBitMask
The bitmask for the alpha channel.
backBufferCount
The number of back buffers.
blueBitMask
The bitmask for the blue bits.
colorkeyDestBltHigh
Color key for destination blit use.
colorkeyDestBltLow
Color key for destination blit use.
colorkeyDestOverlayHigh
Color key for destination overlay use.
colorkeyDestOverlayLow
Color key for destination overlay use.
colorkeySrcBltHigh
Color key for source blit use.
colorkeySrcBltLow
Color key for source blit use.
colorkeySrcOverlayHigh
Color key for source overlay use.
colorkeySrcOverlayLow
Color key for source overlay use.
ddsCaps
One or more values of DDSCAPS_ type specifying DirectDraw surface capabilities.
flags
One or more values of DDSD_ type.
fourCC
FourCC code.
greenBitMask
The bitmask for the green bits.
height
Height of the surface.
mipmapCount
The number of mipmap levels.
pitch
Distance to the start of the next line (return value only).
pixelFormatFlags
One or more values of DDPF_ type.
redBitMask
The bitmask for the red bits.
refreshRate
Used when the display mode is described.
rgbBitCount
The number of RGB bits per pixel (4, 8, 16, 24, or 32).
uBitMask
The bitmask for the U bits.
vBitMask
The bitmask for the V bits.
width
Width of the input surface.
yBitMask
The bitmask for the Y bits.
yuvAlphaBitMask
Mask for alpha channel.
yuvBitCount
The number of YUV bits per pixel (DDBD_4, DDBD_8, DDBD_16, DDBD_24, or DDBD_32).
zbufferBitDepth
Z-buffer bit depth (8, 16, 24, or 32).


Class Direct3d

public class Direct3d implements IDirect3d
{
  // Methods
  public Direct3dLight createLight();
  public Direct3dMaterial createMaterial();
  public Direct3dViewport createViewport();
  public void enumDevices(Id3dEnumDevicesCallback fn, IUnknown p);
  public void findDevice(D3dFindDeviceSearch ds,
        D3dFindDeviceResult hresult, D3dFindDeviceResult sresult);
  public _Guid findDeviceForColorModel(int cm, int hardware);
  public void initialize(_Guid id);
  public int systemBpp();
}

Applications use the methods of the Direct3d class to create Direct3D objects and set up the environment.

Methods

createLight

public Direct3dLight createLight();

Allocates a Direct3dLight object.

Return Value:

Returns the Direct3dLight object if successful; otherwise, returns null.

createMaterial

public Direct3dMaterial createMaterial();

Allocates a Direct3dMaterial object.

Return Value:

Returns the Direct3dMaterial object if successful; otherwise, returns null.

createViewport

public Direct3dViewport createViewport();

Creates a Direct3dViewport object. The viewport is associated with a Direct3DDevice object by using the addViewport method.

Return Value:

Returns the Direct3dViewport object if successful; otherwise, returns null.

enumDevices

public void enumDevices(Id3dEnumDevicesCallback fn, IUnknown p);

Enumerates all Microsoft® Direct3D® device drivers installed on the system.

Return Value:

No return value.

Parameter | Description
fn | An interface containing a callback function that the enumeration procedure will call every time a match is found.
p | Application-defined data passed to the callback function.

findDevice

public void findDevice(D3dFindDeviceSearch ds, D3dFindDeviceResult hresult,
        D3dFindDeviceResult sresult);

Searches for and returns information about devices that match the given description.

Return Value:

No return value.

Parameter | Description
ds | The D3dFindDeviceSearch object that contains a description of the device(s) to search for.
hresult | The D3dFindDeviceSearch object that receives the hardware device results of the search.
sresult | The D3dFindDeviceResult object that receives the software device results of the search.

findDeviceForColorModel

public _Guid findDeviceForColorModel(int cm, int hardware);

Finds a device with specified color model characteristics and retrieves a description of it.

Return Value:

No return value.

Parameter | Description
cm | One value of D3DCOLOR_ type, specifying the color model to locate.
hardware | Set this value to 1 to specify that the device should be a hardware-only renderer; set to 0 for software only.

initialize

public void initialize(_Guid id);

Initializes the Direct3d object.

Return Value:

No return value.

Parameter | Description
id | A universally unique identifier (UUID).

systemBpp

public int systemBpp();

Returns the system bits-per-pixel value.

Return Value:

Returns the bits-per-pixel.


Class Direct3dDevice

public class Direct3dDevice implements IDirect3dDevice
{
  // Methods
  public void addViewport(Direct3dViewport vport);
  public void beginScene();
  public Direct3dExecuteBuffer createExecuteBuffer(
        D3dExecuteBufferDesc ebufDesc);
  public int createMatrix();
  public void deleteMatrix(int hdl);
  public void deleteViewport(Direct3dViewport vport);
  public void endScene();
  public void enumTextureFormats(IEnumTextureFormatsCallback fn,
        IUnknown args);
  public void execute(Direct3dExecuteBuffer eb,
        Direct3dViewport vp, int flags);
  public void getCaps(D3dDeviceDesc hwDesc, D3dDeviceDesc helDesc);
  public Direct3d getDirect3D();
  public void getMatrix(int hdl, D3dMatrix mat);
  public void getPickRecords(int[] flags, D3dPickRecord val);
  public void getStats(D3dStats stat);
  public void initialize(Direct3d dev, _Guid g,
        D3dDeviceDesc devDesc);
  public Direct3dViewport nextViewport(Direct3dViewport vp1,
        int flags);
  public void pick(Direct3dExecuteBuffer eb,
        Direct3dViewport vport, int flags, D3dRect rectangle);
  public void setMatrix(int hdl, D3dMatrix mat);
  public void swapTextureHandles(Direct3dTexture tex1,
        Direct3dTexture tex2);
}

Applications use the methods of the Direct3dDevice class to retrieve and set the capabilities of Microsoft® Direct3D® devices.

Methods

addViewport

public void addViewport(Direct3dViewport vport);

Adds the specified viewport to the list of viewport objects associated with the device.

Return Value:

No return value.

Parameter | Description
vport | The viewport object that should be associated with this Direct3dDevice object.

beginScene

public void beginScene();

Begins a scene.

Return Value:

No return value.

Remarks:

Applications must call this method before performing any rendering, and must call endScene when rendering is complete.

See Also: endScene

createExecuteBuffer

public Direct3dExecuteBuffer createExecuteBuffer(
        D3dExecuteBufferDesc ebufDesc);

Allocates an execute buffer for a display list. The list may be read by hardware DMA into VRAM for processing. All display primitives in the buffer that have indices to vertices must also have those vertices in the same buffer.

Return Value:

Returns the Direct3dExecuteBuffer if successful; otherwise, null.

Parameter | Description
ebufDesc | Describes the Direct3dExecuteBuffer object to be created. The call will fail if a buffer of at least the specified size cannot be created.

Remarks:

The D3dExecuteBufferDesc object describes the execute buffer to be created. At a minimum, the application must specify the size required. If the application specifies DEBCAPS_VIDEO_MEMORY in the capabilities field, Direct3D will attempt to keep the execute buffer in video memory.

The application can use the lock method to request that the memory be moved. When this method returns, it will adjust the contents of the D3dExecuteBufferDesc object to indicate whether the data resides in system or video memory.

createMatrix

public int createMatrix();

Creates a matrix.

Return Value:

Returns a handle to the matrix that is created. The call will fail if a buffer of at least the size of the matrix cannot be created.

See Also: deleteMatrix, setMatrix

deleteMatrix

public void deleteMatrix(int hdl);

Deletes a matrix handle. This matrix handle must have been created by using the createMatrix method.

Return Value:

No return value.

Parameter | Description
hdl | Matrix handle to be deleted.

See Also: createMatrix, setMatrix

deleteViewport

public void deleteViewport(Direct3dViewport vport);

Removes the specified viewport from the list of viewport objects associated with the device.

Return Value:

No return value.

Parameter | Description
vport | A viewport object that should be disassociated with this Direct3dDevice object.

endScene

public void endScene();

Ends a scene that was begun by calling the beginScene method.

Return Value:

No return value.

See Also: beginScene

enumTextureFormats

public void enumTextureFormats(IEnumTextureFormatsCallback fn,
        IUnknown args);

Queries the current driver for a list of supported texture formats.

Return Value:

No return value.

Parameter | Description
fn | Callback interface containing the function that the enumeration procedure will call for each texture format.
args | Application-defined data passed to the callback function.

execute

public void execute(Direct3dExecuteBuffer eb, Direct3dViewport vp,
        int flags);

Executes a buffer.

Return Value:

No return value.

Parameter | Description
eb | The Direct3dExecute buffer to be executed.
vp | The Direct3dViewport object that describes the transformation context, into which the execute buffer will be rendered.
flags | A value of D3DEXECUTE_ type, specifying whether objects in the buffer should be clipped.

getCaps

public void getCaps(D3dDeviceDesc hwDesc, D3dDeviceDesc helDesc);

Retrieves the capabilities of the Direct3dDevice object.

Return Value:

No return value.

Parameter | Description
hwDesc | The D3dDeviceDesc object that receives the hardware features of the device.
helDesc | The D3dDeviceDesc object that receives the software emulation being provided.

Remarks:

This method does not retrieve the capabilities of the display device. To retrieve this information, use the getCaps method.

getDirect3D

public Direct3d getDirect3D();

Retrieves the current Direct3d object.

Return Value:

Returns the Direct3d object if successful; otherwise, returns null.

getMatrix

public void getMatrix(int hdl, D3dMatrix mat);

Retrieves a matrix from a matrix handle. This matrix handle must have been created by using the createMatrix method.

Return Value:

No return value.

Parameter | Description
hdl | Handle of the matrix to be retrieved.
mat | The D3dMatrix object that receives the matrix.

See Also: createMatrix, deleteMatrix, setMatrix

getPickRecords

public void getPickRecords(int[] flags, D3dPickRecord val);

Retrieves the pick records for a device.

Return Value:

No return value.

Parameter | Description
flags | Valid flags for this method.
val | The D3dPickRecord object that receives a pick record.

getStats

public void getStats(D3dStats stat);

Retrieves statistics about a device.

Return Value:

No return value.

Parameter | Description
stat | The D3dStats object that receives the statistics.

initialize

public void initialize(Direct3d dev, _Guid g, D3dDeviceDesc devDesc);

Initializes a Direct3dDevice object.

Return Value:

No return value.

Parameter | Description
dev | The Direct3D device to use as an initializer.
g | The globally unique identifier (GUID) used as the interface identifier.
devDesc | The D3dDeviceDesc object describing the Direct3dDevice object to be initialized.

nextViewport

public Direct3dViewport nextViewport(Direct3dViewport vp1, int flags);

Enumerates the viewports associated with the device.

Return Value:

Returns the next Direct3dViewport object in the list of viewports associated with this Direct3DDevice object if successful; otherwise, returns null.

Parameter | Description
vpl | A viewport in the list of viewports associated with this Direct3dDevice object.
flags | A value of D3DNEXT_ type, specifying which viewport to retrieve from the list of viewports. The default setting is D3DNEXT_NEXT.

pick

public void pick(Direct3dExecuteBuffer eb, Direct3dViewport vport,
        int flags, D3dRect rectangle);

Executes a buffer without performing any rendering, but returns a z-ordered list of offsets to the primitives that cover the rectangle specified by Rect.

This call fails if the Direct3dExecuteBuffer object is locked.

Return Value:

No return value.

Parameter | Description
eb | An execute buffer from which the z-ordered list is retrieved.
vport | A viewport in the list of viewports associated with this Direct3dDevice object.
flags | No flags are currently defined for this method.
Rect | The D3dRect object specifying the range of device coordinates to be picked.

Remarks:

If the x1 and x2 fields of the object specified in the Rect parameter are equal, and the y1 and y2 members are equal, a single pixel is used for picking. The coordinates are specified in device-pixel space.

All Direct3dExecuteBuffer objects must be attached to a Direct3dDevice object for this method to succeed.

See Also: getPickRecords

setMatrix

public void setMatrix(int hdl, D3dMatrix mat);

Applies a matrix to a matrix handle. This matrix handle must have been created by using the createMatrix method.

Return Value:

No return value.

Parameter | Description
hdl | Matrix handle to be set.
mat | The D3dMatrix object that describes the matrix to be set.

Remarks:

Transformations inside the execute buffer include a handle of a matrix. The setMatrix method enables an application to change this matrix without having to lock and unlock the execute buffer.

See Also: createMatrix, getMatrix, deleteMatrix

swapTextureHandles

public void swapTextureHandles(Direct3dTexture tex1, Direct3dTexture tex2);

Swaps two texture handles.

Return Value:

No return value.

Parameter | Description
tex1 | The texture to be swapped.
tex2 | The texture to be swapped.

Remarks:

This method is useful when an application is changing all the textures in a complicated object.


Class Direct3dExecuteBuffer

public class Direct3dExecuteBuffer implements
            IDirect3dExecuteBuffer
{
  // Methods
  public int addLVertexData(D3dLVertex vertex, int bufferindex);
  public int addTLVertexData(D3dTLVertex vertex, int bufferindex);
  public int addVertexData(D3dVertex vertex, int bufferindex);
  public int exit(int bufferindex);
  public native void getDataAsArrayFloats(float[] d);
  public native void getDataAsArrayInts(int[] d);
  public void getExecuteData(D3dExecuteData data);
  public native int lineList(int cnt, char segs, int bufferindex);
  public void lock(D3dExecuteBufferDesc Desc);
  public native int matrixLoad(int hdest, int hsrc,
        int bufferindex);
  public native int matrixMultiply(int hsrc1, int hsrc2, int hdest,
        int bufferindex);
  public native int pointList(int cnt, char first, int bufferindex);
  public int processVertices(int cnt, int bufferindex);
  public int processVerticesData(int flags, int start, int dest,
        int cnt, int bufferindex);
  public native void setDataAsArrayFloats(float[] d);
  public native void setDataAsArrayInts(int[] d);
  public void setExecuteData(D3dExecuteData data);
  public int setStatus(int flags, int status, int x1, int y1,
        int x2, int y2, int bufferindex);
  public native int spanList(int cnt, char first, int bufferindex);
  public int stateLight(int cnt, int bufferindex);
  public int stateLightData(int flags, int Arg, int bufferindex);
  public int stateRender(int cnt, int bufferindex);
  public int stateRenderData(int flags, int Arg, int bufferindex);
  public int stateTransForm(int cnt, int bufferindex);
  public int stateTransFormData(int flags, int Arg,
        int bufferindex);
  public native int textureLoad(int hdest, int hsrc,
        int bufferindex);
  public int triangleList(int cnt, int bufferindex);
  public int triangleListData(D3dTriangle triangle,
        int bufferindex);
  public void unlock();
}

Applications use the methods of the Direct3dExecuteBuffer class to set up and control a Microsoft® Direct3D® execute buffer.

Note This class does not provide an initialize method. Use the Direct3dDevice.createExecuteBuffer method to create and initialize Direct3dExecuteBuffer objects.

Methods

addLVertexData

public int addLVertexData(D3dLVertex vertex, int bufferindex);

Adds a lit, untransformed vertex to the execute buffer at the position indicated by the bufferindex.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
vertex | A D3dVertex object.
bufferindex | The position in the execute buffer to place the vertex.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

addTLVertexData

public int addTLVertexData(D3dTLVertex vertex, int bufferindex);

Adds a lit and transformed vertex to the execute buffer at the position indicated by the bufferindex.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
vertex | A D3dVertex object.
bufferindex | The position in the execute buffer to place the vertex.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

addVertexData

public int addVertexData(D3dVertex vertex, int bufferindex);

Adds an unlit, untransformed vertex to the execute buffer at the position indicated by bufferindex.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
vertex | A D3dVertex object
bufferindex | The position in the execute buffer to place the vertex.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

exit

public int exit(int bufferindex);

getDataAsArrayFloats

public native void getDataAsArrayFloats(float[] d);

Retrieves the data contained in the execute buffer as an array of float types.

Return Value:

No return value.

Parameter | Description
d | The array of floats that the data is copied to.

getDataAsArrayInts

public native void getDataAsArrayInts(int[] d);

Retrieves the data contained in the execute buffer as an array of int types.

Return Value:

No return value.

Parameter | Description
d | The array of ints that the data is copied to.

getExecuteData

public void getExecuteData(D3dExecuteData data);

Retrieves the execute data state of the Direct3dExecuteBuffer object. The execute data is used to describe the contents of the object.

Return Value:

No return value.

Parameter | Description
data | The D3dExecuteData object that receives the current execute data state of the Direct3dExecuteBuffer object.

Remarks:

This call fails if the Direct3dExecuteBuffer object is locked.

See Also: setExecuteData

lineList

public native int lineList(int cnt, char segs, int bufferindex);

Sets the number of LINE instructions that will proceed with this instruction in the execute buffer. This method emulates the similar macro found in the Direct3d d3dmacs.h header file.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
segs
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

lock

public void lock(D3dExecuteBufferDesc Desc);

Obtains the command data from the execute buffer.

Return Value:

No return value.

Parameter | Description
Desc | The D3dExecuteBufferDesc object.

Remarks:

This method can obtain data from either system or video memory as specified by the caps field of Desc. The length of the array assigned to buffer must be set in the bufferSize field before making the call.

The application may use the lock method to request that Direct3D move the data between system or video memory.

This method fails if the Direct3dExecuteBuffer object is locked—that is, if another thread is accessing the buffer or if a Direct3dDevice.execute method that was issued on this buffer has not yet been completed.

See Also: unlock

matrixLoad

public native int matrixLoad(int hdest, int hsrc, int bufferindex);

Loads a matrix.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
hdest | The handle of the destination matrix.
hsrc | The handle of a source matrix.
bufferindex | The position in the execute buffer to place the instruction.

matrixMultiply

public native int matrixMultiply(int hsrc1, int hsrc2, int hdest,
        int bufferindex);

Multiplies two matrices.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
hsrc1 | The handle of one of the matrices to multiply.
hsrc2 | The handle of one of the matrices to multiply.
hdest | The handle of a destination matrix to copy the result of the multiplication to.
bufferindex | The position in the execute buffer to place the instruction.

pointList

public native int pointList(int cnt, char first, int bufferindex);

Sets the number of POINT instructions that will proceed with this instruction in the execute buffer. This method emulates the similar macro found in the Direct3d d3dmacs.h header file.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
first
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

processVertices

public int processVertices(int cnt, int bufferindex);

Sets the number of PROCESSVERTICES instructions that will proceed with this instruction in the execute buffer.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

processVerticesData

public int processVerticesData(int flags, int start, int dest, int cnt, int
        bufferindex);

Sets the data for the PROCESSVERTICES instruction in the execute buffer. This method describes how vertices in the execute buffer should be handled by the driver.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
flags The flags that indicate how the driver should process the vertices. These may be:
D3DPROCESSVERTICES_COPY
D3DPROCESSVERTICES_NOCOLOR
D3DPROCESSVERTICES_OPMASK
D3DPROCESSVERTICES_TRANSFORM
D3DPROCESSVERTICES_TRANSFORMLIGHT
D3DPROCESSVERTICES_UPDATEEXTENTS
start | The index of the first vertex in the source.
dest | The index of the first vertex in the local buffer.
cnt | The number of vertices to be processed.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

setDataAsArrayFloats

public native void setDataAsArrayFloats(float[] d);

Sets the data in the execute buffer to the specified array of floats.

Return Value:

No return value.

Parameter | Description
d | The array to set the data in the execute buffer to.

setDataAsArrayInts

public native void setDataAsArrayInts(int[] d);

Sets the data in the execute buffer to the specified array of ints.

Return Value:

No return value.

Parameter | Description
d | The array to set the data in the execute buffer to.

setExecuteData

public void setExecuteData(D3dExecuteData data);

Sets the execute data state of the Direct3dExecuteBuffer object. The execute data is used to describe the contents of the object.

Return Value:

No return value.

Parameter | Description
data | A D3dExecuteData object that describes the execute buffer layout.

Remarks:

This call fails if the Direct3dExecuteBuffer object is locked.

See Also: getExecuteData

setStatus

public int setStatus(int flags, int status, int x1, int y1, int x2, int y2,
        int bufferindex);

Resets the status of the execute buffer.

Return Value:

Returns the number of 32-bit values added to the buffer.

Parameter | Description
flags Specifies whether the status, extents, or both are being set.
D3DSETSTATUS_STATUS
Sets the status.
D3DSETSTATUS_EXTENTS
Sets the extents specified by a given bounding box (x1,y1,x2,y2).
D3DSETSTATUS_ALL
Sets both the status and the extents.
status The clipping flags. This parameter may be one or more of the following flags:
D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
Other CLIPINTERSECTION flags include D3DSTATUS_CLIPINTERSECTIONBACK, D3DSTATUS_CLIPINTERSECTIONBOTTOM, D3DSTATUS_CLIPINTERSECTIONFRONT, and D3DSTATUS_CLIPINTERSECTIONGEN0 through D3DSTATUS_CLIPINTERSECTIONGEN5.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
Other CLIPUNION flags include
D3DSTATUS_CLIPUNIONBOTTOM,
D3DSTATUS_CLIPUNIONTOP, D3DSTATUS_CLIPUNIONLEFT, and D3DSTATUS_CLIPUNIONRIGHT.
D3DSTATUS_DEFAULT
the default is a combination of D3DSTATUS_CLIPINTERSECTION and D3DSTATUS_ZNOTVISIBLE flags.
Basic clipping flags include D3DCLIP_BACK, D3DCLIP_LEFT, and D3DCLIP_TOP.
x1 | Defines a bounding box for all relevant vertices. The x coordinate of the bounding box's upper-left corner.
x2 | The y coordinate of the bounding box's upper-left corner.
y1 | The x coordinate of the bounding box's lower-right corner.
y2 | The y coordinate of the bounding box's lower-right corner.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The status is a rolling status and is updated during each execution. The bounding box specified can grow with each execution, but it does not shrink. It can be reset by calling this method again.

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

spanList

public native int spanList(int cnt, char first, int bufferindex);

Sets the number of SPAN instructions that will proceed with this instruction in the execute buffer. This method emulates the similar macro found in the Direct3d d3dmacs.h header file.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
first
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateLight

public int stateLight(int cnt, int bufferindex);

Sets the number of STATELIGHT instructions that will proceed with this instruction in the execute buffer. This method emulates the similar macro found in the Direct3d d3dmacs.h header file.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateLightData

public int stateLightData(int flags, int Arg, int bufferindex);

Describes the transformation state for the STATELIGHT instruction.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
flags One of the following values:
D3DLIGHTSTATE_MATERIAL
Defines the material used to compute the final color and intensity values during rasterization.
D3DLIGHTSTATE_AMBIENT
Sets the color and intensity of the current ambient light.
D3DLIGHTSTATE_COLORMODEL
One of the D3DCOLORMODEL types.
D3DLIGHTSTATE_FOGMODE
One of the D3DFOGMODE types.
D3DLIGHTSTATE_FOGSTART
Defines the starting value for fog.
D3DLIGHTSTATE_FOGEND
Defines the ending value for fog.
D3DLIGHTSTATE_FOGDENSITY
Defines the density setting for fog.
Arg | A value that is dependant on which flag is set.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateRender

public int stateRender(int cnt, int bufferindex);

Sets the number of STATERENDER instructions in the execute buffer.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateRenderData

public int stateRenderData(int flags, int Arg, int bufferindex);

Describes the render state for the STATERENDER instruction.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
flags | The flags that describe the render state. For a complete listing of D3DRENDERSTATE_ flags, see DirectXConstants.
Arg | A value that is dependant on the D3DRENDERSTATE_ flag.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateTransForm

public int stateTransForm(int cnt, int bufferindex);

Sets the number of STATETRANSFORM instructions that will proceed with this instruction in the execute buffer.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

stateTransFormData

public int stateTransFormData(int flags, int Arg, int bufferindex);

Describes the transformation state for the STATETRANSFORM instruction.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
flags May be one of the following flags:
D3DTRANSFORMSTATE_WORLD
D3DTRANSFORMSTATE_VIEW
D3DTRANSFORMSTATE_PROJECTION
Arg | The handle of the matrices for the world, view, and projection transformations. The default values for these are null.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

textureLoad

public native int textureLoad(int hdest, int hsrc, int bufferindex);

Loads a texture.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
hdest | The handle of the destination texture.
hsrc | The handle of a source texture.
bufferindex | The position in the execute buffer to place the instruction.

triangleList

public int triangleList(int cnt, int bufferindex);

Sets the number of TRIANGLE instructions that will proceed with this instruction in the execute buffer. This method emulates the similar macro found in the Direct3d d3dmacs.h header file.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
cnt | The number of instructions.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

triangleListData

public int triangleListData(D3dTriangle triangle, int bufferindex);

Describes the transformation state for the TRIANGLE instruction.

Return Value:

Returns the number of 32-bit values added.

Parameter | Description
triangle | The D3dTriangle object.
bufferindex | The position in the execute buffer to place the instruction.

Remarks:

The execute buffer is treated as an array of 32-bit values, which is a collection of floats and ints that describe vertices and instructions. It is up to the user to manage the position of each item added to the buffer.

unlock

public void unlock();

Releases access to the commands in the execute buffer. This must be done prior to calling the execute method for the buffer.

Return Value:

No return value.

See Also: lock


Class Direct3dLight

public class Direct3dLight implements IDirect3dLight
{
  // Methods
  public void getLight(D3dLightDesc light);
  public void setLight(D3dLightDesc light);
}

Applications use the methods of the Direct3dLight class to retrieve and set the capabilities of lights.

Note This class does not provide an initialize method. Use the Direct3d.createLight() method to create and initialize Direct3dLight objects.

Methods

getLight

public void getLight(D3dLightDesc light);

Retrieves the light information for the Direct3dLight object.

Return Value:

No return value.

Parameter | Description
light | The D3dLightDesc object that receives the current light data.

See Also: setLight

setLight

public void setLight(D3dLightDesc light);

Sets the light information for the Direct3dLight object.

Return Value:

No return value.

Parameter | Description
light | The Direct3dLight object that contains the light data to set.

See Also: getLight


Class Direct3dMaterial

public class Direct3dMaterial implements IDirect3dMaterial
{
  // Methods
  public int getHandle(Direct3dDevice dev);
  public void getMaterial(D3dMaterialDesc mat);
  public void reserve();
  public void setMaterial(D3dMaterialDesc mat);
  public void unreserve();
}

Applications use the methods of the Direct3dMaterial class to retrieve and set the properties of materials.

Note This class does not provide an initialize method. Use the Direct3d.createMaterial() method to create and initialize Direct3dMaterial objects.

Methods

getHandle

public int getHandle(Direct3dDevice dev);

Obtains the material handle for the Direct3dMaterial object. This handle is used in all Direct3D API calls where a material is to be referenced. A material can be used by only one device at a time.

If the device is destroyed, the material is disassociated from the device.

Return Value:

Returns the material handle corresponding to the Direct3dMaterial object.

Parameter | Description
dev | The Direct3dDevice object in which the material is being used.

getMaterial

public void getMaterial(D3dMaterialDesc mat);

Retrieves the material data for the Direct3dMaterial object.

Return Value:

No return value.

Parameter | Description
mat | A D3dMaterialDesc object that receives the current material properties.

See Also: setMaterial

reserve

public void reserve();

Not currently implemented.

setMaterial

public void setMaterial(D3dMaterialDesc mat);

Sets the material data for the Direct3dMaterial object.

Return Value:

No return value.

Parameter | Description
mat | A D3dMaterialDesc object that contains the material properties to set.

See Also: getMaterial

unreserve

public void unreserve();

Not currently implemented.


Class Direct3dRM

public class Direct3dRM implements IDirect3dRM
{
  // Methods
  public void addSearchPath(String name);
  public Direct3dRMAnimation createAnimation();
  public Direct3dRMAnimationSet createAnimationSet();
  public int createColorRGB(float red, float green, float blue);
  public Direct3dRMDevice createDevice(int v1, int v2);
  public Direct3dRMDevice createDeviceFromClipper(DirectDrawClipper
        lpDDClipper, _Guid g, int width, int height);
  public Direct3dRMDevice createDeviceFromD3D(Direct3d direct3d,
        Direct3dDevice direct3dDevice));
  public Direct3dRMDevice createDeviceFromSurface(_Guid g,
        DirectDraw dd, DirectDrawSurface DDsBack);
  public Direct3dRMFace createFace();
  public Direct3dRMFrame createFrame(Direct3dRMFrame parent);
  public Direct3dRMLight createLight(int t, int c);
  public Direct3dRMLight createLightRGB(int lt, float vred,
        float vgreen, float vblue);
  public Direct3dRMMaterial createMaterial(float d);
  public Direct3dRMMesh createMesh();
  public Direct3dRMMeshBuilder createMeshBuilder();
  public Direct3dRMVisual createShadow(Direct3dRMVisual v,
        Direct3dRMLight l, float px, float py, float pz,
        float nx, float ny, float nz);
  public Direct3dRMVisual createShadowFromFrame(
        Direct3dRMFrame frame, Direct3dRMLight direct3dRMLight,
        float px, float py, float pz, float nx, float ny,
        float nz);
  public Direct3dRMVisual createShadowFromMesh(Direct3dRMMesh mesh,
        Direct3dRMLight direct3dRMLight, float px, float py,
        float pz, float nx, float ny, float nz);
  public Direct3dRMVisual createShadowFromMeshBuilder(
        Direct3dRMMeshBuilder mb, Direct3dRMLight l, float px,
        float py, float pz, float nx, float ny, float nz);
  public Direct3dRMTexture createTexture(D3dRMImage image,
        byte[] buffer1, byte[] pal);
  public Direct3dRMTexture createTextureFromSurface(
        DirectDrawSurface ddS);
  public Direct3dRMUserVisual createUserVisual(
        IUserVisualCallback fn, IUnknown Arg);
  public Direct3dRMViewport createViewport(Direct3dRMDevice dev,
        Direct3dRMFrame fr, int l, int t, int w, int h);
  public Direct3dRMWrap createWrap(int t, Direct3dRMFrame f,
        float ox, float oy, float oz, float dx, float dy,
        float dz, float ux, float uy, float uz, float ou,
        float ov, float su, float sv);
  public void enumerateObjects(IEnumerateObjectsCallback fn,
        IUnknown pArgs);
  public Direct3dRMDeviceArray getDevices();
  public Direct3dRMObject getNamedObject(String name);
  public String getSearchPath();
  public void loadFromFileByPos(String fnam, int[] id, _Guid g, int
        cnt, int options, ILoadCallback fn1, int[] arg1,
        ILoadTextureCallback fn2, int[] arg2, Direct3dRMFrame f);
  public Direct3dRMTexture loadTexture(String name);
  public Direct3dRMTexture loadTextureFromResource(int hnd);
  public void setDefaultTextureColors(int ds);
  public void setDefaultTextureShades(int ds);
  public void setSearchPath(String name);
  public void tick(float val);
  public void vectorAdd(D3dVector lpd, D3dVector lps1,
        D3dVector lps2);
  public void vectorCrossProduct(D3dvector lpd, D3dvector lps1,
        D3dvector lps2);
  public float vectorDotProduct(D3dVector lps1, D3dVector lps2);
  public float vectorModulus(D3dVector d);
  public void vectorNormalise(D3dvector d);
  public void vectorRandom(D3dVector d);
  public void vectorReflect(D3dVector lpd, D3dVector lpRay,
        D3dVector lpNorm);
  public void vectorRotate(D3dVector lpr, D3dVector lpv,
        D3dVector lpaxis, float theta);
  public void vectorScale(D3dVector lpd, D3dVector lps,
        float factor);
  public void vectorSubtract(D3dVector lpd, D3dVector lps1,
        D3dVector lps2);
}

Applications use the methods of the Direct3dRM class to create Direct3dRM objects and work with system-level variables.

Methods

addSearchPath

public void addSearchPath(String name);

Adds a list of directories to the end of the current file search path.

Return Value:

No return value.

Parameter | Description
name | A string specifying the path to add to the current search path.

Remarks:

For Windows, the path should be a list of directories separated by semicolons (;).

See Also: setSearchPath

createAnimation

public Direct3dRMAnimation createAnimation();

Creates an empty Direct3dRMAnimation object.

Return Value:

Returns the Direct3dRMAnimation object if successful; otherwise, null.

createAnimationSet

public Direct3dRMAnimationSet createAnimationSet();

Creates an empty Direct3dRMAnimationSet object.

Return Value:

Returns the Direct3dRMAnimationSet object if successful; otherwise, null.

createColorRGB

public int createColorRGB(float red, float green, float blue);

Creates an RGB color value.

Return Value:

Returns a color value.

Parameter | Description
red | The red component of the color.
green | The green component of the color.
blue | The blue component of the color.

createDevice

public Direct3dRMDevice createDevice(int v1, int v2);

Not implemented on the Windows platform.

createDeviceFromClipper

public Direct3dRMDevice createDeviceFromClipper(
        DirectDrawClipper lpDDClipper, _Guid g, int width, int height);

Creates a Microsoft® Direct3DRM windows device by using a specified DirectDrawClipper object.

Return Value:

Returns the Direct3dRMDevice object if successful; otherwise, null.

Parameter | Description
lpDDrawClipper | A DirectDrawClipper object.
g | A globally unique identifier (GUID). This parameter can be null.
width | The width of the device to be created.
height | The height of the device to be created.

Remarks:

If the g parameter is null, the system searches for a device with a default set of device capabilities. This is the recommended way to create a Retained-Mode device because it always works, even if the user installs new hardware.

If a hardware device is not found, the monochromatic (ramp) software driver is loaded. An application should enumerate devices instead of specifying null for g if it has special needs that are not met by default settings.

If you are having palette problems using this method, try using the createDeviceFromD3D as an alternative.

createDeviceFromD3D

public Direct3dRMDevice createDeviceFromD3D(Direct3d direct3d,
        Direct3dDevice direct3dDevice));

Creates a Microsoft ®Direct3dRM Windows® device by using specified Direct3d objects. It is important that all objects are derived from the same DirectDraw object. In DirectX for Java, it is also important to use create methods to construct objects, rather than using new. Using new to create certain DirectX for Java objects creates uninitialized objects that can be difficult or impossible to manipulate.

See the createDeviceFromSurface method for a sample using standard techniques to create a Retain Mode object.

Return Value:

Returns the Direct3dRMDevice object if successful; otherwise, null.

Parameter | Description
direct3d | A Microsoft® Direct3D® object.
direct3dDevice | A Direct3dDevice object.

createDeviceFromSurface

public Direct3dRMDevice createDeviceFromSurface(_Guid g, DirectDraw dd,
        DirectDrawSurface DDsBack);

Creates a Microsoft® Windows® device for rendering from the specified DirectDraw surfaces. It is important that all objects are derived from the same DirectDraw object. In DirectX for Java, it is also important to use create methods to construct objects, rather than using new. Using new to create certain DirectX for Java objects creates uninitialized objects that can be difficult or impossible to manipulate.

The following code example shows how to use the createDeviceFromSurface method and create appropriate objects without using new.

int hw =0;  //depends on hardware
dd = new DirectDraw();
dd.setCooperativeLevel (this, DDSCL_NORMAL);

//Create a surface
ddsd = new DDSurfaceDesc();
ddsd.flags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;

if (hw==1){
ddsd.ddsCaps = DDSCAPS_3DDEVICE | DDSCAPS_OFFSCREENPLAIN | CAPS_VIDEOMEMORY;
}
else{
ddsd.ddsCaps = DDSCAPS_3DDEVICE | DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
}
ddsd.width   = w;
ddsd.height  = h;
ddsOffscreen = dd.createSurface(ddsd);
d3d = dd.createD3D();

// Find the device's Guid for a device type specified by
// application info object - can be RGB or MONO
//
_Guid g = d3d.findDeviceForColorModel(D3DCOLOR_RGB, hw );
rmDevice = d3drm.createDeviceFromSurface(g, dd,ddsOffscreen);

Return Value:

Returns the Direct3dRMDevice object if successful; otherwise, null.

Parameter | Description
g | The globally unique identifier (GUID) used as the required device driver. If this parameter is null, the default device driver is used.
dd | The DirectDraw object that is the source of the DirectDraw surface.
DDsBack | The DirectDrawSurface object that represents the back buffer.

createFace

public Direct3dRMFace createFace();

Creates a Direct3dRMFace object.

Return Value:

Returns the Direct3dRMFace object if successful; otherwise, null.

createFrame

public Direct3dRMFrame createFrame(Direct3dRMFrame parent);

Creates a new child frame of the given parent frame.

Return Value:

Returns the Direct3dRMFrame object if successful; otherwise, null.

Parameter | Description
parent | A frame object that is to be the parent of the new frame.

Remarks:

The child frame inherits the motion attributes of its parent. For example, if the parent is moving with a given velocity, the child frame will also move with that velocity. Furthermore, if the parent is set rotating, the child frame will rotate about the origin of the parent. Frames that have no parent are called scenes. To create a scene, specify null as the parent. An application can create a frame with no parent, and then associate it with a parent frame later by using the addChild method.

See Also: com.ms.directX.Direct3dRMFrame

createLight

public Direct3dRMLight createLight(int t, int c);

Creates a new light source with the given type and color.

Return Value:

Returns the Direct3dRMLight object if successful; otherwise, null.

Parameter | Description
t | One value of the D3DRMLIGHT_ type.
c | Color of the light.

createLightRGB

public Direct3dRMLight createLightRGB(int lt, float vred, float vgreen,
        float vblue);

Creates a new light source with the given type and color.

Return Value:

Returns the Direct3dRMLight object if successful; otherwise, null.

Parameter | Description
lt | One value of D3DRMLIGHT_ type.
vred | The red component of the color.
vgreen | The green component of the color.
vblue | The blue component of the color.

createMaterial

public Direct3dRMMaterial createMaterial(float d);

Creates a material with the given specular property.

Return Value:

Returns the Direct3dRMMaterial object if successful; otherwise, null.

Parameter | Description
vPower | Sharpness of the reflected highlights, with a value of 5 giving a metallic look and higher values giving a more "plastic" look to the rendered surface.

createMesh

public Direct3dRMMesh createMesh();

Creates a new mesh object with no faces. The mesh is not visible until it is added to a frame.

Return Value:

Returns the Direct3dRMMesh object if successful; otherwise, null.

createMeshBuilder

public Direct3dRMMeshBuilder createMeshBuilder();

Creates a new mesh builder object.

Return Value:

Returns the Direct3dRMMeshBuilder object if successful; otherwise, null.

createShadow

public Direct3dRMVisual createShadow(Direct3dRMVisual v, Direct3dRMLight l,
        float px, float py, float pz, float nx, float ny, float nz);

Creates a shadow by using the specified visual and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, null.

Parameter | Description
v | The Direct3dRMVisual object that is casting the shadow.
l | The Direct3dRMLight object that is the light source.
px | The x component of the plane that the shadow is to be projected on.
py | The y component of the plane that the shadow is to be projected on.
pz | The z component of the plane that the shadow is to be projected on.
nx | The x component of the normal to the plane that the shadow is to be projected on.
ny | The y component of the normal to the plane that the shadow is to be projected on.
nz | The z component of the normal to the plane that the shadow is to be projected on.

createShadowFromFrame

public Direct3dRMVisual createShadowFromFrame(Direct3dRMFrame frame,
        Direct3dRMLight direct3dRMLight, float px, float py, float pz,
        float nx, float ny, float nz);

Creates a shadow by using the specified frame and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, null.

Parameter | Description
frame | The Direct3dRMFrame object that is casting the shadow.
l | The Direct3dRMLight object that is the light source.
px | The x component of the plane that the shadow is to be projected on.
py | The y component of the plane that the shadow is to be projected on.
pz | The z component of the plane that the shadow is to be projected on.
nx | The x component of the normal to the plane that the shadow is to be projected on.
ny | The y component of the normal to the plane that the shadow is to be projected on.
nz | The z component of the normal to the plane that the shadow is to be projected on.

createShadowFromMesh

public Direct3dRMVisual createShadowFromMesh(Direct3dRMMesh mesh,
        Direct3dRMLight direct3dRMLight, float px, float py, float pz,
        float nx, float ny, float nz);

Creates a shadow by using the specified mesh and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, null.

Parameter | Description
mesh | The Direct3dRMMesh object that is casting the shadow.
l | The Direct3dRMLight object that is the light source.
px | The x component of the plane that the shadow is to be projected on.
py | The y component of the plane that the shadow is to be projected on.
pz | The z component of the plane that the shadow is to be projected on.
nx | The x component of the normal to the plane that the shadow is to be projected on.
ny | The y component of the normal to the plane that the shadow is to be projected on.
nz | The z component of the normal to the plane that the shadow is to be projected on.

createShadowFromMeshBuilder

public Direct3dRMVisual createShadowFromMeshBuilder(
        Direct3dRMMeshBuilder mb, Direct3dRMLight l, float px, float py,
        float pz, float nx, float ny, float nz);

Creates a shadow by using the specified mesh builder and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, null.

Parameter | Description
v | The Direct3dRMMeshBuilder object that is casting the shadow.
l | The Direct3dRMLight object that is the light source.
px | The x component of the plane that the shadow is to be projected on.
py | The y component of the plane that the shadow is to be projected on.
pz | The z component of the plane that the shadow is to be projected on.
nx | The x component of the normal to the plane that the shadow is to be projected on.
ny | The y component of the normal to the plane that the shadow is to be projected on.
nz | The z component of the normal to the plane that the shadow is to be projected on.

createTexture

public Direct3dRMTexture createTexture(D3dRMImage image, byte[] buffer1,
        byte[] pal);

Creates a texture from an image in memory.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, null.

Parameter | Description
image | A Direct3dRMImage object describing the source for the texture.
buffer1 | The image buffer.
pal | The image palette.

Remarks:

The memory associated with the image is used each time the texture is rendered (rather than the memory being copied into Direct3dRM's buffers). This allows the image to be used both as a rendering target and as a texture.

createTextureFromSurface

public Direct3dRMTexture createTextureFromSurface(DirectDrawSurface ddS);

Creates a texture from a specified DirectDraw surface.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, null.

Parameter | Description
ddS | The DirectDrawSurface object containing the texture.

createUserVisual

public Direct3dRMUserVisual createUserVisual(IUserVisualCallback fn,
        IUnknown Arg);

Creates an application-defined visual object, which can then be added to a scene and rendered by using an application-defined handler.

Return Value:

Returns the Direct3dRMUserVisual object if successful; otherwise, null.

Parameter | Description
fn | A callback interface containing the application-defined callback function.
Arg | Application-defined data passed to the callback function.

createViewport

public Direct3dRMViewport createViewport(Direct3dRMDevice dev,
        Direct3dRMFrame fr, int l, int t, int w, int h);

Creates a viewport on a device with device coordinates (xPos, yPos) to (xPos + width, yPos + height).

Return Value:

Returns the Direct3dRMViewport object if successful; otherwise, null.

Parameter | Description
dev | The device that the viewport is to be created on.
fr | The frame that describes the position and direction of the view.
l | The x coordinate of the upper-left corner of the viewport, in device coordinates.
t | The y coordinate of the upper-left corner of the viewport, in device coordinates.
w | Width of the viewport, in device coordinates.
h | Height of the viewport, in device coordinates.

Remarks:

The viewport displays objects in the scene that contains the camera, with the view direction and up vector taken from the camera.

createWrap

public Direct3dRMWrap createWrap(int t, Direct3dRMFrame f, float ox,
        float oy, float oz, float dx, float dy, float dz, float ux,
        float uy, float uz, float ou, float ov, float su, float sv);

Creates a wrapping function that can be used to assign texture coordinates to faces and meshes. The vector [ox oy oz] gives the origin of the wrap, [dx dy dz] gives its z-axis, and [ux uy uz] gives its y-axis. The 2D vectors [ou ov] and [su sv] give an origin and scale factor in the texture applied to the result of the wrapping function.

Return Value:

Returns the Direct3dRMWrap object if successful; otherwise, null.

Parameter | Description
t | One value of the D3DRMWRAP_ type.
f | The reference frame for the wrap.
ox | The x component of the wrap's origin.
oy | The y component of the wrap's origin.
oz | The z component of the wrap's origin
dx | The x component of the z-axis of the wrap.
dy | The y component of the z-axis of the wrap.
dz | The z component of the z-axis of the wrap.
ux | The x component of the y-axis of the wrap.
uy | The y component of the y-axis of the wrap.
uz | The z component of the y-axis of the wrap.
ou | Origin in the texture.
ov | Origin in the texture.
su | Scale factor in the texture.
sv | Scale factor in the texture.

enumerateObjects

public void enumerateObjects(IEnumerateObjectsCallback fn, IUnknown pArgs);

Calls the callback function specified by the fn parameter on each of the active Direct3dRM objects.

Return Value:

No return value.

Parameter | Description
fn | A callback interface that contains an application-defined callback function to be called with each Direct3dRMObject object and the application-defined argument.
pArgs | Application-defined data passed to the callback function.

getDevices

public Direct3dRMDeviceArray getDevices();

Returns all the Direct3dRM devices that have been created in the system.

Return Value:

Returns the Direct3dRMDeviceArray object if successful; otherwise, null.

getNamedObject

public Direct3dRMObject getNamedObject(String name);

Retrieves a Direct3dRMObject object, given its name.

Return Value:

Returns the Direct3dRMObject object if successful; otherwise, null.

Parameter | Description
name | The name of the object to be searched for.

getSearchPath

public String getSearchPath();

Returns the current file search path.

Return Value:

Returns a string specifying the search path.

See Also: setSearchPath

loadFromFileByPos

public void loadFromFileByPos(String fnam, int[] id, _Guid g, int cnt,
        int options, ILoadCallback fn1, int[] arg1,
        ILoadTextureCallback fn2, int[] arg2, Direct3dRMFrame f);

Loads an object. This method enables you to inspect an X file and decide what object to load, using the ILoadCallback interface.

The following example shows how this method can be used.

//Indicate what type of objects will be sent to the callback.

IID_IDirect3DRMFrame.set(0xeb16cb03, (short)0xd271,(short) 0x11ce,
 (byte)0xac, (byte)0x48, (byte)0x0,(byte) 0x0,(byte) 0xc0, (byte)0x38,
 (byte)0x25, (byte)0xa1);
IID_IDirect3DRMMeshBuilder.set(0xa3a80d02, (short)0x6e12, (short)0x11cf,
 (byte)0xac, (byte)0x4a, (byte)0x0, (byte)0x0, (byte)0xc0, (byte)0x38,
 (byte)0x25, (byte)0xa1);
IID_IDirect3DRMAnimationSet.set(0xeb16cb0e, (short)0xd271,(short) 0x11ce,
 (byte)0xac, (byte)0x48, (byte)0x0, (byte)0x0, (byte)0xc0, (byte)0x38,
 (byte)0x25, (byte)0xa1);

// If you use 0, you will retrieve all objects.
d3drm.loadFromFileByPos(sFile,
    null, IID_IDirect3DRMFrame, 1,
    D3DRM_LOADFROMFILE, this,
    null, this,
    null, f_env);

public void callbackLoad(Direct3dRMObject obj, _Guid id, IUnknown Arg)
{
    String sType=obj.getClassName();
    if (sType.equals("Frame"))
    {
         Direct3dRMFrame f=obj.getd3drmFrame();
         f_env.addChild(f);
    }
    if (sType.equals("Builder"))
    {
         Direct3dRMMeshBuilder m=obj.getd3drmMeshBuilder();
         System.out.println("OK to convert");
         f_env.addVisualMeshBuilder(m);
    }
}
// other callbacks ...

Return Value:

No return value.

Parameter | Description
fnam | The name of the file that the object is loaded from.
id | The object position. The value of the first variable in the array gives the object's order in the file.
g | The interface identifier to be loaded.
cnt | The number of identifiers specified in the g parameter.
options | A load options type.
fn1 | The callback interface that contains a load callback function called when the system reads the specified object.
arg1 | Application-defined data passed to the load callback function.
fn2 | The callback interface that contains a load texture callback function called to load any textures used by an object that require special formatting. This parameter can be null.
arg2 | Application-defined data passed to the load texture callback function.
f | A parent frame. This information is useful when loading Direct3dRMAnimationSet or Direct3dRMFrame objects because otherwise, these objects would be created with a null parent. This value can be null.

loadTexture

public Direct3dRMTexture loadTexture(String name);

Loads a texture from the specified file. This texture can have 8, 24, or 32 bits-per-pixel, and it should be in either the Windows bitmap (.bmp) or Portable Pixmap (.ppm) P6 format.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, null.

Parameter | Description
name | The name of the required .bmp or .ppm file.

loadTextureFromResource

public Direct3dRMTexture loadTextureFromResource(int hnd);

Loads a texture from a specified resource. Because it is difficult to obtain resource handles, this method is rarely used in Java.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, null.

Parameter | Description
hnd | Handle of the resource.

setDefaultTextureColors

public void setDefaultTextureColors(int ds);

Sets the default colors to be used for a Direct3dRMTexture object.

Return Value:

No return value.

Parameter | Description
ds | Number of colors.

Remarks:

This method affects texture colors only when it is called before the createTexture method; it has no effect on textures that have already been created.

setDefaultTextureShades

public void setDefaultTextureShades(int ds);

Sets the default shades to be used for an Direct3dRMTexture object.

Return Value:

No return value.

Parameter | Description
ds | The number of shades.

Remarks:

This method affects texture shades only when it is called before the createTexture method; it has no effect on textures that have already been created.

setSearchPath

public void setSearchPath(String name);

Sets the current file search path from a list of directories.

Return Value:

No return value.

Parameter | Description
name | A string specifying the path to set as the current search path.

Remarks:

The default search path is taken from the value of the D3DPATH environment variable. If this is not set, the search path will be empty. When opening a file, the system first looks for the file in the current working directory, and then checks every directory in the search path.

See Also: getSearchPath

tick

public void tick(float val);

Performs the Direct3dRM system heartbeat. When this method is called, the positions of all moving frames are updated according to their current motion attributes, the scene is rendered to the current device, and relevant callback functions are called at their appropriate times. Control is returned when the rendering cycle is complete.

Return Value:

No return value.

Parameter | Description
val | The velocity and rotation step for the setRotation and setVelocity methods.

Remarks:

You can implement this method by using other Retained-Mode methods to allow more flexibility in rendering a scene.

vectorAdd

public void vectorAdd(D3dVector lpd, D3dVector lps1, D3dVector lps2);

Calculates the sum of two vectors.

Return Value:

No return value.

Parameter | Description
lpd | A D3dVector object that receives the sum of lps1 and lps2.
lps1 | A D3dVector object that contains a vector.
lps2 | A D3dVector object that contains a vector.

vectorCrossProduct

public void vectorCrossProduct(D3dvector lpd, D3dvector lps1,
        D3dvector lps2);

Calculates the cross-product of two vectors.

Return Value:

No return value.

Parameter | Description
lpd | A D3dVector object that receives the cross product.
lps1 | A D3dVector object that contains a vector.
lps2 | A D3dVector object that contains a vector.

vectorDotProduct

public float vectorDotProduct(D3dVector lps1, D3dVector lps2);

Calculates the dot-product of two vectors.

Return Value:

Returns the result of the operation.

Parameter | Description
lps1 | A D3dVector object that contains a vector.
lps2 | A D3dVector object that contains a vector.

vectorModulus

public float vectorModulus(D3dVector d);

Calculates the modulus of a vector.

Return Value:

Returns a float that is the remainder of the modulus operation.

Parameter | Description
d | The vector to mod.

vectorNormalise

public void vectorNormalise(D3dvector d);

Normalizes a vector.

Return Value:

No return value.

Parameter | Description
d | A D3dVector object that contains the vector to normalize. This object also receives the normalized vector.

vectorRandom

public void vectorRandom(D3dVector d);

Randomizes a vector.

Return Value:

No return value.

Parameter | Description
d | A D3dVector object that contains the vector to randomize. This object also receives the randomized vector.

vectorReflect

public void vectorReflect(D3dVector lpd, D3dVector lpRay, D3dVector lpNorm);

Reflects a vector, given a vector ray and a vector normal.

Return Value:

No return value.

Parameter | Description
lpd | The resulting D3dVector from the operation.
lpRay | A D3dVector ray.
lpNorm | A D3dVector normal.

vectorRotate

public void vectorRotate(D3dVector lpr, D3dVector lpv, D3dVector lpaxis,
        float theta);

Rotates a vector, given a ray, vector, axis, and amount to rotate.

Return Value:

No return value.

Parameter | Description
lpr | A D3dVector ray.
lpv | A D3dVector vector.
lpaxis | A D3dVector axis.
theta | The amount to rotate the vector (in radians).

vectorScale

public void vectorScale(D3dVector lpd, D3dVector lps, float factor);

Scales one vector to another by a specified factor.

Parameter | Description
lpd | A D3dVector object that receives the result of the scaling operation.
lps | A D3dVector object that contains the source vector.
The | factor to scale lps by.

vectorSubtract

public void vectorSubtract(D3dVector lpd, D3dVector lps1, D3dVector lps2);

Subtracts one vector from another.

Return Value:

No return value.

Parameter | Description
lpd | A D3dVector object that receives the result of the subtraction.
lps1 | A D3dVector object that contains a vector.
lps2 | A D3dVector object that contains a vector.


Class Direct3dRMAnimation

public class Direct3dRMAnimation implements
            IDirect3dRMAnimation
{
  // Methods
  public void addPositionKey(float time, float x, float y, float z);
  public void addRotateKey(float time, D3dRMQuaternion q);
  public void addScaleKey(float time, float x, float y, float z);
  public void deleteKey(float time);
  public int getOptions();
  public void setFrame(Direct3dRMFrame frame);
  public void setOptions(int flags);
  public void setTime(float time);
}

Applications use the methods of the Direct3dRMAnimation class to animate the position, orientation, and scaling of visuals, lights, and viewports.

The Direct3dRMAnimation class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

Methods

addPositionKey

public void addPositionKey(float time, float x, float y, float z);

Adds a position key to the animation.

Return Value:

No return value.

Parameter | Description
time | The time in the animation to store the position key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation, whose last key has an time value of 99.
x | The x component of the position.
y | The y component of the position.
z | The z component of the position.

Remarks:

The transformation applied by this method is a translation.

See Also: deleteKey

addRotateKey

public void addRotateKey(float time, D3dRMQuaternion q);

Adds a rotate key to the animation.

Return Value:

No return value.

Parameter | Description
time | The time in the animation to store the rotate key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation, whose last key has an time value of 99.
q | D3dRMQuaternion representing the rotation.

Remarks:

This method applies a rotation transformation.

See Also: deleteKey

addScaleKey

public void addScaleKey(float time, float x, float y, float z);

Adds a scale key to the animation.

Return Value:

No return value.

Parameter | Description
time | The time in the animation to store the scale key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation, whose last key has an time value of 99.
x | The x component of the scale factor.
y | The y component of the scale factor.
z | The z component of the scale factor.

Remarks:

This method applies a scaling transformation.

See Also: deleteKey

deleteKey

public void deleteKey(float time);

Removes a key from an animation.

Return Value:

No return value.

Parameter | Description
time | The time identifying the key that will be removed from the animation.

getOptions

public int getOptions();

Retrieves animation options.

Return Value:

Returns the value of an animation option type describing the animation options.

See Also: setOptions

setFrame

public void setFrame(Direct3dRMFrame frame);

Sets the frame for the animation.

Return Value:

No return value.

Parameter | Description
frame | The Direct3dRMFrame object to set for the animation.

setOptions

public void setOptions(int flags);

Sets the animation options.

Return Value:

No return value.

Parameter | Description
flags | The value of animation option type describing the animation options.

See Also: getOptions

setTime

public void setTime(float time);

Sets the current time for this animation.

Return Value:

No return value.

Parameter | Description
time | The new current time for the animation. The time units are arbitrary and zero-based; a key, whose time value is 49, occurs exactly in the middle of an animation, whose last key has an time value of 99.


Class Direct3dRMAnimationSet

public class Direct3dRMAnimationSet implements
            IDirect3dRMAnimationSet
{
  // Methods
  public void addAnimation(Direct3dRMAnimation aid);
  public void deleteAnimation(Direct3dRMAnimation aid);
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser,
        Direct3dRMFrame f);
  public void setTime(float time);
}

Applications use the methods of the Direct3dRMAnimationSet class to group Direct3dRMAnimation objects together, which can simplify the playback of complex animation sequences.

The Direct3dRMAnimationSet class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMAnimationSet object is obtained by calling the createAnimationSet method.

Methods

addAnimation

public void addAnimation(Direct3dRMAnimation aid);

Adds an animation to the animation set.

Return Value:

No return value.

Parameter | Description
aid | The Direct3dRMAnimation object to be added to the animation set.

deleteAnimation

public void deleteAnimation(Direct3dRMAnimation aid);

Removes a previously added animation from the animation set.

Return Value:

No return value.

Parameter | Description
aid | The Direct3dRMAnimation object to be removed from the animation set.

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser, Direct3dRMFrame f);

Loads an animation set.

Return Value:

No return value.

Parameter | Description
filename | The name of the file that the object is to be loaded from.
position | The position in the file to be loaded from. The value gives the object's order in the file. This parameter can be null.
flags | A load options type.
c | The callback interface that contains the load texture callback function called to load any textures used by the object that require special formatting. This parameter can be null.
pUser | Application-defined data passed to the load texture callback function.
f | The parent Direct3dRMFrame object. This prevents the frames referred to by the animation set from being created with a null parent.

Remarks:

By default, this method loads the first animation set in the file specified by the objSource parameter.

setTime

public void setTime(float time);

Sets the time for the animation set.

Return Value:

No return value.

Parameter | Description
time | The new time.


Class Direct3dRMArray

public class Direct3dRMArray implements IDirect3dRMArray
{
  // Methods
  public int getSize();
}

The Direct3dRMArray class organizes groups of objects. Applications typically use array objects that are subsidiary to this class (rather than use this class directly).

The class supports the getSize method.

Methods

getSize

public int getSize();

Retrieves the number of objects associated with this array object.

Return Value:

Returns the number of objects.


Class Direct3dRMDevice

public class Direct3dRMDevice implements IDirect3dRMDevice
{
  // Methods
  public void addUpdateCallback(IDeviceUpdateCallback fn,
        IUnknown args);
  public void deleteUpdateCallback(IDeviceUpdateCallback fn,
        IUnknown args);
  public int getBufferCount();
  public int getColorModel();
  public Direct3dRMWinDevice getd3drmWinDevice();
  public Direct3dDevice getDirect3DDevice();
  public int getDither();
  public int getHeight();
  public int getQuality();
  public int getShades();
  public int getTextureQuality();
  public int getTrianglesDrawn();
  public Direct3dRMViewportArray getViewports();
  public int getWidth();
  public int getWireframeOptions();
  public void init(int width, int height);
  public void setBufferCount(int count);
  public void setDither(int dith);
  public void setQuality(int q);
  public void setShades(int s);
  public void setTextureQuality(int d);
  public void update();
}

Applications use the methods of the Direct3dRMDevice class to interact with the output device.

The Direct3dRMDevice class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMDevice object is obtained by calling the createDevice method.

Methods

addUpdateCallback

public void addUpdateCallback(IDeviceUpdateCallback fn, IUnknown args);

Adds a callback function that alerts the application when a change occurs to the device. The system calls this callback function whenever the application calls the update method.

Return Value:

No return value.

Parameter | Description
fn | The callback interface that contains an application-defined callback function.
args | Private data to be passed to the update callback function.

See Also: deleteUpdateCallback, update

deleteUpdateCallback

public void deleteUpdateCallback(IDeviceUpdateCallback fn, IUnknown args);

Removes an update callback function that was added by calling the addUpdateCallback method.

Return Value:

No return value.

Parameter | Description
fn | The callback interface that contains an application-defined callback function.
args | Private data that was passed to the update callback function.

See Also: addUpdateCallback, update

getBufferCount

public int getBufferCount();

Retrieves the value set in a call to the setBufferCount method.

Return Value:

Returns the number of buffers—one for single-buffering, two for double-buffering, and so on.

getColorModel

public int getColorModel();

Retrieves the color model of a device.

Return Value:

Returns a value of D3DCOLOR_ type that describes the Direct3D color model (RGB or monochrome).

getd3drmWinDevice

public Direct3dRMWinDevice getd3drmWinDevice();

Retrieves the Microsoft® Windows® device associated with this Retained-Mode device.

Return Value:

Returns the Direct3dRMWinDevice object if successful; otherwise, returns null.

getDirect3DDevice

public Direct3dDevice getDirect3DDevice();

Retrieves an Immediate-Mode device.

Return Value:

Returns the Direct3dDevice object if successful; otherwise, null.

getDither

public int getDither();

Retrieves the dither flag for the device.

Return Value:

Returns true if the dither flag is set; otherwise, returns false.

See Also: setDither

getHeight

public int getHeight();

Retrieves the height, in pixels, of a device. This method is a convenience function.

Return Value:

Returns the height.

getQuality

public int getQuality();

Retrieves the rendering quality for the device.

Return Value:

Returns one or more values of the render quality type.

See Also: setQuality

getShades

public int getShades();

Retrieves the number of shades in a ramp of colors used for shading.

Return Value:

Returns the number of shades.

See Also: setShades

getTextureQuality

public int getTextureQuality();

Retrieves the current texture quality parameter for the device. Texture quality is relevant only for an RGB device.

Return Value:

Returns a value of texture quality type.

See Also: setTextureQuality

getTrianglesDrawn

public int getTrianglesDrawn();

Retrieves the number of triangles drawn to a device since its creation. This method is a convenience function.

Return Value:

Returns the number of triangles.

Remarks:

The number of triangles includes those that were passed to the renderer, but were not drawn because they were backfacing. The number does not include triangles that were rejected for lying outside of the viewing frustum.

getViewports

public Direct3dRMViewportArray getViewports();

Constructs a Direct3dRMViewportArray object that represents the viewports currently constructed from the device.

Return Value:

Returns the Direct3dRMViewportArray object if successful; otherwise, returns null.

getWidth

public int getWidth();

Retrieves the width, in pixels, of a device. This method is a convenience function.

Return Value:

Returns the width.

getWireframeOptions

public int getWireframeOptions();

Retrieves the wireframe options of a given device.

Return Value:

Returns a combination of values of D3DRMWIREFRAME_ type.

init

public void init(int width, int height);

Not implemented on the Windows platform.

setBufferCount

public void setBufferCount(int count);

Sets the number of buffers currently being used by the application.

Return Value:

No return value.

Parameter | Description
count | Specifies the number of buffers— one for single-buffering, two for double-buffering, and so on. The default value is 1, which is correct only for single-buffered window operation.

Remarks:

An application that employs double-buffering or triple-buffering must use this method to inform the system of how many buffers it is using so that the system can calculate how much of the window to clear and update on each frame.

See Also: getBufferCount

setDither

public void setDither(int dith);

Sets the dither flag for the device.

Return Value:

No return value.

Parameter | Description
dith | The new dithering mode for the device; the value can be true or false.

Remarks:

By default, a device's dither flag is initially set to true.

See Also: getDither

setQuality

public void setQuality(int q);

Sets the rendering quality of a device

Return Value:

No return value.

Parameter | Description
q | One or more values of the render quality type.

Remarks:

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device. Each mesh can have its own quality, but the maximum quality available for a mesh is that of the device. Different devices can have different qualities. For example, previewing devices usually have a lower quality, while devices used for final viewing usually have a higher quality.

By default, a device's rendering quality is initially set to D3DRMRENDER_FLAT.

See Also: getQuality

setShades

public void setShades(int s);

Sets the number of shades in a ramp of colors used for shading.

Return Value:

No return value.

Parameter | Description
s | The new number of shades. This parameter must be a power of 2.

Remarks:

By default, a device's number of shades is initially set to 32.

See Also: getShades

setTextureQuality

public void setTextureQuality(int d);

Sets the texture quality for the device.

Return Value:

No return value.

Parameter | Description
d | One value of the texture quality type.

Remarks:

By default, a device's texture quality is initially set to D3DRMTEXTURE_NEAREST.

See Also: getTextureQuality

update

public void update();

Copies the image that has been rendered to the display and provides a heartbeat function to the device driver.

Return Value:

No return value.

Remarks:

Each call to this method causes the system to call an application-defined callback function. To add a callback function, use the addUpdateCallback method.

See Also: addUpdateCallback, com.ms.directX.Direct3dRMViewport.forceUpdate


Class Direct3dRMDeviceArray

public class Direct3dRMDeviceArray implements
            IDirect3dRMDeviceArray
{
  // Methods
  public Direct3dRMDevice getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMDeviceArray class to organize device objects.

The Direct3dRMDeviceArray object is obtained by calling the getDevices method.

Methods

getElement

public Direct3dRMDevice getElement(int index);

Retrieves one of the Direct3dRMDevice objects associated with this object.

Return Value:

Returns the Direct3dRMDevice object if successful; otherwise, returns null.

Parameter | Description
index | Identifies the object to return. Must be a value in the range 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Retrieves the number of Direct3dRMDevice objects associated with this object.

Return Value:

Returns the number of objects.


Class Direct3dRMFace

public class Direct3dRMFace implements IDirect3dRMFace
{
  // Methods
  public void addVertex(float x, float y, float z);
  public void addVertexAndNormalIndexed(int vertex, int normal);
  public int getColor();
  public Direct3dRMMaterial getMaterial();
  public void getNormal(D3dVector val);
  public Direct3dRMTexture getTexture();
  public int getTextureCoordinateIndex(int which);
  public void getTextureCoordinates(int vertex, float[] u,
        float[] v);
  public void getTextureTopology(int[] u, int[] v);
  public void getVertex(int idx, D3dVector vert, D3dVector norm);
  public int getVertexCount();
  public int getVertexIndex(int which);
  public void getVertices(int vCount, D3dVector[] v, D3dVector[] n);
  public void getVerticesAsFloats(int[] vertex_cnt,
        D3dVector coord, D3dVector normals);
  public void getVerticesSize(int[] v_cnt);
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setMaterial(Direct3dRMMaterial ref);
  public void setTexture(Direct3dRMTexture ref);
  public void setTextureCoordinates(int vertex, float u, float v);
  public void setTextureTopology(int wrap_u, int wrap_v);
}

Applications use the methods of the Direct3dRMFace class to interact with a single polygon in a mesh.

The Direct3dRMFace class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMFace object is obtained by calling the createFace method.

Methods

addVertex

public void addVertex(float x, float y, float z);

Adds a vertex to a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
x | The x component of the position of the new vertex.
y | The y component of the position of the new vertex.
z | The z component of the position of the new vertex.

addVertexAndNormalIndexed

public void addVertexAndNormalIndexed(int vertex, int normal);

Adds a vertex and a normal to a Direct3dRMFace object by using an index for the vertex and an index for the normal in the containing mesh builder. The face, vertex, and normal must already be part of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
vertex | Index of the vertex to add.
normal | Index of the normal to add.

getColor

public int getColor();

Retrieves the color of a Direct3dRMFace object.

Return Value:

Returns the color.

See Also: setColor

getMaterial

public Direct3dRMMaterial getMaterial();

Retrieves the material of a Direct3dRMFace object.

Return Value:

Returns the Direct3dRMMaterial object if successful; otherwise, returns null.

See Also: setMaterial

getNormal

public void getNormal(D3dVector val);

Retrieves the normal vector of a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
val | The D3dVector object that receives the normal vector of the face.

getTexture

public Direct3dRMTexture getTexture();

Retrieves the Direct3dRMTexture object applied to a Direct3dRMFace object.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, returns null.

See Also: setTexture

getTextureCoordinateIndex

public int getTextureCoordinateIndex(int which);

Retrieves the index of the vertex for texture coordinates in the face's mesh. This index corresponds to the index specified in the which parameter.

Return Value:

Returns the index.

Parameter | Description
which | The index within the face of the vertex.

getTextureCoordinates

public void getTextureCoordinates(int vertex, float[] u, float[] v);

Retrieves the texture coordinates of a vertex in a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
vertex | The index of the vertex.
u | The array variables that receive the texture u coordinates of the vertex.
v | The array variables that receive the texture v coordinates of the vertex.

getTextureTopology

public void getTextureTopology(int[] u, int[] v);

Retrieves the texture topology of a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
u | The array variables that are set or cleared, depending on how the cylindrical wrapping flags are set for the face.
v | The array variables that are set or cleared, depending on how the cylindrical wrapping flags are set for the face.

See Also: setTextureTopology

getVertex

public void getVertex(int idx, D3dVector vert, D3dVector norm);

Retrieves the position and normal of a vertex in a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex.
vert | The D3dVector objects that receive the position of the vertex.
norm | The D3dVector objects that receive the normal of the vertex.

getVertexCount

public int getVertexCount();

Retrieves the number of vertices in a Direct3dRMFace object.

Return Value:

Returns the number of vertices.

getVertexIndex

public int getVertexIndex(int which);

Retrieves the index of the vertex in the face's mesh. This index corresponds to the index specified in the which parameter.

Return Value:

Returns the index.

Parameter | Description
which | The index within the face of the vertex.

getVertices

public void getVertices(int vCount, D3dVector[] v, D3dVector[] n);

Retrieves the position and normal vector of each vertex in a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
vCount | The number of vectors.
v | The D3dVector array that receives the vertices.
n | The D3dVector array that receives the normals.

getVerticesAsFloats

public void getVerticesAsFloats(int[] vertex_cnt, D3dVector coord,
        D3dVector normals);

Retrieves the position and normal vector of each vertex in a Direct3dRMFace object (as floats).

Return Value:

No return value.

Parameter | Description
vertex_cnt | The array variable that receives the number of floats of the vertices.
coord | The D3dVector objects that receive the positions vectors of the vertices.
normals | The D3dVector objects that receive the normal vectors of the vertices.

getVerticesSize

public void getVerticesSize(int[] v_cnt);

Retrieves the number of vertices associated with a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
v_cnt | The array variable that receives the number of vertices.

See Also: getVertices

setColor

public void setColor(int c);

Sets a Direct3dRMFace object to a given color.

Return Value:

No return value.

Parameter | Description
c | The color to set.

See Also: getColor

setColorRGB

public void setColorRGB(float r, float g, float b);

Sets a Direct3dRMFace object to a given color.

Return Value:

No return value.

Parameter | Description
r | The red component of the color.
g | The green component of the color.
b | The blue component of the color.

setMaterial

public void setMaterial(Direct3dRMMaterial ref);

Sets the material of a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMMaterial object to set.

See Also: getMaterial

setTexture

public void setTexture(Direct3dRMTexture ref);

Sets the texture of a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMTexture object to set.

See Also: getTexture

setTextureCoordinates

public void setTextureCoordinates(int vertex, float u, float v);

Sets the texture coordinates of a specified vertex in a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
vertex | Index of the vertex to be set. For example, if the face were a triangle, the possible vertex indices would be 0, 1, and 2.
u | The texture u coordinate to assign to the specified vertex.
v | The texture v coordinate to assign to the specified vertex.

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);

Sets the texture topology of a Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
wrap_u | Specifies whether the texture has a cylindrical topology in the u dimension.
wrap_v | Specifies whether the texture has a cylindrical topology in the v dimension.

See Also: getTextureTopology


Class Direct3dRMFaceArray

public class Direct3dRMFaceArray implements
            IDirect3dRMFaceArray
{
  // Methods
  public Direct3dRMFace getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMFaceArray class to organize faces in a mesh.

The Direct3dRMFaceArray object is obtained by calling the getFaces method.

Methods

getElement

public Direct3dRMFace getElement(int index);

Returns one of the Direct3dRMFace objects associated with this object.

Return Value:

Returns the Direct3dRMFace object if successful; otherwise, returns null.

Parameter | Description
index | Identifies the object to return. Must be a value in the range of 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Returns the number of Direct3dRMFace objects associated with this object.

Return Value:

Returns the number of objects.


Class Direct3dRMFrame

public class Direct3dRMFrame implements IDirect3dRMFrame
{
  // Methods
  public void addChild(Direct3dRMFrame child);
  public void addLight(Direct3dRMLight val);
  public void addMoveCallback(IFrameMoveCallback fmC,
        IUnknown args);
  public void addRotation(int typ, float x, float y, float z, float
        theta);
  public void addScale(int typ, float sx, float sy, float sz);
  public void addTransform(int t, float[] val);
  public void addTranslation(int t, float x, float y, float z);
  public void addVisual(Direct3dRMVisual v);
  public void addVisualFrame(Direct3dRMFrame v);
  public void addVisualMesh(Direct3dRMMesh v);
  public void addVisualMeshBuilder(Direct3dRMMeshBuilder v);
  public void addVisualShadow(Direct3dRMShadow v);
  public void addVisualTexture(Direct3dRMTexture v);
  public void addVisualUserVisual(Direct3dRMUserVisual v);
  public void deleteChild(Direct3dRMFrame c);
  public void deleteLight(Direct3dRMLight l);
  public void deleteMoveCallback(IFrameMoveCallback fn,
        IUnknown args);
  public void deleteVisual(Direct3dRMVisual v);
  public void deleteVisualFrame(Direct3dRMFrame v);
  public void deleteVisualMesh(Direct3dRMMesh v);
  public void deleteVisualMeshBuilder(Direct3dRMMeshBuilder v);
  public void deleteVisualShadow(Direct3dRMShadow v);
  public void deleteVisualTexture(Direct3dRMTexture v);
  public void deleteVisualUserVisual(Direct3dRMUserVisual v);
  public Direct3dRMFrameArray getChildren();
  public int getColor();
  public Direct3dRMLightArray getLights();
  public int getMaterialMode();
  public void getOrientation(Direct3dRMFrame ref, D3dVector dir,
        D3dVector up);
  public Direct3dRMFrame getParent();
  public void getPosition(Direct3dRMFrame ref, D3dVector position);
  public void getRotation(Direct3dRMFrame ref, D3dVector axis,
        float[] theta);
  public Direct3dRMFrame getScene();
  public int getSceneBackground();
  public DirectDrawSurface getSceneBackgroundDepth();
  public int getSceneFogColor();
  public int getSceneFogEnable();
  public int getSceneFogMode();
  public void getSceneFogParams(float[] start, float[] end, float[]
        density);
  public int getSortMode();
  public Direct3dRMTexture getTexture();
  public void getTextureTopology(int[] u, int[] v);
  public void getTransform(float[] val);
  public void getVelocity(Direct3dRMFrame ref, D3dVector vel,
        int rotation);
  public Direct3dRMVisualArray getVisuals();
  public int getZbufferMode();
  public void inverseTransform(D3dVector d, D3dVector s);
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser);
  public void lookAt(Direct3dRMFrame tgt, Direct3dRMFrame ref,
        int val);
  public void move(float delta);
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setMaterialMode(int val);
  public void setOrientation(Direct3dRMFrame reference, float dx,
        float dy, float dz, float ux, float uy, float uz);
  public void setPosition(Direct3dRMFrame reference, float x, float
        y, float z);
  public void setRotation(Direct3dRMFrame reference, float x, float
        y, float z, float theta);
  public void setSceneBackground(int c);
  public void setSceneBackgroundDepth(DirectDrawSurface s);
  public void setSceneBackgroundImage(Direct3dRMTexture i);
  public void setSceneBackgroundRGB(float r, float g, float b);
  public void setSceneFogColor(int c);
  public void setSceneFogEnable(int enable);
  public void setSceneFogMode(int c);
  public void setSceneFogParams(float s, float e, float d);
  public void setSortMode(int val);
  public void setTexture(Direct3dRMTexture t);
  public void setTextureTopology(int wrap_u, int wrap_v);
  public void setVelocity(Direct3dRMFrame reference, float x, float
        y, float z, int with_rotation);
  public void setZbufferMode(int val);
  public void transform(D3dVector d, D3dVector s);
}

Applications use the methods of the Direct3dRMFrame class to interact with frames—an object's frame of reference.

The Direct3dRMFrame class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMFrame object is obtained by calling the createFrame method.

Methods

addChild

public void addChild(Direct3dRMFrame child);

Adds a child frame to a frame hierarchy.

Return Value:

No return value.

Parameter | Description
child | The Direct3dRMFrame object that will be added as a child.

Remarks:

If the frame being added as a child already has a parent, this method removes it from its previous parent before adding it to the new parent.

To preserve an object's transformation, use the getTransform method to retrieve the object's transformation before using the addChild method. Then, reapply the transformation after the frame is added.

addLight

public void addLight(Direct3dRMLight val);

Adds a light to a frame.

Return Value:

No return value.

Parameter | Description
val | The Direct3dRMLight object to be added to the frame.

addMoveCallback

public void addMoveCallback(IFrameMoveCallback fmC, IUnknown args);

Adds a callback function for special movement processing.

Return Value:

No return value.

Parameter | Description
fmC | The callback interface that contains an application-defined callback function.
args | Application-defined data to be passed to the callback function.

See Also: move, deleteMoveCallback

addRotation

public void addRotation(int typ, float x, float y, float z, float theta);

Adds a rotation about (x, y, z) by the number of radians specified in theta.

Return Value:

No return value.

Parameter | Description
typ | A value of combine type that specifies how to combine the new rotation with any current frame transformation.
x | The axis about which to rotate.
y | The axis about which to rotate.
z | The axis about which to rotate.
theta | The angle of rotation, in radians.

Remarks:

The specified rotation changes the matrix only for the frame identified by this object. This method changes the objects in the frame only once, unlike setRotation, which changes the matrix with every render tick.

addScale

public void addScale(int typ, float sx, float sy, float sz);

Scales a frame's local transformation by (sx, sy, sz).

Return Value:

No return value.

Parameter | Description
typ | The value of combine type that specifies how to combine the new scale with any current frame transformation.
sz | The scale factor in the x direction.
sy | The scale factor in the y direction.
sz | The scale factor in the z direction.

Remarks:

The specified transformation changes the matrix only for the frame identified by this object.

addTransform

public void addTransform(int t, float[] val);

Transforms the local coordinates of the frame by the given affine transformation according to the value of the t parameter.

Return Value:

No return value.

Parameter | Description
t | The value of combine type that specifies how to combine the new transformation with any current transformation.
val | The array variable that defines the transformation matrix to be combined.

Remarks:

Although a 4-by-4 matrix is given, the last column must be the transpose of [0 0 0 1] for the transformation to be affine.

The specified transformation changes the matrix only for the frame identified by this Direct3dRMFrame object.

addTranslation

public void addTranslation(int t, float x, float y, float z);

Adds a translation by (x, y, z) to a frame's local coordinate system.

Return Value:

No return value.

Parameter | Description
t | The value of combine type that specifies how to combine the new translation with any current translation.
x | The position change in the x direction.
y | The position change in the y direction.
z | The position change in the z direction.

Remarks:

The specified translation changes the matrix only for the frame identified by this object.

addVisual

public void addVisual(Direct3dRMVisual v);

Adds a visual object to a frame.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMVisual object to be added to the frame.

Remarks:

Visual objects include meshes and textures. When a visual object is added to a frame, it becomes visible if the frame is in view. The visual object is referenced by the frame.

addVisualFrame

public void addVisualFrame(Direct3dRMFrame v);

Adds a visual frame to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMFrame object to be added.

addVisualMesh

public void addVisualMesh(Direct3dRMMesh v);

Adds a visual mesh to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMMesh object to be added.

addVisualMeshBuilder

public void addVisualMeshBuilder(Direct3dRMMeshBuilder v);

Adds a mesh builder object to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMMeshBuilder object to be added.

addVisualShadow

public void addVisualShadow(Direct3dRMShadow v);

Adds a shadow object to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMShadow object to be added.

addVisualTexture

public void addVisualTexture(Direct3dRMTexture v);

Adds a texture object to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMTexture object to be added.

addVisualUserVisual

public void addVisualUserVisual(Direct3dRMUserVisual v);

Adds a user visual object to the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMUserVisual object to be added.

deleteChild

public void deleteChild(Direct3dRMFrame c);

Removes a frame from the hierarchy. If the frame is not referenced, it is destroyed along with any child frames, lights, and meshes.

Return Value:

No return value.

Parameter | Description
c | The Direct3dRMFrame object to be used as the child.

deleteLight

public void deleteLight(Direct3dRMLight l);

Removes a light from a frame and destroys it if it is no longer referenced. When a light is removed from a frame, it no longer affects meshes in the scene its frame was in.

Return Value:

No return value.

Parameter | Description
l | The Direct3dRMLight object to be removed.

deleteMoveCallback

public void deleteMoveCallback(IFrameMoveCallback fn, IUnknown args);

Removes a callback function that performed special motion processing.

Return Value:

No return value.

Parameter | Description
fn | The callback interface that contains an application-defined callback function.
args | Application-defined data that was passed to the callback function.

See Also: addMoveCallback, move

deleteVisual

public void deleteVisual(Direct3dRMVisual v);

Removes a visual object from a frame and destroys it if it is no longer referenced.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMVisual object to be removed.

deleteVisualFrame

public void deleteVisualFrame(Direct3dRMFrame v);

Deletes a visual frame from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMFrame object to be deleted.

deleteVisualMesh

public void deleteVisualMesh(Direct3dRMMesh v);

Deletes a mesh object from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMMesh object to be deleted.

deleteVisualMeshBuilder

public void deleteVisualMeshBuilder(Direct3dRMMeshBuilder v);

Deletes a mesh builder object from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMMeshBuilder object to be deleted.

deleteVisualShadow

public void deleteVisualShadow(Direct3dRMShadow v);

Deletes a shadow object from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMShadow object to be deleted.

deleteVisualTexture

public void deleteVisualTexture(Direct3dRMTexture v);

Deletes a texture object from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMTexture object to be deleted.

deleteVisualUserVisual

public void deleteVisualUserVisual(Direct3dRMUserVisual v);

Deletes a user visual object from the frame object.

Return Value:

No return value.

Parameter | Description
v | The Direct3dRMUserVisual object to be deleted.

getChildren

public Direct3dRMFrameArray getChildren();

Retrieves a list of child frames in the form of a Direct3dRMFrameArray object.

Return Value:

Returns the Direct3dRMFrameArray object if successful; otherwise, null.

See Also: com.ms.directX.Direct3dRMFrameArray

getColor

public int getColor();

Retrieves the color of the frame.

Return Value:

Returns the color of the Direct3dRMFrame object.

See Also: setColor

getLights

public Direct3dRMLightArray getLights();

Retrieves a list of lights in the frame in the form of a Direct3dRMLightArray object.

Return Value:

Returns the Direct3dRMLightArray object if successful; otherwise, null.

See Also: com.ms.directX.Direct3dRMLightArray

getMaterialMode

public int getMaterialMode();

Retrieves the material mode of the frame.

Return Value:

Returns a value of material mode type that specifies the current material mode.

See Also: setMaterialMode

getOrientation

public void getOrientation(Direct3dRMFrame ref, D3dVector dir,
        D3dVector up);

Retrieves the orientation of a frame relative to the given reference frame.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMFrame object to be used as the reference.
dir | The D3dVector objects that receive the directions of the frame's z-axis.
up | The D3dVector objects that receive the directions of the frame's y-axis.

See Also: setOrientation

getParent

public Direct3dRMFrame getParent();

Retrieves the parent frame of the current frame.

Return Value:

Returns the Direct3dRMFrame object if successful; null otherwise.

Remarks:

If the current frame is the root, this method returns null.

getPosition

public void getPosition(Direct3dRMFrame ref, D3dVector position);

Retrieves the position of a frame, relative to the given reference frame. (For example, this method retrieves the distance of the frame from the reference.) The distance is stored in the position parameter as a vector, rather than as a linear measure.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMFrame object to be used as the reference.
position | The D3dVector object that receives the frame's position.

See Also: setPosition

getRotation

public void getRotation(Direct3dRMFrame ref, D3dVector axis, float[] theta);

Retrieves the rotation of the frame, relative to the given reference frame.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMFrame object to be used as the reference.
axis | The D3dVector object that receives the frame's axis of rotation.
theta | The array variable that receives the frame's rotation, in radians.

See Also: setRotation

getScene

public Direct3dRMFrame getScene();

Retrieves the root frame of the hierarchy containing the given frame.

Return Value:

Returns the Direct3dRMFrame object if successful; otherwise, null.

getSceneBackground

public int getSceneBackground();

Retrieves the background color of a scene.

Return Value:

Returns the color.

getSceneBackgroundDepth

public DirectDrawSurface getSceneBackgroundDepth();

Retrieves the current background-depth buffer for the scene.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

See Also: setSceneBackgroundDepth

getSceneFogColor

public int getSceneFogColor();

Retrieves the fog color of a scene.

Return Value:

Returns the fog's color.

getSceneFogEnable

public int getSceneFogEnable();

Returns whether fog is currently enabled for this scene.

Return Value:

Returns true if fog is enabled, otherwise, returns false.

getSceneFogMode

public int getSceneFogMode();

Retrieves the current fog mode for this scene.

Return Value:

Returns a value of the fog mode type that specifies the current fog mode.

getSceneFogParams

public void getSceneFogParams(float[] start, float[] end, float[] density);

Retrieves the current fog parameters for this scene.

Return Value:

No return value.

Parameter | Description
start | The array variables that receive the fog start values.
end | The array variables that receive the fog end values.
density | The array variables that receive the fog density values.

getSortMode

public int getSortMode();

Retrieves the sorting mode used to process child frames.

Return Value:

Returns a value of the D3DRMSORT_ type that specifies the sorting mode.

See Also: setSortMode

getTexture

public Direct3dRMTexture getTexture();

Retrieves the texture of the given frame.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, null.

See Also: setTexture

getTextureTopology

public void getTextureTopology(int[] u, int[] v);

Retrieves the topological properties of a texture when it is mapped onto objects in the given frame.

Return Value:

No return value.

Parameter | Description
u | Array variable that is set to true if the texture is mapped in the u direction.
v | Array variable that is set to true if the texture is mapped in the v direction.

See Also: setTextureTopology

getTransform

public void getTransform(float[] val);

Retrieves the local transformation of the frame as a 4-by-4 affine matrix.

Return Value:

No return value.

Parameter | Description
val | The array variable that receives the frame's transformation.

getVelocity

public void getVelocity(Direct3dRMFrame ref, D3dVector vel, int rotation);

Retrieves the velocity of the frame, relative to the given reference frame.

Return Value:

No return value.

Parameter | Description
ref | The Direct3dRMFrame object to be used as the reference.
vel | A D3dVector object that receives the frame's velocity.
rotation | A flag specifying whether the rotational velocity of the object is taken into account when retrieving the linear velocity. If this parameter is true, the object's rotational velocity is included in the calculation.

See Also: setVelocity

getVisuals

public Direct3dRMVisualArray getVisuals();

Retrieves a list of visuals in the frame.

Return Value:

Returns the Direct3dRMVisualArray object if successful; otherwise, null.

getZbufferMode

public int getZbufferMode();

Determines whether z-buffering is enabled or disabled.

Return Value:

Returns one value of D3DRMZBUFFER_ type.

See Also: setZbufferMode

inverseTransform

public void inverseTransform(D3dVector d, D3dVector s);

Transforms the vector in the s parameter in world coordinates to model coordinates, and returns the result in the d parameter.

Return Value:

No return value.

Parameter | Description
d | A D3dVector object that receives the result of the transformation.
s | The D3dVector object that is the source of the transformation.

See Also: transform

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser);

Loads a Direct3dRMFrame object.

Return Value:

No return value.

Parameter | Description
filename | The name of the file containing the object to be loaded.
position | The position of the object to be loaded. This is a value that gives the object's order in the file. This parameter can be null.
flags | The value of the load options type.
c | The callback interface that contains a load texture callback function called to load any textures used by the object that require special formatting. This parameter can be null.
pUser | Application-defined data passed to the load texture callback function.

Remarks:

By default, this method loads the first frame hierarchy in the file specified by the filename parameter. The frame that calls this method is used as the parent of the new frame hierarchy.

lookAt

public void lookAt(Direct3dRMFrame tgt, Direct3dRMFrame ref, int val);

Faces the frame toward the target frame (relative to the given reference frame) and locks the rotation by the given constraints.

Return Value:

No return value.

Parameter | Description
tgt | The Direct3dRMFrame objects to be used as the target.
ref | The Direct3dRMFrame objects to be used as the reference.
val | The value of frame constraint type that specifies the axis of rotation constrained.

move

public void move(float delta);

Applies the rotations and velocities for all frames in the given hierarchy.

Return Value:

No return value.

Parameter | Description
delta | The amount to change the velocity and rotation by.

setColor

public void setColor(int c);

Sets the color of the frame. This color is used for meshes in the frame when the material mode is D3DRMMATERIAL_FROMFRAME.

Return Value:

No return value.

Parameter | Description
c | New color for the frame.

See Also: getColor, setMaterialMode

setColorRGB

public void setColorRGB(float r, float g, float b);

Sets the color of the frame. This color is used for meshes in the frame when the material mode is D3DRMMATERIAL_FROMFRAME.

Return Value:

No return value.

Parameter | Description
r | The red component of a new color for the frame.
g | The green component of a new color for the frame.
b The blue component of a new color for the frame.

Each component of the color should be in the range of 0 to 1.

See Also: setMaterialMode

setMaterialMode

public void setMaterialMode(int val);

Sets the material mode for a frame. The material mode determines the source of material information for visuals rendered with the frame.

Return Value:

No return value.

Parameter | Description
val | The material mode type.

See Also: getMaterialMode

setOrientation

public void setOrientation(Direct3dRMFrame reference, float dx, float dy,
        float dz, float ux, float uy, float uz);

Aligns a frame so that its z-direction points along the direction vector [dx, dy, dz] and its y-direction aligns with the vector [ux, uy, uz].

Return Value:

No return value.

Parameter | Description
reference | The Direct3dRMFrame object to be used as the reference.
dx | The new z axis for the frame.
dy | The new z axis for the frame.
dz | The new z axis for the frame.
ux | The new y axis for the frame.
uy | The new y axis for the frame.
uz | The new y axis for the frame.

Remarks:

The default orientation of a frame has a direction vector of [0, 0, 1] and an up vector of [0, 1, 0].

If [ux, uy, uz] is parallel to [dx, dy, dz], no action is taken; otherwise, the [ux, uy, uz] vector passed is projected onto the plane that is perpendicular to [dx, dy, dz].

See Also: getOrientation

setPosition

public void setPosition(Direct3dRMFrame reference, float x, float y,
        float z);

Sets the position of a frame, relative to the frame of reference. This method places the frame a distance of [x, y, z] from the reference. When a child frame is created within a parent frame, it is placed at [0, 0, 0] in the parent frame.

Return Value:

No return value.

Parameter | Description
reference | The Direct3dRMFrame object to be used as the reference.
x | The x coordinate of the new position for the frame.
y | The y coordinate of the new position for the frame.
z | The z coordinate of the new position for the frame.

See Also: getPosition

setRotation

public void setRotation(Direct3dRMFrame reference, float x, float y,
        float z, float theta);

Sets a frame rotating by the given angle around the given vector at each call to the tick or move method. The direction vector [x, y, z] is defined in the reference frame.

Return Value:

No return value.

Parameter | Description
reference | The Direct3dRMFrame object to be used as the reference.
x | The x element of the vector, about which rotation occurs.
y | The y element of the vector, about which rotation occurs.
z | The z element of the vector, about which rotation occurs.
theta | The rotation angle, in radians.

Remarks:

The specified rotation changes the matrix with every render tick, unlike the addRotation method, which changes the objects in the frame only once.

See Also: addRotation, getRotation

setSceneBackground

public void setSceneBackground(int c);

Sets the background color of a scene.

Return Value:

No return value.

Parameter | Description
c | New color for the background.

setSceneBackgroundDepth

public void setSceneBackgroundDepth(DirectDrawSurface s);

Specifies a background-depth buffer for a scene.

Return Value:

No return value.

Parameter | Description
s | A DirectDrawSurface object that will store the new background depth for the scene.

Remarks:

The image must have a depth of 16. If the image and viewport sizes are different, the image is scaled first. For best performance when animating the background-depth buffer, the image should be the same size as the viewport. This enables the depth buffer to be updated directly from the image memory without incurring extra overhead.

See Also: getSceneBackgroundDepth

setSceneBackgroundImage

public void setSceneBackgroundImage(Direct3dRMTexture i);

Specifies a background image for a scene.

Return Value:

No return value.

Parameter | Description
i | A Direct3dRMTexture object that will contain the new background scene.

Remarks:

If the image is a different size or color depth than the viewport, the image will first be scaled or converted to the correct depth. For best performance when animating the background, the image should be the same size and color depth. This enables the background to be rendered directly from the image memory without incurring any extra overhead.

setSceneBackgroundRGB

public void setSceneBackgroundRGB(float r, float g, float b);

Sets the background color of a scene, using an RGB value.

Return Value:

No return value.

Parameter | Description
r | The red component of the new color for the background.
g | The green component of the new color for the background.
b | The blue component of the new color for the background.

setSceneFogColor

public void setSceneFogColor(int c);

Sets the fog color of a scene.

Return Value:

No return value.

Parameter | Description
c | The new color for the fog.

setSceneFogEnable

public void setSceneFogEnable(int enable);

Sets the fog enable state.

Return Value:

No return value.

Parameter | Description
enable | The new fog enable state.

setSceneFogMode

public void setSceneFogMode(int c);

Sets the fog mode.

Return Value:

No return value.

Parameter | Description
c | The fog mode type.

See Also: setSceneFogParams

setSceneFogParams

public void setSceneFogParams(float s, float e, float d);

Sets the current fog parameters for the scene.

Return Value:

No return value.

Parameter | Description
s | The fog start point for linear fog mode.
e | The fog end point for linear fog mode. These settings determine the distance from the camera at which the fog effects first become visible and the distance at which the fog reaches its maximum density.
d | The fog density for the exponential fog modes.. This value should be in the range of 0 through 1.

See Also: setSceneFogMode

setSortMode

public void setSortMode(int val);

Sets the sorting mode used to process child frames. You can use this method to change the properties of hidden-surface-removal algorithms.

Return Value:

No return value.

Parameter | Description
val | One value of the D3DRMSORT_ type, specifying the sorting mode.

Remarks:

By default, a frame's initial sort mode is D3DRMSORT_FROMPARENT.

See Also: getSortMode

setTexture

public void setTexture(Direct3dRMTexture t);

Sets the texture of the frame.

Return Value:

No return value.

Parameter | Description
t | The Direct3dRMTexture object to be used.

Remarks:

The texture is used for meshes in the frame when the material mode is D3DRMMATERIAL_FROMFRAME. To disable the frame's texture, use a null texture.

See Also: getTexture, setMaterialMode

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);

Defines the topological properties of the texture coordinates across objects in the frame.

Return Value:

No return value.

Parameter | Description
wrap_u | A variable that is set to true to map the texture in the u-direction.
wrap_v | A variable that is set to true to map the texture in the v-directions.

See Also: getTextureTopology

setVelocity

public void setVelocity(Direct3dRMFrame reference, float x, float y,
        float z, int with_rotation);

Sets the velocity of the given frame relative to the reference frame. The frame will be moved by the vector [x, y, z], with respect to the reference frame at each successive call to the tick or move method.

Return Value:

No return value.

Parameter | Description
reference | The Direct3dRMFrame object to be used as the reference.
x | The x component of the new velocity for the frame.
y | The y component of the new velocity for the frame.
z | The z component of the new velocity for the frame.
with_rotation | A flag specifying whether the rotational velocity of the object is taken into account when setting the linear velocity. If with_rotation is true, the object's rotational velocity is included in the calculation.

See Also: getVelocity

setZbufferMode

public void setZbufferMode(int val);

Sets the z-buffer mode (that is, whether z-buffering is enabled or disabled).

Return Value:

No return value.

Parameter | Description
val | One value of theD3DRMZBUFFER_ type, specifying the z-buffer mode.

Remarks:

By default, a frame's initial z-buffer mode is D3DRMZBUFFER_FROMPARENT.

See Also: getZbufferMode

transform

public void transform(D3dVector d, D3dVector s);

Transforms the vector in the s parameter, which is in model coordinates, into world coordinates. The result is returned in the d parameter.

Return Value:

No return value.

Parameter | Description
d | A D3dVector object that receives the result of the transformation operation.
s | The D3dVector object that is the source of the transformation operation.

See Also: inverseTransform


Class Direct3dRMFrameArray

public class Direct3dRMFrameArray implements
            IDirect3dRMFrameArray
{
  // Methods
  public Direct3dRMFrame getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMFrameArray class to organize frame objects.

The Direct3dRMFrameArray object is obtained by calling the getPickFrame or getChildren method.

Methods

getElement

public Direct3dRMFrame getElement(int index);

Retrieves one of the Direct3dRMFrame objects associated with this object.

Return Value:

Returns the Direct3dRMFrame object if successful; otherwise, null.

Parameter | Description
index | Identifies the object to return. Must be a value in the range of 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Retrieves the number of Direct3dRMFrame objects associated with this object.

Return Value:

Returns the number of objects.


Class Direct3dRMLight

public class Direct3dRMLight implements IDirect3dRMLight
{
  // Methods
  public int getColor();
  public float getConstantAttenuation();
  public Direct3dRMFrame getEnableFrame();
  public float getLinearAttenuation();
  public float getPenumbra();
  public float getQuadraticAttenuation();
  public float getRange();
  public int getType();
  public float getUmbra();
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setConstantAttenuation(float atn);
  public void setEnableFrame(Direct3dRMFrame f);
  public void setLinearAttenuation(float atn);
  public void setPenumbra(float p);
  public void setQuadraticAttenuation(float atn);
  public void setRange(float rng);
  public void setType(int t);
  public void setUmbra(float u);
}

Applications use the methods of the Direct3dRMLight class to interact with light objects.

The Direct3dRMLight class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMLight object is obtained by calling the createLight or createLightRGB method.

Methods

getColor

public int getColor();

Retrieves the color of the current Direct3dRMLight object.

Return Value:

Returns the color.

See Also: setColor

getConstantAttenuation

public float getConstantAttenuation();

Retrieves the constant attenuation factor for the Direct3dRMLight object.

Return Value:

Returns the constant attenuation value.

Remarks:

The constant attenuation value affects the light intensity inversely. For example, a constant attenuation value of 2 reduces the intensity of the light by half.

See Also: setConstantAttenuation

getEnableFrame

public Direct3dRMFrame getEnableFrame();

Retrieves the enable frame for a light.

Return Value:

Returns the Direct3dRMFrame object if successful; otherwise, null.

See Also: setEnableFrame

getLinearAttenuation

public float getLinearAttenuation();

Retrieves the linear attenuation factor for a light.

Return Value:

Returns the linear attenuation value.

See Also: setLinearAttenuation

getPenumbra

public float getPenumbra();

Retrieves the penumbra angle of a spotlight.

Return Value:

Returns the penumbra angle.

See Also: setPenumbra

getQuadraticAttenuation

public float getQuadraticAttenuation();

Retrieves the quadratic attenuation factor for a light.

Return Value:

Returns the quadratic attenuation value.

See Also: setQuadraticAttenuation

getRange

public float getRange();

Retrieves the range of the current Direct3dRMLight object.

Return Value:

Returns a value describing the range.

See Also: setRange

getType

public int getType();

Retrieves the type of a given light.

Return Value:

Returns one value of light type.

See Also: setType

getUmbra

public float getUmbra();

Retrieves the umbra angle of the Direct3dRMLight object.

Return Value:

Returns The umbra angle.

See Also: setUmbra

setColor

public void setColor(int c);

Sets the color of the given light.

Return Value:

No return value.

Parameter | Description
c | The new color of the light.

See Also: getColor

setColorRGB

public void setColorRGB(float r, float g, float b);

Sets the color of the given light.

Return Value:

No return value.

Parameter | Description
r | The red element of the new color of the light.
g | The green element of the new color of the light.
b | The blue element of the new color of the light.

setConstantAttenuation

public void setConstantAttenuation(float atn);

Sets the constant attenuation factor for a light.

Return Value:

No return value.

Parameter | Description
atn | The new attenuation factor.

Remarks:

The constant attenuation value affects the light intensity inversely. For example, a constant attenuation value of 2 reduces the intensity of the light by half.

See Also: getConstantAttenuation

setEnableFrame

public void setEnableFrame(Direct3dRMFrame f);

Sets the enable frame for a light.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object to be the light's enable frame. Child frames of this frame are also enabled for this light source.

See Also: getEnableFrame

setLinearAttenuation

public void setLinearAttenuation(float atn);

Sets the linear attenuation factor for a light.

Return Value:

No return value.

Parameter | Description
atn | The new attenuation factor.

See Also: getLinearAttenuation

setPenumbra

public void setPenumbra(float p);

Sets the angle of the penumbra cone.

Return Value:

No return value.

Parameter | Description
p | The new penumbra angle. This angle must be greater than or equal to the angle of the umbra. If you set the penumbra angle to less than the umbra angle, the umbra angle will be set equal to the penumbra angle.

Remarks:

By default, the initial penumbra angle is 0.5 radians.

See Also: getPenumbra

setQuadraticAttenuation

public void setQuadraticAttenuation(float atn);

Sets the quadratic attenuation factor for a light.

Return Value:

No return value.

Parameter | Description
atn | The new attenuation factor.

See Also: getQuadraticAttenuation

setRange

public void setRange(float rng);

Sets the range of a light. The light affects only those objects within the range.

Return Value:

No return value.

Parameter | Description
rng | The new range.

Remarks:

By default, the initial range of light is 256.

See Also: getRange

setType

public void setType(int t);

Changes the light type.

Return Value:

No return value.

Parameter | Description
t | The new light type.

See Also: getType

setUmbra

public void setUmbra(float u);

Sets the angle of the umbra cone.

Return Value:

No return value.

Parameter | Description
u | The new umbra angle. This angle must be less than or equal to the angle of the penumbra. If you set the umbra angle to greater than the penumbra angle, the penumbra angle will be set equal to the umbra angle.

Remarks:

By default, the initial umbra angle is 0.4 radians.

See Also: getUmbra


Class Direct3dRMLightArray

public class Direct3dRMLightArray implements
            IDirect3dRMLightArray
{
  // Methods
  public Direct3dRMLight getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMLightArray class to organize light objects.

The Direct3dRMLightArray object is obtained by calling the getLights method.

Methods

getElement

public Direct3dRMLight getElement(int index);

Retrieves one of the Direct3dRMLight objects associated with this object.

Return Value:

Returns the Direct3dRMLight object if successful; otherwise, returns null.

Parameter | Description
index | Identifies the object to return. The index must be a value in the range of 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Retrieves the number of Direct3dRMLight objects associated with this object.

Return Value:

Returns the number of objects.


Class Direct3dRMMaterial

public class Direct3dRMMaterial implements IDirect3dRMMaterial
{
  // Methods
  public void getEmissive(float[] r, float[] g, float[] b);
  public float getPower();
  public void getSpecular(float[] r, float[] g, float[] b);
  public void setEmissive(float r, float g, float b);
  public void setPower(float power);
  public void setSpecular(float r, float g, float b);
}

Applications use the methods of the Direct3dRMMaterial class to interact with material objects.

The Direct3dRMMaterial class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMMaterial object is obtained by calling the createMaterial method.

Methods

getEmissive

public void getEmissive(float[] r, float[] g, float[] b);

Retrieves the setting for the emissive property of a material. The setting of this property is the color and intensity of the light that the object emits.

Return Value:

No return value.

Parameter | Description
r | The array variables that receive the red component of the emissive color.
g | The array variables that receive the green component of the emissive color.
b | The array variables that receive the blue component of the emissive color.

See Also: setEmissive

getPower

public float getPower();

Retrieves the power used for the specular exponent in the given material.

Return Value:

Returns the value specifying the power of the specular exponent.

See Also: setPower

getSpecular

public void getSpecular(float[] r, float[] g, float[] b);

Retrieves the color of the specular highlights of a material.

Return Value:

No return value.

Parameter | Description
r | The array variables that receive the red component of the color of the specular highlights when the method returns.
g | The array variables that receive the green component of the color of the specular highlights when the method returns.
b | The array variables that receive the blue component of the color of the specular highlights when the method returns.

See Also: setSpecular

setEmissive

public void setEmissive(float r, float g, float b);

Sets the emissive property of a material.

Return Value:

No return value.

Parameter | Description
r | The red component of the emissive color.
g | The green component of the emissive color.
b | The blue component of the emissive color.

See Also: getEmissive

setPower

public void setPower(float power);

Sets the power used for the specular exponent in a material.

Return Value:

No return value.

Parameter | Description
power | The new specular exponent.

See Also: getPower

setSpecular

public void setSpecular(float r, float g, float b);

Sets the color of the specular highlights of a material.

Return Value:

No return value.

Parameter | Description
r | The red component of the specular highlight color.
g | The green component of the specular highlight color.
b | The blue component of the specular highlight color.

See Also: getSpecular


Class Direct3dRMMesh

public class Direct3dRMMesh implements IDirect3dRMMesh
{
  // Methods
  public void addGroup(int vcnt, int fcnt, int vPerFace,
        int[] fdata, int[] retId);
  public void getBox(D3dRMBox vector);
  public void getGroup(int id, int[] vcnt, int[] fcnt,
        int[] vPerFace, int[] fDataSize, int[] fdata);
  public int getGroupColor(int id);
  public int getGroupCount();
  public int getGroupMapping(int id);
  public Direct3dRMMaterial getGroupMaterial(int id);
  public int getGroupQuality(int id);
  public void getGroupSize(int id, int[] val);
  public Direct3dRMTexture getGroupTexture(int id);
  public void getVertices(int id, int idx, int vCount,
        Direct3dRMVertex[] v);
  public void getVerticesSize(int id, int idx, int[] cnt);
  public void scale(float sx, float sy, float sz);
  public void setGroupColor(int id, int val);
  public void setGroupColorRGB(int id, float r, float g, float b);
  public void setGroupMapping(int id, int value);
  public void setGroupMaterial(int id, Direct3dRMMaterial val);
  public void setGroupQuality(int id, int value);
  public void setGroupTexture(int id, Direct3dRMTexture val);
  public void setVertices(int id, int idx, int vCount,
        Direct3dRMVertex[] v);
  public void setVerticesAsFloats(int id, int idx, int vCount,
        float[] v);
  public void translate(float tx, float ty, float tz);
}

Applications use the methods of the Direct3dRMMesh class to interact with groups of meshes.

The Direct3dRMMesh class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMMesh object is obtained by calling the createMesh method.

Methods

addGroup

public void addGroup(int vcnt, int fcnt, int vPerFace, int[] fdata,
        int[] retId);

Allocates space for a collection of vertices and faces and retrieves an identifier for the group.

Return Value:

No return value.

Parameter | Description
vcnt | The number of vertices in the group.
fcnt | The number of faces in the group.
vPerFace | Number of vertices per face in the group, if all faces have the same vertex count. If the group contains faces with varying vertex counts, this parameter should be zero.
fdata The array variable containing face data.

If the vPerFace parameter specifies a value, this data is simply a list of indices into the group's vertex array. If vPerFace is zero, the vertex indices should be preceded by an integer giving the number of vertices in that face.

For example, if vPerFace is zero and the group is made up of triangular and quadrilateral faces, the data might be in the following form:

3 index index index 4 index index index index 3 index index index ...
retId | The array variable that receives a value identifying the group.

Remarks:

A newly added group has the following default properties:

  • White
  • No texture
  • No specular reflection
  • Position, normal, and color of each vertex in the vertex array equal to zero

To set the positions of the vertices, use the setVertices method.

getBox

public void getBox(D3dRMBox vector);

Retrieves the bounding box containing a Direct3dRMMesh object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Return Value:

No return value.

Parameter | Description
vector | A D3dRMBox object that receives the bounding box coordinates.

getGroup

public void getGroup(int id, int[] vcnt, int[] fcnt, int[] vPerFace,
        int[] fDataSize, int[] fdata);

Retrieves the data associated with a specified group.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
vcnt | The array variables that receive the number of vertices for the group.
fcnt | The array variables that receive the number of faces for the group.
vPerFace | The array variable that receives the number of vertices per face for the group.
fDataSize | The array variable that receives the number of values in the array associated with the fdata parameter.
fData | The array variable that receives the face data for the group. The format of this data is the same as was specified in the call to the addGroup method.

getGroupColor

public int getGroupColor(int id);

Retrieves the color for a group.

Return Value:

Returns a value specifying the color if successful; otherwise, returns zero.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.

See Also: setGroupColor, setGroupColorRGB

getGroupCount

public int getGroupCount();

Retrieves the number of groups for a given Direct3dRMMesh object.

Return Value:

Returns the number of groups if successful; otherwise, returns zero.

getGroupMapping

public int getGroupMapping(int id);

Returns a description of how textures are mapped to a group in a Direct3dRMMesh object.

Return Value:

Returns one value of mapping type describing how textures are mapped to a group, if successful; otherwise, returns zero.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.

See Also: setGroupMapping

getGroupMaterial

public Direct3dRMMaterial getGroupMaterial(int id);

Retrieves the material object associated with a group in a Direct3dRMMesh object.

Return Value:

Returns the Direct3dRMMaterial object if successful; otherwise, returns null.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.

See Also: setGroupMaterial

getGroupQuality

public int getGroupQuality(int id);

Retrieves the rendering quality for a specified group in a Direct3dRMMesh object.

Return Value:

Returns one or more values of the render quality type if successful; otherwise, returns zero. These values include the shading, lighting, and fill modes for the object.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.

See Also: setGroupQuality

getGroupSize

public void getGroupSize(int id, int[] val);

Retrieves the size of data associated with the group.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
val | The array variable that receives the size of the data.

See Also: getGroup

getGroupTexture

public Direct3dRMTexture getGroupTexture(int id);

Retrieves an address of the texture associated with a group in a Direct3dRMMesh object.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, returns null.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.

See Also: setGroupTexture

getVertices

public void getVertices(int id, int idx, int vCount, Direct3dRMVertex[] v);

Retrieves the vertex positions for a specified group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
idx The index of the D3dRMVertex object to return. The idx parameter is used in an internal data structure, not the v array. The structure follows the following format
D3DVECTOR position;    v[0]x  v[1]y  v[2]z
D3DVECTOR normal;      v[3]xn v[4]yn v[5]zn
D3DVALUE tu, tv;       v[6]   v[7]
D3DCOLOR color;        v[8]
                       v[9]x for the next D3dRMVector
vCount | The number of D3dRMVertex objects (vertices) to retrieve.
v | The array of D3dRMVertex objects that receives the vertex positions.

See Also: setVertices

getVerticesSize

public void getVerticesSize(int id, int idx, int[] cnt);

Retrieves the number of vertex positions from the given index to the end of the array associated with the group.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
idx | The index of the first vertex position to count.
cnt | The array variable that receives the count of vertex positions.

See Also: getVertices

scale

public void scale(float sx, float sy, float sz);

Scales a Direct3dRMMesh object by the given scaling factors parallel to the x-, y-, and z-axes in model coordinates.

Return Value:

No return value.

Parameter | Description
sx | The scaling factor that is applied along the x-axis.
sy | The scaling factor that is applied along the y-axis.
sz | The scaling factor that is applied along the z-axis.

setGroupColor

public void setGroupColor(int id, int val);

Sets the color of a group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
val | The color of the group.

See Also: getGroupColor, setGroupColorRGB

setGroupColorRGB

public void setGroupColorRGB(int id, float r, float g, float b);

Sets the color of a group in a Direct3dRMMesh object by using individual RGB values.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
r | The red component of the group color.
g | The green component of the group color.
b | The blue component of the group color.

See Also: getGroupColor, setGroupColor

setGroupMapping

public void setGroupMapping(int id, int value);

Sets the mapping for a group in a Direct3dRMMesh object. The mapping controls how textures are mapped to a surface.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
value | The mapping type value describing the mapping for the group.

See Also: getGroupMapping

setGroupMaterial

public void setGroupMaterial(int id, Direct3dRMMaterial val);

Sets the material associated with a group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
val | The Direct3dRMMaterial object to set.

See Also: getGroupMaterial

setGroupQuality

public void setGroupQuality(int id, int value);

Sets the rendering quality for a specified group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
value | The render quality type value. These values include the shading, lighting, and fill modes for the object.

See Also: getGroupQuality

setGroupTexture

public void setGroupTexture(int id, Direct3dRMTexture val);

Sets the texture associated with a group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
val | The Direct3dRMTexture object to set.

See Also: getGroupTexture

setVertices

public void setVertices(int id, int idx, int vCount, Direct3dRMVertex[] v);

Sets the vertex positions for a specified group in a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
idx The index of the first D3dRMVertex object to set. The idx parameter is used in an internal data structure, not the v array. The structure follows the following format
D3DVECTOR position;    v[0]x  v[1]y  v[2]z
D3DVECTOR normal;      v[3]xn v[4]yn v[5]zn
D3DVALUE tu, tv;       v[6]   v[7]
D3DCOLOR color;        v[8]
                       v[9]x for the next D3dRMVector
vCount | The number of vertices in the array.
v | An array of D3dRMVertex objects specifying the vertex positions to be set.

Remarks:

Vertices are local to the group. If an application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups.

See Also: getVertices

setVerticesAsFloats

public void setVerticesAsFloats(int id, int idx, int vCount, float[] v);

Sets the vertex positions for a specified group in a Direct3dRMMesh object, using an array of floats.

Return Value:

No return value.

Parameter | Description
id | The group identifier. This identifier must have been produced by using the addGroup method.
idx | The index of the first D3dRMVertex object to set. The idx parameter is used in an internal data structure, not the v array.
vCount | The number of floats to set.
v | An array of floats specifying the vertex positions to be set.

Remarks:

Vertices are local to the group. If an application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups.

translate

public void translate(float tx, float ty, float tz);

Adds the specified offsets to the vertex positions of a Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
tx | The offset that is added to the x coordinate of each vertex position.
ty | The offset that is added to the y coordinate of each vertex position.
tz | The offset that is added to the z coordinate of each vertex position.


Class Direct3dRMMeshBuilder

public class Direct3dRMMeshBuilder implements
            IDirect3dRMMeshBuilder
{
  // Methods
  public void addFace(Direct3dRMFace f);
  public void addFaces(int vCount, D3dVector[] v, int nCount,
        D3dVector[] n, int[] cones);
  public void addFacesAsFloats(int vc, float[] ver, int nc, float[]
        norm, int[] cones);
  public void addFrame(Direct3dRMFrame f);
  public void addMesh(Direct3dRMMesh m);
  public void addMeshBuilder(Direct3dRMMeshBuilder mb);
  public int addNormal(float x, float y, float z);
  public int addVertex(float x, float y, float z);
  public Direct3dRMFace createFace();
  public Direct3dRMFaceArray createFaceArray(int vCount,
        float[] vertices, int nCount, float[] normals,
        int[] cones);
  public Direct3dRMMesh createMesh();
  public void generateNormals();
  public void getBox(D3dRMBox retv);
  public int getColorSource();
  public Direct3dRMMeshBuilder getd3drmMeshBuilder();
  public int getFaceCount();
  public void getFacedataSize(int[] f_cnt);
  public Direct3dRMFaceArray getFaces();
  public void getNormalsSize(int[] n_cnt);
  public int getPerspective();
  public int getQuality();
  public void getTextureCoordinates(int idx, float[] u, float[] v);
  public int getVertexColor(int index);
  public int getVertexCount();
  public void getVertices(int[] vc, D3dvector v, int[] nc,
        D3dvector n, int[] fs, int[] fc);
  public int getVerticesSize();
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser);
  public void reserveSpace(int v_cnt, int n_cnt, int f_cnt);
  public void save(String fname, int xFormat, int save);
  public void scale(float sx, float sy, float sz);
  public void setColor(int col);
  public void setColorRGB(float red, float green, float blue);
  public void setColorSource(int val);
  public void setMaterial(Direct3dRMMaterial val);
  public void setNormal(int idx, float x, float y, float z);
  public void setPerspective(int persp);
  public void setQuality(int q);
  public void setTexture(Direct3dRMTexture val);
  public void setTextureCoordinates(int idx, float u, float v);
  public void setTextureTopology(int wrap_u, int wrap_v);
  public void setVertex(int idx, float x, float y, float z);
  public void setVertexColor(int idx, int c);
  public void setVertexColorRGB(int idx, float r, float g, float b);
  public void translate(float tx, float ty, float tz);
}

Applications use the methods of the Direct3dRMMeshBuilder class to interact with mesh objects.

The Direct3dRMMeshBuilder class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMMeshBuilder object is obtained by calling the createMeshBuilder method.

There are two ways to add faces to a mesh object.
The recommended way is to use the addFaces method.

// Create a mesh builder.
mb = myd3drm.createMeshBuilder();

// Add faces to the mesh.
mb.addFaces(vCount, v, nCount, n, cones);

// Create a material to set for the whole mesh.
material = myd3drm.createMaterial();
mb.setMaterial(material); // This works.

Another possible way is to use the addVertex and addNormal methods, then use createFace to create a face, and add the vertices and normals to it. Currently, this procedure fails.

// Create a mesh builder.
mb = myd3drm.createMeshBuilder();
// Add four vertices.
mb.addVertex(x, y, x); // ...
// Add four normals.
mb.addNormal(x, y, z); // ...

// Create a face from the mesh builder.
d3drmface = mb.createFace();

// Use the Direct3dRMFace.addVertexAndNormalIndexed method
// to add the vertex and normals to the face.
d3drmface.addVertexAndNormalIndexed(index, index); // ...

// Create a material to set for the whole mesh.
material = myd3drm.createMaterial();
mb.setMaterial(material); // This faults.

Methods

addFace

public void addFace(Direct3dRMFace f);

Adds a face to a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFace object to add.

Remarks:

Any one face can exist in only one mesh at a time.

addFaces

public void addFaces(int vCount, D3dVector[] v, int nCount, D3dVector[] n,
        int[] cones);

Adds a face to the Direct3dRMMeshBuilder object. This method is very similar to addFaces(int, float[], int, float[], int[]) except that it uses D3dVector array objects instead of simple float arrays.

Return Value:

No return value.

Parameter | Description
vCount | The number of vertices to use to create the face.
v | An array of vectors that contains the vertices to use to create the face.
nCount The number of normals to use to create the face. If nCount is 0, then the data is formatted as follows:
3, 1, 2, 3 //(v[1], v[2], and v[3] make this triangle)
3, 1, 2, 5 //(v[1], v[2], and v[5] make this triangle)
4, 7, 4, 0, 1 //(v[7], v[4], 4[0], and v[1] make this quadrilateral)

However, if nCount is not 0, then the data is as follows:

3, 1, 1, 2, 2, 3, 3 // normals are interlaced.
3, 1, 1, 2, 2, 5, 5
4, 7, 7, 4, 4, 0, 0, 1, 1
n | An array of vectors that contains the normals used to create the face.
cones | Array variable that contains the data associated with the face.

addFacesAsFloats

public void addFacesAsFloats(int vc, float[] ver, int nc, float[] norm,
        int[] cones);

Adds a face to the Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
vc | Number of vertices. This is one-third the size of the float array.
ver | A float array variable that contains the vertices to use to create the face.
nc | Number of normals. This is one-third the size of the float array.
norm | A float array variable that contains the normals to use to create the face.
cones | Array variable that contains the data associated with the face.

addFrame

public void addFrame(Direct3dRMFrame f);

Adds the contents of a frame to a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object to add.

Remarks:

The source frame is not modified or referenced by this operation.

addMesh

public void addMesh(Direct3dRMMesh m);

Adds a mesh to a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
m | The Direct3dRMMesh object to add.

addMeshBuilder

public void addMeshBuilder(Direct3dRMMeshBuilder mb);

Adds the contents of a Direct3dRMMeshBuilder object to another Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
mb | The Direct3dRMMeshBuilder object to add.

Remarks:

The source Direct3dRMMeshBuilder object is not modified or referenced by this operation.

addNormal

public int addNormal(float x, float y, float z);

Adds a normal to a Direct3dRMMeshBuilder object.

Return Value:

Returns the index of the normal.

Parameter | Description
x | The x component of the direction of the new normal
y | The y component of the direction of the new normal
z | The z component of the direction of the new normal.

addVertex

public int addVertex(float x, float y, float z);

Adds a vertex to a Direct3dRMMeshBuilder object.

Return Value:

Returns the index of the vertex.

Parameter | Description
x | The x component of the position of the new vertex.
y | The y component of the position of the new vertex.
z | The z component of the position of the new vertex.

createFace

public Direct3dRMFace createFace();

Creates a new face with no vertices and adds it to a Direct3dRMMeshBuilder object.

Return Value:

Returns the Direct3dRMFace object if successful; otherwise, returns null

createFaceArray

public Direct3dRMFaceArray createFaceArray(int vCount, float[] vertices,
        int nCount, float[] normals, int[] cones);

Creates a face array for the Direct3dRMMeshBuilder object.

Return Value:

Returns the Direct3dRMFaceArray object if successful; otherwise, null

Parameter | Description
vCount | The number of vertices. This is one-third the size of the float array.
vertices | the array variable that contains the vertices used to create the face array.
nCount | the number of normals. This is one-third the size of the float array.
normals | The array variable that contains the normals used to create the face array.
cones | The array variable that contains the data associated with the face array.

createMesh

public Direct3dRMMesh createMesh();

Creates a new mesh from a Direct3dRMMeshBuilder object.

Return Value:

Returns the Direct3dRMMesh object if successful; otherwise, returns null

generateNormals

public void generateNormals();

Processes the Direct3dRMMeshBuilder object and generates vertex normals that are the average of each vertex's adjoining face normals.

Return Value:

No return value.

Remarks:

Averaging the normals of back-to-back faces produces a zero normal.

getBox

public void getBox(D3dRMBox retv);

Retrieves the bounding box containing a Direct3dRMMeshBuilder object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Return Value:

No return value.

Parameter | Description
retv | A D3dRMBox object that receives the bounding box coordinates.

getColorSource

public int getColorSource();

Retrieves the color source of a Direct3dRMMeshBuilder object. The color source can be either a face or a vertex.

Return Value:

Returns a value of color source type.

See Also: setColorSource

getd3drmMeshBuilder

public Direct3dRMMeshBuilder getd3drmMeshBuilder();

Retrieves a mesh builder object associated with this object.

Return Value:

Returns the Direct3dRMMeshBuilder object if successful; otherwise, returns null

getFaceCount

public int getFaceCount();

Retrieves the number of faces in a Direct3dRMMeshBuilder object.

Return Value:

Returns the number of faces.

getFacedataSize

public void getFacedataSize(int[] f_cnt);

Retrieves the size of the faces in a Direct3dRMFaceArray and stores them in the int array f_cnt.

Return Value:

No return value.

Parameter | Description
f_cnt | The array that stores the sizes of the faces that are measured.

getFaces

public Direct3dRMFaceArray getFaces();

Retrieves the faces of a Direct3dRMMeshBuilder object.

Return Value:

Returns the Direct3dRMFaceArray object if successful; otherwise, returns null

getNormalsSize

public void getNormalsSize(int[] n_cnt);

Retrieves the size of the normals in a Direct3dRMFaceArray and stores them in the int array n_cnt.

Return Value:

No return value.

Parameter | Description
n_cnt | The array that stores the sizes of the faces that are measured.

getPerspective

public int getPerspective();

Determines whether perspective correction for a Direct3dRMMeshBuilder object is turned on.

Return Value:

Returns true if perspective correction is on, otherwise, returns false.

getQuality

public int getQuality();

Retrieves the rendering quality of a Direct3dRMMeshBuilder object.

Return Value:

Returns a value that specifies the rendering quality of the mesh.

See Also: setQuality

getTextureCoordinates

public void getTextureCoordinates(int idx, float[] u, float[] v);

Retrieves the texture coordinates of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex.
u | The array variables that receive the texture coordinates of the vertex.
v | The array variables that receive the texture coordinates of the vertex.

See Also: setTextureCoordinates

getVertexColor

public int getVertexColor(int index);

Retrieves the color of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

Returns the color.

Parameter | Description
index | The index of the vertex.

See Also: setVertexColor

getVertexCount

public int getVertexCount();

Retrieves the number of vertices in a Direct3dRMMeshBuilder object.

Return Value:

Returns the number of vertices.

getVertices

public void getVertices(int[] vc, D3dvector v, int[] nc, D3dvector n, int[]
        fs, int[] fc);

Retrieves the vertex, normal, and face data for a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
vc | The array variable that receives the number of vertices.
v | A D3dVector object that receives the vertices for the Direct3dRMMeshBuilder object.
nc | The array variable that receives the number of normals.
n | A D3dVector object that receives the normals for the Direct3dRMMeshBuilder object.
fs | The array variable that receives the length of the array associated with the fc parameter.
fc | The array variable that receives the face data for the Direct3dRMMeshBuilder object. This data is in the same format as specified in the addFacesToMesh method except that it is null-terminated.

getVerticesSize

public int getVerticesSize();

Retrieves the number of vertices.

Return Value:

Returns the number of vertices.

See Also: getVertices

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser);

Loads a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
filename | The name of the file containing the object to be loaded.
position | The position of the object to be loaded. The value gives the object's order in the file.
flags | The load options type value.
c | The callback interface that contains a load texture callback function called to load textures used by an object that require special formatting. This parameter can be null.
pUser | Application-defined data passed to the load texture callback function.

Remarks:

By default, this method loads the first mesh from the file specified by the filename parameter.

reserveSpace

public void reserveSpace(int v_cnt, int n_cnt, int f_cnt);

Reserves space within a Direct3dRMMeshBuilder object for the specified number of vertices, normals, and faces. This allows the system to use memory more efficiently.

Return Value:

No return value.

Parameter | Description
v_cnt | The number of vertices to allocate space for.
n_cnt | The number of normals to allocate space for.
f_cnt | The number of faces to allocate space for.

save

public void save(String fname, int xFormat, int save);

Saves a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
fname | The name of the created file. This file must have a .X filename extension.
xFormat | D3DRMXOF_TEXT.
save | A value of the save options type.

scale

public void scale(float sx, float sy, float sz);

Scales a Direct3dRMMeshBuilder object by the given scaling factors, parallel to the x-, y-, and z-axes in model coordinates.

Return Value:

No return value.

Parameter | Description
sx | The scaling factors that are applied along the x-axis.
sy | the scaling factors that are applied along the y-axis.
sz | The scaling factors that are applied along the z-axis.

setColor

public void setColor(int col);

Sets all the faces of a Direct3dRMMeshBuilder object to a given color.

Return Value:

No return value.

Parameter | Description
col | The color of the faces.

setColorRGB

public void setColorRGB(float red, float green, float blue);

Sets all the faces of a Direct3dRMMeshBuilder object to a given color.

Return Value:

No return value.

Parameter | Description
red | The red component of the color.
green | The green component of the color.
blue | The blue component of the color.

setColorSource

public void setColorSource(int val);

Sets the color source of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
val | The value of color source type that specifies the new color source to use.

Remarks:

This method does not exhibit expected behavior under certain circumstances. If you use this method to set colors to faces, then it works as expected. But if you try to set colors for individual vertices, it wont, because face data is still used. To set vertice's colors, call the createMesh method and set individual vertex colors with the setVertex method.

See Also: getColorSource

setMaterial

public void setMaterial(Direct3dRMMaterial val);

Sets the material of all the faces of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
val | The Direct3dRMMaterial object to set.

setNormal

public void setNormal(int idx, float x, float y, float z);

Sets the normal vector of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the normal to be set.
x | The x component of the vector to assign to the specified normal.
y | The y component of the vector to assign to the specified normal.
z | The z component of the vector to assign to the specified normal.

setPerspective

public void setPerspective(int persp);

Enables or disables perspective-correct texture-mapping for a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
persp | Specify true if the mesh should be texture-mapped with perspective correction, otherwise, specify false.

setQuality

public void setQuality(int q);

Sets the rendering quality of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
q | The value that specifies the new rendering quality to use.

See Also: getQuality

setTexture

public void setTexture(Direct3dRMTexture val);

Sets the texture of all the faces of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
val | The Direct3dRMTexture object to set.

setTextureCoordinates

public void setTextureCoordinates(int idx, float u, float v);

Sets the texture coordinates of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex to be set.
u | The texture u coordinate to assign to the specified mesh vertex.
v | The texture v coordinate to assign to the specified mesh vertex.

See Also: getTextureCoordinates

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);

Sets the texture topology of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
wrap_u | Specify true if you want the texture to have a cylindrical topology in the u dimension; otherwise, specify false.
wrap_v Specify true if you want the texture to have a cylindrical topology in the v dimension; otherwise, specify false.

You can use any combination of true and false for these parameters. (Both may be true, both may be false, and so on.)

setVertex

public void setVertex(int idx, float x, float y, float z);

Sets the position of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex to be set.
x | The x component of the position to assign to the specified vertex.
y | The y component of the position to assign to the specified vertex.
z | The z component of the position to assign to the specified vertex.

setVertexColor

public void setVertexColor(int idx, int c);

Sets the color of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex to be set.
c | The color to assign to the specified vertex.

See Also: getVertexColor

setVertexColorRGB

public void setVertexColorRGB(int idx, float r, float g, float b);

Sets the color of a specified vertex in a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
idx | The index of the vertex to be set.
r | The red component of the color assigned to the specified vertex.
g | The green component of the color assigned to the specified vertex.
b | The blue component of the color assigned to the specified vertex.

translate

public void translate(float tx, float ty, float tz);

Adds the specified offsets to the vertex positions of a Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
tx | The offset that is added to the x coordinate of each vertex position.
ty | The offset that is added to the y coordinate of each vertex position.
tz | The offset that is added to the z coordinate of each vertex position.


Class Direct3dRMObject

public class Direct3dRMObject implements IDirect3dRMObject
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMObject duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void setAppData(int data);
  public void setName(String name);
}

Applications use the methods of the Direct3dRMObject class to work with the object superclass of Direct3dRM objects.

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

Registers a function to be called when an object is destroyed.

Return Value:

No return value.

Parameter | Description
fn | The callback interface that contains a user-defined callback function that will be called when the object is destroyed.
Arg | Application-defined data passed to the callback function. Because this function is called after the object has been destroyed, you should not call this function with the object as an argument.

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

Removes a function previously registered with the addDestroyCallback method.

Return Value:

No return value.

Parameter | Description
fn | The callback interface that contains a user-defined callback function that will be called when the object is destroyed.
args | Application-defined data passed to the callback function.

duplicate

public Direct3dRMObject duplicate();

Creates a copy of an object.

Return Value:

Returns the Direct3dRMObject object if successful; otherwise, returns null.

getAppData

public int getAppData();

Retrieves the 32 bits of application-specific data in the object. The default value is 0.

Return Value:

Returns the data value defined by the application.

See Also: setAppData

getClassName

public String getClassName();

Retrieves the name of the object's class.

Return Value:

Returns the name of the class.

getName

public String getName();

Retrieves the object name.

Return Value:

Returns the name of the object.

See Also: setName

setAppData

public void setAppData(int data);

Sets the 32 bits of application-specific data in the object.

Return Value:

No return value.

Parameter | Description
data | A user-defined integer. You cannot use this method to set a generic Java Object.

See Also: getAppData

setName

public void setName(String name);

Sets the object's name.

Return Value:

No return value.

Parameter | Description
name | A String that contains the name of the object.

See Also: getName


Class Direct3dRMPickArray

public class Direct3dRMPickArray implements
            IDirect3dRMPickArray
{
  // Methods
  public Direct3dRMFrameArray getPickFrame(int index, D3dRMPickDesc
        desc);
  public Direct3dRMVisual getPickVisual(int index,
        D3dRMPickDesc desc);
  public int getSize();
}

Applications use the methods of the Direct3dRMPickArray class to organize pick objects.

The Direct3dRMPickArray object is obtained by calling the pick method.

Methods

getPickFrame

public Direct3dRMFrameArray getPickFrame(int index, D3dRMPickDesc desc);

Retrieves a Direct3dRMFrameArray object associated with this object.

Return Value:

Returns the Direct3dRMFrameArray object if successful; otherwise, returns null.

Parameter | Description
index | The object to return. The index must be a value in the range of 0 to one less than the number returned by the getSize method.
desc | The D3dRMPickDesc object that receives the pick description.

getPickVisual

public Direct3dRMVisual getPickVisual(int index, D3dRMPickDesc desc);

Returns one of the Direct3dRMVisual objects associated with this object.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, returns null.

Parameter | Description
index | The object to return. The index must be a value in the range of 0 to one less than the number returned by the getSize method.
desc | The D3dRMPickDesc object that receives the pick description.

getSize

public int getSize();

Retrieves the number of Direct3dRMVisual and Direct3dRMFrameArray objects associated with this object.

Return Value:

Returns the number of objects.


Class Direct3dRMTexture

public class Direct3dRMTexture implements IDirect3dRMTexture
{
  // Methods
  public void changed(int pixels, int palette);
  public int getColors();
  public void getDecalOrigin(int[] x, int[] y);
  public int getDecalScale();
  public void getDecalSize(float[] w, float[] h);
  public int getDecalTransparency();
  public int getDecalTransparentColor();
  public Direct3dRMImage getImage();
  public void getImageBuffer(byte[] buffer1);
  public void getImagePalette(byte[] pal);
  public int getShades();
  public void setColors(int c);
  public void setDecalOrigin(int x, int y);
  public void setDecalScale(int s);
  public void setDecalSize(float width, float height);
  public void setDecalTransparency(int trans);
  public void setDecalTransparentColor(int tcolor);
  public void setShades(int s);
}

Applications use the methods of the Direct3dRMTexture class to work with textures, which are rectangular arrays of pixels.

The Direct3dRMTexture class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMTexture object is obtained by calling the createTexture method.

Methods

changed

public void changed(int pixels, int palette);

Informs the renderer that the application has changed the pixels or the palette of a texture.

Return Value:

No return value.

Parameter | Description
pixels | If this parameter is true, the pixels have changed.
palette | If this parameter is true, the palette has changed.

getColors

public int getColors();

Retrieves the maximum number of colors used for rendering a texture.

Return Value:

Returns the number of colors.

Remarks:

This method returns the number of colors that the texture has been quantized to, not the number of colors in the image that the texture was created from. Consequently, the number of colors that are returned usually matches the number ofcolors that were set by calling the setDefaultTextureColors method, unless you explicitly used the setColors method to change the colors for the texture.

See Also: setColors

getDecalOrigin

public void getDecalOrigin(int[] x, int[] y);

Retrieves the current origin of the decal.

Return Value:

No return value.

Parameter | Description
x | The array variables that receive the x coordinate of the origin of the decal.
y | The array variables that receive the y coordinate of the origin of the decal.

See Also: setDecalOrigin

getDecalScale

public int getDecalScale();

Retrieves the scaling property of the given decal.

Return Value:

Returns the scaling property if successful; otherwise, returns -1.

See Also: setDecalScale

getDecalSize

public void getDecalSize(float[] w, float[] h);

Retrieves the size of the decal.

Return Value:

No return value.

Parameter | Description
w | The addresses of variables that will be filled with the width of the decal when the method returns.
h | The addresses of variables that will be filled with the height of the decal when the method returns.

See Also: setDecalSize

getDecalTransparency

public int getDecalTransparency();

Retrieves the transparency property of the decal.

Return Value:

Returns true if the decal has a transparent color; otherwise, returns false.

See Also: setDecalTransparency

getDecalTransparentColor

public int getDecalTransparentColor();

Retrieves the transparent color of the decal.

Return Value:

Returns the value of the transparent color.

See Also: setDecalTransparentColor

getImage

public Direct3dRMImage getImage();

Retrieves the image that the texture is created with.

Return Value:

Returns the D3dRMImage object that the current texture was created with.

getImageBuffer

public void getImageBuffer(byte[] buffer1);

Retrieves the image buffer that the texture is created with.

Return Value:

No return value.

Parameter | Description
buffer1 | The image buffer.

getImagePalette

public void getImagePalette(byte[] pal);

Retrieves the image palette that the texture is created with.

Return Value:

No return value.

Parameter | Description
pal | The image palette.

getShades

public int getShades();

Retrieves the number of shades used for each color in the texture when rendering.

Return Value:

Returns the number of shades.

See Also: setShades

setColors

public void setColors(int c);

Sets the maximum number of colors used for rendering a texture. This method is required only in the ramp color model.

Return Value:

No return value.

Parameter | Description
c | The number of colors.

Remarks:

By default, the initial number of colors is 8.

See Also: getColors

setDecalOrigin

public void setDecalOrigin(int x, int y);

Sets the decal origin as an offset from the top left of the decal.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the new origin for the decal.
y | The y coordinate of the new origin for the decal.

Remarks:

The decal origin is mapped to its frame's position when rendering. For example, the origin of a decal of a cross would be set to the middle of the decal, and the origin of an arrow pointing down would be set to midway along the bottom edge.

By default, the initial decal origin is [0, 0].

See Also: getDecalOrigin

setDecalScale

public void setDecalScale(int s);

Sets the scaling property for a decal.

Return Value:

No return value.

Parameter | Description
s | If this parameter is true, depth is taken into account when the decal is scaled. If it is false, depth information is ignored.

Remarks:

By default, the initial decal scaling property is true.

See Also: getDecalScale

setDecalSize

public void setDecalSize(float width, float height);

Sets the size of the decal to be used if the decal is being scaled according to its depth in the scene.

Return Value:

No return value.

Parameter | Description
width | The new width of the decal, in model coordinates.
height | The new height of the decal, in model coordinates.

Remarks:

By default, the initial decal size is [1, 1].

See Also: getDecalSize

setDecalTransparency

public void setDecalTransparency(int trans);

Sets the transparency property of the decal.

Return Value:

No return value.

Parameter | Description
trans | If this parameter is true, the decal has a transparent color. If it is false, it has an opaque color.

Remarks:

By default, the initial transparency property is false.

See Also: getDecalTransparency

setDecalTransparentColor

public void setDecalTransparentColor(int tcolor);

Sets the transparent color for a decal.

Return Value:

No return value.

Parameter | Description
tcolor | The new transparent color.

Remarks:

By default, the initial transparent color is black.

See Also: getDecalTransparentColor

setShades

public void setShades(int s);

Sets the maximum number of shades to use for each color for the texture when rendering. This method is required only in the ramp color model.

Return Value:

No return value.

Parameter | Description
s | The new number of shades. This value must be a power of 2.

Remarks:

By default, the initial number of shades is 16.

See Also: getShades


Class Direct3dRMUserVisual

public class Direct3dRMUserVisual implements
            IDirect3dRMUserVisual
{
}

Applications use the Direct3dRMUserVisual class to manage user visual objects.

Note This class does not provide an init method. Use the Direct3dRM.createUserVisual method to create and initialize Direct3dRMUserVisual objects.

The Direct3dRMUserVisual class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName


Class Direct3dRMViewport

public class Direct3dRMViewport implements IDirect3dRMViewport
{
  // Methods
  public void clear();
  public void configure(int x, int y, int width, int height);
  public void forceUpdate(int x1, int y1, int x2, int y2);
  public float getBack();
  public Direct3dRMFrame getCamera();
  public Direct3dRMDevice getDevice();
  public Direct3dViewport getDirect3DViewport();
  public float getField();
  public float getFront();
  public int getHeight();
  public void getPlane(float[] l, float[] r, float[] b, float[] t);
  public int getProjection();
  public int getUniformScaling();
  public int getWidth();
  public int getX();
  public int getY();
  public void inverseTransform(D3dVector d, D3dRMVector4d s);
  public Direct3dRMPickedArray pick(int x, int y);
  public void render(Direct3dRMFrame f);
  public void setBack(float v);
  public void setCamera(Direct3dRMFrame f);
  public void setField(float v);
  public void setFront(float v);
  public void setPlane(float left, float right, float bottom, float
        top);
  public void setProjection(int val);
  public void setUniformScaling(int flag);
  public void transform(D3dRMVector4d d, D3dVector s);
}

Applications use the methods of the Direct3dRMViewport class to work with viewport objects.

The Direct3dRMViewport class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

Note This class does not provide an init method. Use the Direct3dRM.createViewport method to create and initialize Direct3dRMViewport objects.

Methods

clear

public void clear();

Clears the given viewport to the current background color.

Return Value:

No return value.

configure

public void configure(int x, int y, int width, int height);

Reconfigures the viewport origin and dimensions.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the new viewport position.
y | The y coordinate of the new viewport position.
width | The new width of the viewport (in pixels).
height | The new height of the viewport (in pixels).

Remarks:

This method carries out no action if x + width or y + height are greater than the width or height of the device, or if any of x, y, width, or height is less than zero.

forceUpdate

public void forceUpdate(int x1, int y1, int x2, int y2);

Forces an area of the viewport to be updated. The specified area will be copied to the screen at the next call to the update method.

Return Value:

No return value.

Parameter | Description
x1 | The updated area's upper-left x coordinate.
y1 | The updated area's upper-left y coordinate.
x2 | The updated area's lower-right y coordinate.
y2 | The updated area's lower-right y coordinate.

Remarks:

The system might update any region that is larger than the specified rectangle, including (possibly) the entire window.

getBack

public float getBack();

Retrieves the position of the viewport back clipping plane.

Return Value:

Returns a value describing the position of the plane.

See Also: setBack

getCamera

public Direct3dRMFrame getCamera();

Retrieves the camera for a viewport.

Return Value:

Returns the Direct3dRMFrame object if successful; otherwise, returns null.

See Also: setCamera

getDevice

public Direct3dRMDevice getDevice();

Retrieves the device associated with a viewport.

Return Value:

Returns the Direct3dRMDevice object if successful; otherwise, returns null.

getDirect3DViewport

public Direct3dViewport getDirect3DViewport();

Retrieves the Microsoft® Direct3D® viewport corresponding to the current Direct3dRMViewport object.

Return Value:

Returns the Direct3dViewport object if successful; otherwise, returns null.

getField

public float getField();

Retrieves the viewport's field of view.

Return Value:

Returns a value describing the viewport's field of view.

See Also: setField

getFront

public float getFront();

Retrieves the position of the viewport's front clipping plane.

Return Value:

Returns a value describing the position of the plane.

See Also: setFront

getHeight

public int getHeight();

Retrieves the height (measured in pixels) of the viewport.

Return Value:

Returns the height of the viewport (in pixels).

getPlane

public void getPlane(float[] l, float[] r, float[] b, float[] t);

Retrieves the dimensions of the viewport on the front clipping plane.

Return Value:

No return value.

Parameter | Description
l | The array variables that receive the left dimensions of the viewport on the front clipping plane.
r | The array variables that receive the right dimensions of the viewport on the front clipping plane.
b | The array variables that receive the bottom dimensions of the viewport on the front clipping plane.
t | The array variables that receive the top dimensions of the viewport on the front clipping plane.

See Also: setPlane

getProjection

public int getProjection();

Retrieves the viewport's projection type. A viewport can use either orthographic or perspective projection.

Return Value:

Returns a projection type value.

See Also: setProjection

getUniformScaling

public int getUniformScaling();

Retrieves the scaling property used to scale the viewing volume into the larger dimension of the window.

Return Value:

Returns true if the viewport scales uniformly; otherwise, returns false.

See Also: setUniformScaling

getWidth

public int getWidth();

Retrieves the width (measured in pixels) of the viewport.

Return Value:

Returns the width of the viewport (in pixels).

getX

public int getX();

Retrieves the x-offset of the start of the viewport on a device.

Return Value:

Returns the x-offset.

getY

public int getY();

Retrieves the y-offset of the start of the viewport on a device.

Return Value:

Returns the y-offset.

inverseTransform

public void inverseTransform(D3dVector d, D3dRMVector4d s);

Transforms the vector in the s parameter (measured in screen coordinates) to world coordinates and returns the result in the d parameter.

Return Value:

No return value.

Parameter | Description
d | A D3dVector object that receives the result of the operation.
s | A D3dRMVector4d object that contains the source of the operation.

pick

public Direct3dRMPickedArray pick(int x, int y);

Finds a depth-sorted list of objects (and faces, if relevant) that includes the path taken in the hierarchy, from the root down to the frame that contained the object.

Return Value:

Returns the Direct3dRMPickedArray object if successful; otherwise, returns null.

Parameter | Description
x | The x coordinate used for picking.
y | The y coordinate used for picking.

render

public void render(Direct3dRMFrame f);

Renders a frame hierarchy to the given viewport. Only those visuals on the given frame and any frames below it in the hierarchy are rendered.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object that represents the frame hierarchy to be rendered.

setBack

public void setBack(float v);

Sets the position of the back clipping plane for a viewport.

Return Value:

No return value.

Parameter | Description
v | The new position of the back clipping plane.

See Also: getBack, setFront

setCamera

public void setCamera(Direct3dRMFrame f);

Sets a camera for a viewport.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object that represents the camera.

Remarks:

This method sets viewport position, direction, and orientation to that of the given camera frame. The view is oriented along the positive z-axis of the camera frame, with the up direction being that of the positive y-axis.

See Also: getCamera

setField

public void setField(float v);

Sets the viewport field of view.

Return Value:

No return value.

Parameter | Description
v | The new field of view. If this value is less than or equal to zero, this method does not carry out an action.

Remarks:

By default, the initial field of view value is 0.5.

See Also: getField

setFront

public void setFront(float v);

Sets the position of the front clipping plane for a viewport.

Return Value:

No return value.

Parameter | Description
v | The new position of the front clipping plane. If the value passed is less than or equal to zero, this method does not carry out an action.

Remarks:

By default, the initial position is 1.0.

See Also: getFront

setPlane

public void setPlane(float left, float right, float bottom, float top);

Sets the dimensions of the viewport on the front clipping plane, relative to the camera's z-axis.

Return Value:

No return value.

Parameter | Description
left | The minimum x coordinate of the four sides of the viewport.
right | The maximum x coordinate of the four sides of the viewport.
bottom | The minimum y coordinate of the four sides of the viewport.
top | The maximum y coordinate of the four sides of the viewport.

Remarks:

Unlike the setField method, which specifies a centered proportional viewport, this method enables you to specify a viewport of arbitrary proportion and position. For example, this method could be used to construct a sheared viewing frustum to implement a right- or left-eye stereo view.

See Also: getPlane, setField

setProjection

public void setProjection(int val);

Sets the viewport projection.

Return Value:

No return value.

Parameter | Description
val | A projection type value.

See Also: getProjection

setUniformScaling

public void setUniformScaling(int flag);

Sets the scaling property used to scale the viewing volume into the larger dimension of the window.

Return Value:

No return value.

Parameter | Description
flag | The new scaling property. If this parameter is true, the same horizontal and vertical scaling factor is used to scale the viewing volume. Otherwise, different scaling factors are used to scale the viewing volume exactly into the window.

Remarks:

This method is typically used with the setPlane method to support banding.

By default, the initial scaling property is true.

See Also: getUniformScaling

transform

public void transform(D3dRMVector4d d, D3dVector s);

Transforms the vector in the s parameter (measured in world coordinates) to screen coordinates and returns the result in the d parameter.

Return Value:

No return value.

Parameter | Description
d | A D3dRMVector4d object that receives the result of the transformation operation.
s | A D3dVector object that contains the source for the transformation operation.

Remarks:

The result of the transformation is a four-element homogeneous vector.


Class Direct3dRMViewportArray

public class Direct3dRMViewportArray implements
            IDirect3dRMViewportArray
{
  // Methods
  public Direct3dRMViewport getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMViewportArray class to organize viewport objects.

The Direct3dRMViewportArray object is obtained by calling the Direct3dRM.createFrame method.

Methods

getElement

public Direct3dRMViewport getElement(int index);

Retrieves one of the Direct3dRMViewport objects associated with the current Direct3dRMViewportArray object.

Return Value:

Returns the Direct3dRMViewport object if successful; otherwise, returns null.

Parameter | Description
index | The identifier of the object to return. The index must be a value in the range of 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Retrieves the number of Direct3dRMViewport objects associated with the current Direct3dRMViewportArray object.

Return Value:

Returns the number of objects.


Class Direct3dRMVisual

public class Direct3dRMVisual implements IDirect3dRMVisual
{
  // Methods
  public Direct3dRMMeshBuilder getd3drmMeshBuilder();
}

Applications use the Direct3dRMVisual class when creating shadows or adding visuals to a frame.

This class supports the getd3drmMeshBuilder method.

In addition, the Direct3dRMFrame class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

Methods

getd3drmMeshBuilder

public Direct3dRMMeshBuilder getd3drmMeshBuilder();

Retrieves the mesh builder object associated with the current Direct3dRMVisual object.

Return Value:

Returns the Direct3dRMMeshBuilder object if successful; otherwise, returns null.


Class Direct3dRMVisualArray

public class Direct3dRMVisualArray implements
            IDirect3dRMVisualArray
{
  // Methods
  public Direct3dRMVisual getElement(int index);
  public int getSize();
}

Applications use the methods of the Direct3dRMVisualArray class to organize groups of visual objects.

The Direct3dRMVisualArray object is obtained by calling the Direct3dRMFrame.getVisuals method.

Methods

getElement

public Direct3dRMVisual getElement(int index);

Returns one of the Direct3dRMVisual objects associated with the current Direct3dRMVisualArray object.

Return Value:

Returns the Direct3dRMVisual object if successful; otherwise, returns null.

Parameter | Description
index | Identifies the object to return. The index must be a value in the range of 0 to one less than the number returned by the getSize method.

getSize

public int getSize();

Retrieves the number of Direct3dRMVisual objects associated with the current Direct3dRMVisualArray object.

Return Value:

Returns the number of objects.


Class Direct3dRMWinDevice

public class Direct3dRMWinDevice implements
            IDirect3dRMWinDevice
{
  // Methods
  public void handleActivate(int wparam);
  public void handlePaint(int hdc);
}

Applications use the methods of the Direct3dRMWinDevice class to respond to window messages in a window procedure.

In addition, the Direct3dRMWinDevice class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

The Direct3dRMWinDevice object is obtained by calling the getDirect3dRMWinDevice method or by calling a method such as createDeviceFromDirect3d.

Methods

handleActivate

public void handleActivate(int wparam);

Responds to a Microsoft® Windows® WM_ACTIVATE message. This method ensures that the colors in the active rendering window are correct.

Return Value:

No return value.

Parameter | Description
wparam | The WPARAM parameter is passed to the message-processing procedure with the WM_ACTIVATE message.

handlePaint

public void handlePaint(int hdc);

Handles painting updates.

Return Value:

No return value.

Parameter | Description
hdc | The device context (DC) handle.

Remarks:

This method should be called before repainting any application areas in the window because areas outside the viewports that have been created on the device may be repainted.


Class Direct3dRMWrap

public class Direct3dRMWrap implements IDirect3dRMWrap
{
  // Methods
  public void applyFace(Direct3dRMFace face);
  public void applyMesh(Direct3dRMMesh mesh);
  public void applyMeshBuilder(Direct3dRMMeshBuilder meshbuilder);
  public void applyRelative(Direct3dRMFrame f, Direct3dRMObject o);
}

Applications use the methods of the Direct3dRMWrap class to work with wrap objects.

In addition, the Direct3dRMWrap class inherits the following methods from the Direct3dRMObject class:

addDestroyCallback
duplicate
deleteDestroyCallback
getAppData
getClassName
getName
setAppData
setName

Note This class does not provide an init method. Use the Direct3dRM.createWrap method to create and initialize Direct3dRMWrap objects.

Note Wrap objects wrap a two dimensional surface to a three dimensional object. If you are using DirectX3 on the native side, wrap objects may not behave as expected. If you are using DirectX5, you should not encounter problems.

Methods

applyFace

public void applyFace(Direct3dRMFace face);

Applies a Direct3dRMWrap object to a destination Direct3dRMFace object.

Return Value:

No return value.

Parameter | Description
face | The destination object.

See Also: com.ms.directX.Direct3dRM

applyMesh

public void applyMesh(Direct3dRMMesh mesh);

Applies a Direct3dRMWrap object to a destination Direct3dRMMesh object.

Return Value:

No return value.

Parameter | Description
mesh | The destination object.

See Also: com.ms.directX.Direct3dRM

applyMeshBuilder

public void applyMeshBuilder(Direct3dRMMeshBuilder meshbuilder);

Applies a Direct3dRMWrap object to a destination Direct3dRMMeshBuilder object.

Return Value:

No return value.

Parameter | Description
meshbuilder | The destination object.

See Also: com.ms.directX.Direct3dRM

applyRelative

public void applyRelative(Direct3dRMFrame f, Direct3dRMObject o);

Applies the wrap to the vertices of the object. First it transforms each vertex by the frame's world transformation. Then it transforms each vertex by the inverse world transformation of the wrap's reference frame.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object containing the object to wrap.
o | The Direct3dRMWrap object to apply.

See Also: com.ms.directX.Direct3dRM


Class Direct3dTexture

public class Direct3dTexture implements IDirect3dTexture
{
  // Methods
  public void getHandle(Direct3dDevice dev);
  public void initialize(Direct3dDevice dev,
        DirectDrawSurface surf);
  public void load(Direct3dTexture tex);
  public void paletteChanged(int start, int count);
  public void unload();
}

Applications use the methods of the Direct3dTexture class to retrieve and set texture properties.

Methods

getHandle

public void getHandle(Direct3dDevice dev);

Obtains the texture handle for the Direct3dTexture object. This handle is used in all Microsoft® Direct3D® API calls where a texture is to be referenced.

Return Value:

No return value.

Parameter | Description
dev | The Direct3dDevice object that the texture is to be loaded into.

initialize

public void initialize(Direct3dDevice dev, DirectDrawSurface surf);

Initializes the Direct3dTexture object.

Return Value:

No return value.

Parameter | Description
dev | The device representing the Direct3D object.
surf | The DirectDrawSurface for this object.

load

public void load(Direct3dTexture tex);

Loads a texture that was created with the DDSCAPS_ALLOCONLOAD flag, which indicates that memory for the DirectDraw surface is not allocated until the surface is loaded by using this method.

Return Value:

No return value.

Parameter | Description
tex | The texture to load.

See Also: unload

paletteChanged

public void paletteChanged(int start, int count);

Informs the driver that the palette has changed on a surface.

Return Value:

No return value.

Parameter | Description
start | The index of the first palette entry that has changed.
count | The number of palette entries that have changed.

Remarks:

This method is particularly useful for applications that play video clips and therefore require palette-changing capabilities.

unload

public void unload();

Unloads the current texture.

Return Value:

No return value.

See Also: load


Class Direct3dViewport

public class Direct3dViewport implements IDirect3dViewport
{
  // Methods
  public void addLight(Direct3dLight light);
  public void clear(int count, D3dRect rec, int flags);
  public void deleteLight(Direct3dLight light);
  public void getBackground(int[] hdl, int[] stat);
  public DirectDrawSurface getBackgroundDepth(int[] status);
  public void getViewport(D3dViewportDesc vp);
  public Direct3dLight nextLight(Direct3dLight l1, int flags);
  public void setBackground(int hdl);
  public void setBackgroundDepth(IDirectDrawSurface surface);
  public void setViewport(D3dViewportDesc vp);
}

Applications use the methods of the Direct3dViewport class to retrieve and set the properties of viewports.

Note This class does not provide an initialize method. Use the Direct3d.createViewport() method to create and initialize Direct3dViewport objects.

Methods

addLight

public void addLight(Direct3dLight light);

Adds a Direct3dLight light object to the viewport.

Return Value:

No return value.

Parameter | Description
light | The Direct3dLight object to add.

clear

public void clear(int count, D3dRect rec, int flags);

Clears the viewport or a set of rectangles in the viewport to the current background material.

Return Value:

No return value.

Parameter | Description
count | The number of rectangles pointed to by rec.
rec | A D3dRect object.
flags | One or more values of D3DCLEAR_ type, indicating what to clear: the rendering target, the z-buffer, or both.

deleteLight

public void deleteLight(Direct3dLight light);

Deletes a Direct3dLight light object from the viewport.

Return Value:

No return value.

Parameter | Description
light | The Direct3dLight object to delete.

getBackground

public void getBackground(int[] hdl, int[] stat);

Retrieves the handle of a material that represents the current viewport background.

Return Value:

No return value.

Parameter | Description
hdl | The array variable that receives the handle of the material being used as the background.
stat | The array variable that receives a value, indicating whether a background is associated with the viewport. If this value is FALSE, a background is not associated with the viewport.

See Also: setBackground

getBackgroundDepth

public DirectDrawSurface getBackgroundDepth(int[] status);

Retrieves a DirectDraw surface that represents the current background-depth field associated with the viewport.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

Parameter | Description
status | The array variable that receives the value FALSE if a background depth is not associated with the viewport.

See Also: setBackgroundDepth

getViewport

public void getViewport(D3dViewportDesc vp);

Retrieves the viewport registers.

Return Value:

No return value.

Parameter | Description
vp | A D3dViewportDesc object that receives values for the viewport.

See Also: setViewport

nextLight

public Direct3dLight nextLight(Direct3dLight l1, int flags);

Retrieves a light from a Direct3dViewport, according to the specified flags.

Return Value:

Returns the requested Direct3dLight object.

Parameter | Description
l1 | This may be null if the flags constant is either D3DNEXT_HEAD or D3DNEXT_TAIL.
flags This may be one of the following values:
D3DNEXT_HEAD
D3DNEXT_TAIL
D3DNEXT_NEXT

setBackground

public void setBackground(int hdl);

Sets the background associated with the viewport.

Return Value:

No return value.

Parameter | Description
hdl | The material handle that will be used as the background.

See Also: getBackground

setBackgroundDepth

public void setBackgroundDepth(IDirectDrawSurface surface);

Sets the viewport background depth field.

Return Value:

No return value.

Parameter | Description
surface | The DirectDrawSurface object representing the background depth.

Remarks:

The z-buffer is filled with the specified depth field when the clear method is called and the D3DCLEAR_ZBUFFER flag is specified. The bit depth must be 16 bits.

See Also: getBackgroundDepth

setViewport

public void setViewport(D3dViewportDesc vp);

Sets the viewport registers.

Return Value:

No return value.

Parameter | Description
vp | A D3dViewportDesc object that contains the new viewport.

See Also: getViewport


Class DirectDraw

public class DirectDraw implements IDirectDraw
{
  // Methods
  public DirectDrawClipper createClipper(int flags);
  public Direct3d createD3D();
  public DirectDrawPalette createPalette(int flags, byte[] pe);
  public DirectDrawPalette createPalette(int flags);
  public DirectDrawPalette createPalette(int flags, Color[] pe);
  public DirectDrawPalette createPalette(int flags,
        PaletteEntry[] pe);
  public DirectDrawSurface createSurface(DDSurfaceDesc dd);
  public DirectDrawSurface duplicateSurface(DirectDrawSurface ddIn);
  public void enumDisplayModes(int d, DDSurfaceDesc s,
        IUnknown args, IEnumModesCallback fn);
  public void flipToGDISurface();
  public int getAvailableTotalMem(int[] ddsCaps);
  public void getCaps(DDCaps driverCaps, DDCapsFx driverCapsFx,
        DDCaps helCaps, DDCapsFx helCapsFx);
  public void getDisplayMode(DDSurfaceDesc surface);
  public int getFourCCCodes(int[] size);
  public int getFreeMem(int [] ddsCaps);
  public DirectDrawSurface getGDISurface();
  public int getMonitorFrequency();
  public int getNumFourCCCodes();
  public int getScanLine();
  public int getVerticalBlankStatus();
  public DirectDrawPalette loadPaletteFromBitmap(String bName);
  public void restoreDisplayMode();
  public void setCooperativeLevel(Component c, int flags);
  public void setCooperativeLevel(int hdl, int flags);
  public void setDisplayMode(int w, int h, int bpp, int ref,
        int mode);
  public int systemBpp();
  public int tickCount();
  public void waitForVerticalBlank(int flags, int handle);
}

Applications use the methods of the DirectDraw class to create Microsoft® DirectDraw® objects and work with system-level variables.

Methods

createClipper

public DirectDrawClipper createClipper(int flags);

Creates a DirectDrawClipper object.

Return Value:

Returns the DirectDrawClipper object if successful; otherwise, returns null.

Parameter | Description
flags | This parameter is currently not used and must be set to 0.

Remarks:

The DirectDrawClipper object can be attached to a DirectDrawSurface and used during blt and updateOverlay operations.

See Also: com.ms.directX.DirectDrawSurface

createD3D

public Direct3d createD3D();

Creates a Microsoft® Direct3D® object.

Return Value:

Returns the Direct3d object if successful; otherwise, returns null.

createPalette

public DirectDrawPalette createPalette(int flags, byte[] pe);

Creates a DirectDrawPalette object for this DirectDraw object.

Return Value:

Returns the DirectDrawPalette object if successful; otherwise, returns null.

Parameter | Description
flags | One or more values of the DDPCAPS_ type.
pe | The array variable that contains the data describing the initial value for each palette entry.

createPalette

public DirectDrawPalette createPalette(int flags);

Creates a palette and fills it with standard halftone entries.

Return Value:

Returns the DirectDrawPalette object if successful; otherwise, returns null. Currently, only DDPCAPS_8BIT and DDPCAPS_INITIALIZE are valid arguments for the flags parameter.

Parameter | Description
flags | One or more values of DDPCAPS_ type.

createPalette

public DirectDrawPalette createPalette(int flags, Color[] pe);

Creates a DirectDrawPalette object for this DirectDraw object.

Return Value:

Returns the DirectDrawPalette object if successful; otherwise, returns null.

Parameter | Description
flags | One or more values of the DDPCAPS_ type.
pe | The array variable that contains the data describing the initial color value for each palette entry.

createPalette

public DirectDrawPalette createPalette(int flags, PaletteEntry[] pe);

Creates a DirectDrawPalette object for this DirectDraw object.

Return Value:

Returns the DirectDrawPalette object if successful; otherwise, returns null.

Parameter | Description
flags | One or more values of DDPCAPS_ type.
pe | The array variable that contains a PaletteEntry object describing each palette entry.

createSurface

public DirectDrawSurface createSurface(DDSurfaceDesc dd);

Creates a DirectDrawSurface object for this DirectDraw object.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

Parameter | Description
dd | The DDSurfaceDesc object that describes the requested surface.

duplicateSurface

public DirectDrawSurface duplicateSurface(DirectDrawSurface ddIn);

Duplicates a DirectDrawSurface object.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

Parameter | Description
ddIn | The DirectDrawSurface object to be duplicated.

Remarks:

This method creates a new DirectDrawSurface object that represents the same surface memory as an existing DirectDrawSurface object. This duplicate can be used just like the original object. The surface memory is released after the last object referencing it is released. A primary surface, 3D surface, or implicitly created surface cannot be duplicated.

enumDisplayModes

public void enumDisplayModes(int d, DDSurfaceDesc s, IUnknown args,
        IEnumModesCallback fn);

Enumerates all of the display modes the hardware exposes through the DirectDraw object that are compatible with a provided surface description. If null is passed for the surface description, all exposed modes are enumerated.

Return Value:

No return value.

Parameter | Description
d | This flag Can be DDEDM_REFRESHRATES.
s | A DDSurfaceDesc object that will be checked against available modes. If the value of this parameter is null, all modes are enumerated.
args | Application-defined data that will be passed to each enumeration member.
fn | The callback interface containing the callback function that the enumeration procedure will call every time a match is found.

Remarks:

This method enumerates the backBufferCount field of the DDSurfaceDesc class. If you use the setDisplayMode method to set the refresh rate of a new mode, you must use enumDisplayModes to enumerate the backBufferCount field.

See Also: getDisplayMode, setDisplayMode, restoreDisplayMode

flipToGDISurface

public void flipToGDISurface();

Makes the surface that GDI writes to the primary surface.

Return Value:

No return value.

Remarks:

This method can be called at the end of a page-flipping application to ensure that the display memory that the GDI is writing to is visible to the user.

See Also: getGDISurface

getAvailableTotalMem

public int getAvailableTotalMem(int[] ddsCaps);

Retrieves the total available amount of display memory.

Return Value:

Returns the amount of memory.

Parameter | Description
ddsCaps | An array of the values found in the DDSCaps class.

Remarks:

A display adapter card may make no distinction between two different memory types.

For example, the adapter might use the same portion of display memory to store z-buffers and textures. So, allocating one type of surface (for example, a z-buffer) can affect the amount of display memory available for another type of surface (for example, textures). Therefore, it is best to first allocate an application's fixed resources (such as front, back, and z-buffers) before determining how much memory is available for dynamic use, such as texture mapping.

getCaps

public void getCaps(DDCaps driverCaps, DDCapsFx driverCapsFx,
        DDCaps helCaps, DDCapsFx helCapsFx);

Fills in the capabilities of the device driver for the hardware and the hardware emulation layer (HEL).

Return Value:

No return value.

Parameter | Description
driverCaps | A DDCaps object that receives the capabilities of the hardware, as reported by the device driver.
driverCapsFx | A DDCapsFx object that receives the capabilities of the hardware, as reported by the device driver. The DDCapsFx class is used with classes that contain more than 256 bytes of member data.
helCaps | A DDCaps object that receives the capabilities of the HEL.
helCapsFx | A DDCapsFx object that receives the capabilities of the HEL. The DDCapsFx class is used with classes that contain more than 256 bytes of member data.

getDisplayMode

public void getDisplayMode(DDSurfaceDesc surface);

Retrieves the current display mode.

Return Value:

No return value.

Parameter | Description
surface | A DDSurfaceDesc object that receives a description of the surface.

Remarks:

An application should not save the information returned by this method to restore the display mode on clean-up. The application should use the restoreDisplayMode method to restore the mode on clean-up, which avoids mode-setting conflicts that could arise in a multiprocess environment.

See Also: setDisplayMode, restoreDisplayMode, enumDisplayModes

getFourCCCodes

public int getFourCCCodes(int[] size);

Retrieves the FourCC codes supported by the DirectDraw object. This method can also retrieve the number of codes supported.

Return Value:

Returns an address of an array that contains the codes.

Parameter | Description
size | The array variable that receives the FourCC codes supported by this DirectDraw object.

getFreeMem

public int getFreeMem(int [] ddsCaps);

Retrieves the amount of display memory currently free.

Return Value:

Returns the amount of free display memory.

Parameter | Description
ddsCaps | An array of the values found in the DDSCaps class.

Remarks:

This method provides only a snapshot of the current display-memory state. The amount of free display memory is subject to change as surfaces are created and released. Therefore, you should use the free memory value only as an approximation.

getGDISurface

public DirectDrawSurface getGDISurface();

Retrieves the DirectDrawSurface object that currently represents the surface memory that the Graphical Device Interface (GDI) is treating as the primary surface.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

See Also: flipToGDISurface

getMonitorFrequency

public int getMonitorFrequency();

Retrieves the frequency of the monitor being driven by the DirectDraw object. The frequency value is returned in Hz multiplied by 100. For example, 60Hz is returned as 6000.

Return Value:

Returns the monitor frequency.

getNumFourCCCodes

public int getNumFourCCCodes();

Retrieves the number of FourCC codes in the array getFourCCCodes specifies.

Return Value:

Returns the number of FourCCCodes.

getScanLine

public int getScanLine();

Retrieves the scan line that is currently being drawn on the monitor.

Return Value:

Returns the scan line.

See Also: getVerticalBlankStatus, waitForVerticalBlank

getVerticalBlankStatus

public int getVerticalBlankStatus();

Retrieves the status of the vertical blank.

Return Value:

Returns 1 if a vertical blank is occurring; otherwise, returns 0.

Remarks:

To synchronize with the vertical blank, use the waitForVerticalBlank method.

See Also: getScanLine, waitForVerticalBlank

loadPaletteFromBitmap

public DirectDrawPalette loadPaletteFromBitmap(String bName);

Loads a palette.

Return Value:

Returns the DirectDrawPalette object if successful; otherwise, returns null.

Parameter | Description
bName | Name of the bitmap that contains the palette to load.

restoreDisplayMode

public void restoreDisplayMode();

Resets the mode of the display device hardware for the primary surface to what it was before the setDisplayMode method was called. Exclusive-level access is required to use this method.

Return Value:

No return value.

See Also: setDisplayMode, enumDisplayModes, setCooperativeLevel

setCooperativeLevel

public void setCooperativeLevel(Component c, int flags);

Determines the top-level behavior of the application (the primary method that does so).

Return Value:

No return value.

Parameter | Description
c | The Component used for the application.
flags | One or more values of DDSCL_ type.

Remarks:

You must call the show() or addNotify() method before calling setCooperativeLevel

See Also: setDisplayMode, compact, enumDisplayModes

setCooperativeLevel

public void setCooperativeLevel(int hdl, int flags);

Serves as a helper for the setCooperativeLevel(Component, int) method and remains for use by more advanced programmers. The setCooperativeLevel method also determines the top-level behavior of the application.

Return Value:

No return value.

Parameter | Description
hdl | The Microsoft® Windows® handle used for the application. Applications can use DirectDraw with multiple windows. Therefore, setCooperativeLevel does not require a window handle to be specified if the application is requesting the DDSCL_NORMAL mode. By passing a null to the window handle, all the windows can be used simultaneously in normal Windows mode.
flags | One or more values of the DDSCL_ type.

See Also: setDisplayMode, compact, enumDisplayModes

setDisplayMode

public void setDisplayMode(int w, int h, int bpp, int ref, int mode);

Sets the mode of the display-device hardware.

Return Value:

No return value.

Parameter | Description
w | The width of the new mode.
h | The height of the new mode.
bpp | The bits per pixel of the new mode.
ref | The refresh rate of the new mode.
mode | Reserved; value must be 0.

Remarks:

The setCooperativeLevel method must be used to set exclusive-level access before the mode can be changed. If other applications have created a DirectDrawSurface object on the primary surface and the mode is changed, those applications' primary surface objects return DDERR_SURFACELOST until they are restored.

See Also: restoreDisplayMode, getDisplayMode, enumDisplayModes, setCooperativeLevel

systemBpp

public int systemBpp();

Retrieves the current system's bits-per-pixel value.

Return Value:

Returns the bits-per-pixel value.

tickCount

public int tickCount();

Retrieves the current tick count.

Return Value:

Returns the tick count.

waitForVerticalBlank

public void waitForVerticalBlank(int flags, int handle);

Assists the application tosynchronize itself with the vertical-blank interval.

Return Value:

No return value.

Parameter | Description
flags | One value of DDWAITVB_ type; flag specifies how long to wait for the vertical blank.
handle | The handle of the event to be triggered when the vertical blank begins.

See Also: getVerticalBlankStatus, getScanLine


Class DirectDrawBitmap

public class DirectDrawBitmap implements IDirectDrawBitmap
{
  // Methods
  public void filename(String val);
  public int height();
  public void initHeight(int val);
  public void initWidth(int val);
  public int loaded();
  public int width();
}

Applications use the DirectDrawBitmap class to create and manage bitmaps.

Methods

filename

public void filename(String val);

Sets the name of the file containing the bitmap data.

Return Value:

No return value.

Parameter | Description
val | The name of the bitmap file.

height

public int height();

Retrieves the actual height of the bitmap.

Return Value:

Returns the height, in pixels.

initHeight

public void initHeight(int val);

Sets the initial height of the bitmap.

Return Value:

No return value.

Parameter | Description
val | The initial height, in pixels.

initWidth

public void initWidth(int val);

Initializes the width of the bitmap.

Return Value:

No return value.

Parameter | Description
val | The initial width, in pixels.

loaded

public int loaded();

Indicates whether the bitmap data has been loaded.

Return Value:

Returns 1 if loaded, 0 otherwise.

width

public int width();

Retrieves the actual width of the bitmap.

Return Value:

Returns the width in pixels.


Class DirectDrawClipper

public class DirectDrawClipper implements IDirectDrawClipper
{
  // Methods
  public void getClipList(Rect rec, int [] rects, int count,
        Rect boundingrect);
  public int getClipListSize(Rect rec);
  public int getHWnd();
  public void initialize(DirectDraw dd, int flags);
  public int isClipListChanged();
  public void setClipList(Rect rec, int [] rects, int count);
  public void setComponent(Component c);
  public void setHWnd(int flags, int hdl);
  public void setOffset(int x, int y);
  public void setSurfaceOffset(Point point);
  public void setSurfaceVisRgn(Region visRgn);
}

Applications use the methods of the DirectDrawClipper class to manage clip lists.

Methods

getClipList

public void getClipList(Rect rec, int [] rects, int count,
        Rect boundingrect);

Retrieves a copy of the clip list associated with a DirectDrawClipper object. A subset of the clip list can be selected by passing a rectangle that clips the clip list.

Return Value:

No return value.

Parameter | Description
rec | A Rect object that is used to clip the clip list.
rects | An int array containing a list of rectangle dimensions.
count | The number of rectangles in the array.
boundingrect | The bounding rectangle.

See Also: setClipList

getClipListSize

public int getClipListSize(Rect rec);

Retrieves the size of the portion of the clip list contained with the given rectangle.

Return Value:

Returns the clip list size.

Parameter | Description
rec | A Rect object that is used to clip the clip list.

getHWnd

public int getHWnd();

Retrieves the window handle previously associated with this DirectDrawClipper object by the setHWnd method.

Return Value:

Returns The window handle.

See Also: setHWnd

initialize

public void initialize(DirectDraw dd, int flags);

Initializes a DirectDrawClipper object.

Return Value:

No return value.

Parameter | Description
dd | The DirectDraw object. If this parameter is set to null, an independent DirectDrawClipper object is created.
flags | Reserved; the value must be 0.

See Also: com.ms.directX.DirectDraw

isClipListChanged

public int isClipListChanged();

Monitors the status of the clip list if a window handle is associated with a DirectDrawClipper object.

Return Value:

Returns true if the clip list has changed.

setClipList

public void setClipList(Rect rec, int [] rects, int count);

Sets or deletes the clip list used by the blt and updateOverlay methods on surfaces that the parent DirectDrawClipper object is attached to.

Return Value:

No return value.

Parameter | Description
rec | A Rect object that is used to clip the clip list.
rects | An int array containing a list of rectangle dimensions.
count | The number of rectangles in the list.

Remarks:

The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object. Note that the bltFast method cannot clip.

See Also: getClipList

setComponent

public void setComponent(Component c);

Associates the surface object with a top-level Java component.

Return Value:

No return value.

Parameter | Description
c | The component to link the DirectDrawClipper object to.

setHWnd

public void setHWnd(int flags, int hdl);

Sets the window handle that will obtain the clipping information.

Return Value:

No return value.

Parameter | Description
flags | Reserved; the value must be 0.
hdl | The window handle that obtains the clipping information.

See Also: getHWnd

setOffset

public void setOffset(int x, int y);

Calls to native code to translate a surface to new coordinates.

Return Value:

No return value.

Parameter | Description
x | The new x coordinate to offset the surface to.
y | The new y coordinate to offset the surface to.

setSurfaceOffset

public void setSurfaceOffset(Point point);

Translates a surface to new coordinates.

Return Value:

No return value.

Parameter | Description
point | The new point to offset the surface to.

setSurfaceVisRgn

public void setSurfaceVisRgn(Region visRgn);

Sets a visible region for the surface.

Return Value:

No return value.

Parameter | Description
visRgn | The region to set for the surface.


Class DirectDrawPalette

public class DirectDrawPalette implements IDirectDrawPalette
{
  // Methods
  public int getCaps();
  public Color[] getColorEntries(int flags, int start, int count);
  public void getEntries(int flags, int start, int count,
        byte[] val);
  public PaletteEntry[] getPaletteEntries(int flags, int start, int
        count);
  public void setEntries(int flags, int start, int count,
        byte[] val);
  public void setEntries(int flags, int start, int count,
        Color c[]);
  public void setEntries(int flags, int start, int count,
        PaletteEntry pe[]);
  public void setEntriesHalftone(int start, int count);
  public void setEntriesSystemPalette(int start, int count);
}

Applications use the methods of the DirectDrawPalette class to create Microsoft® DirectDraw® palette objects and work with system-level variables.

Note This class does not provide an initialize method. Use the DirectDraw.createPalette method to create and initialize DirectDrawPalette objects.

Methods

getCaps

public int getCaps();

Retrieves the capabilities of this palette object.

Return Value:

Returns one value of the DDPCAPS_ type.

getColorEntries

public Color[] getColorEntries(int flags, int start, int count);

Queries palette values from a DirectDrawPalette object and returns the color values associated with each entry.

Return Value:

Returns an array that contains the color values for the requested entries.

Parameter | Description
flags | Reserved; the value must be 0.
start | The beginning of the entries that should be sequentially retrieved.
count | The number of palette entries to retrieve. The colors of each palette entry are returned in sequence, from the value of the start parameter through the value of the count parameter minus 1.

See Also: getEntries, getPaletteEntries

getEntries

public void getEntries(int flags, int start, int count, byte[] val);

Queries palette values from a DirectDrawPalette object.

Return Value:

No return value.

Parameter | Description
flags | Reserved; the value must be 0.
start | The beginning of the entries that should be sequentially retrieved.
count | Number of palette entries that can fit in the object-specified val. The colors of each palette entry are returned in sequence, from the value of the start parameter through the value of the count parameter minus 1.
val | The array variable that receives the palette entries. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag is set; otherwise, entries are 4 bytes each. Each entry is a color description.

See Also: setEntries

getPaletteEntries

public PaletteEntry[] getPaletteEntries(int flags, int start, int count);

Queries palette values from a DirectDrawPalette object and returns a PaletteEntry object that represents each entry.

Return Value:

Returns an array of objects that contain the requested entries.

Parameter | Description
flags | Reserved; the value must be 0.
start | The beginning of the entries that should be sequentially retrieved.
count | The number of palette entries to retrieve. Each palette entry is returned in sequence, from the value of the start parameter through the value of the count parameter minus 1.

See Also: getColorEntries, getEntries

setEntries

public void setEntries(int flags, int start, int count, byte[] val);

Immediately changes entries in a DirectDrawPalette object. The palette must have been attached to a surface by using the setPalette method before setEntries can be used.

Return Value:

No return value.

Parameter | Description
flags | Reserved; the value must be 0.
start | The first entry to be set.
count | The number of palette entries to be changed.
val | The array variable that contains the palette entries. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag is set; otherwise, entries are 4 bytes each. Each entry is a color description.

See Also: getEntries, com.ms.directX.DirectDrawSurface

setEntries

public void setEntries(int flags, int start, int count, Color c[]);

Immediately changes entries in a DirectDrawPalette object. The palette must have been attached to a surface by using the setPalette method before setEntries can be used.

Return Value:

No return value.

Parameter | Description
flags | Reserved; the value must be 0.
start | The first entry to be set.
count | The number of palette entries to be changed.
c | The array variable that contains the new color values for each entry.

See Also: getEntries, com.ms.directX.DirectDrawSurface

setEntries

public void setEntries(int flags, int start, int count, PaletteEntry pe[]);

Immediately changes entries in a DirectDrawPalette object. The palette must have been attached to a surface by using the setPalette method before setEntries can be used.

Return Value:

No return value.

Parameter | Description
flags | Reserved; the value must be 0.
start | The first entry to be set.
count | The number of palette entries to be changed.
pe | The array variable that contains the PaletteEntry objects that define the new values for each entry.

See Also: getEntries, com.ms.directX.DirectDrawSurface

setEntriesHalftone

public void setEntriesHalftone(int start, int count);

Fills the palette in with standard halftone entries.

Return Value:

No return value.

Parameter | Description
start | The starting position in the palette to place the values.
count | The number of entries to add to the palette.

setEntriesSystemPalette

public void setEntriesSystemPalette(int start, int count);

Fills the entries in the palette with the values in the current system palette.

Return Value:

No return value.

Parameter | Description
start | The starting position in the palette to place the values.
count | The number of entries to add to the palette.


Class DirectDrawSurface

public class DirectDrawSurface implements IDirectDrawSurface
{
  // Methods
  public void addAttachedSurface(DirectDrawSurface ddS);
  public void addOverlayDirtyRect(Rect r);
  public int blt(Rect dest, DirectDrawSurface ddS, Rect src,
        int flags);
  public int bltColorFill(Rect dest, int fillValue);
  public int bltFast(int dx, int dy, DirectDrawSurface ddS,
        Rect src, int trans);
  public int bltFx(Rect dest, DirectDrawSurface ddS, Rect src,
        int flags, DDBltFx bltFx);
  public void copyBitmap(DirectDrawBitmap val, int cx, int cy,
        int dx, int dy);
  public Direct3dDevice create3DDevice(_Guid g);
  public void deleteAttachedSurface(int flags,
        DirectDrawSurface ddS);
  public void enumAttachedSurfaces(IUnknown args,
        IEnumSurfacesCallback fn);
  public void enumOverlayZOrders(int flags, IUnknown args,
        IEnumZOrdersCallback fn);
  public void flip(DirectDrawSurface ddS, int flags);
  public DirectDrawSurface getAttachedSurface(int caps);
  public int getBltStatus(int flags);
  public int getCaps();
  public DirectDrawClipper getClipper();
  public void getColorKey(int flags, DDColorKey val);
  public int getDC();
  public IUnknown getDDInterface();
  public int getFlipStatus(int flags);
  public int getOverlayPositionX();
  public int getOverlayPositionY();
  public DirectDrawPalette getPalette();
  public void getPixelFormat(DDPixelFormat pf);
  public void getSurfaceDesc(DDSurfaceDesc surface);
  public int isLost();
  public void lock(Rect r, DDSurfaceDesc d, int flags, int hnd,
        byte[] memory);
  public void releaseDC(int hdc);
  public int restore();
  public void setClipper(DirectDrawClipper val);
  public void setColorKey(int flags, DDColorKey val);
  public void setOverlayPosition(int x, int y);
  public void setPalette(DirectDrawPalette ddp);
  public void unlock(Rect r, DDSurfaceDesc d, byte[] memory);
  public void updateOverlay(Rect r, DirectDrawSurface ddS, Rect d,
        int flags);
  public void updateOverlayDisplay(int flags);
  public void updateOverlayZOrder(int flags, DirectDrawSurface ddS);
}

Applications use the methods of the DirectDrawSurface class to create Microsoft® DirectDraw® surface objects and work with system-level variables.

Note This class does not provide an initialize method. Use the DirectDraw.createSurface method to create and initialize DirectDrawSurface objects.

Methods

addAttachedSurface

public void addAttachedSurface(DirectDrawSurface ddS);

Attaches a surface to another surface.

Return Value:

No return value.

Parameter | Description
ddS | The DirectDrawSurface object to attach.

See Also: deleteAttachedSurface, enumAttachedSurfaces, flip

addOverlayDirtyRect

public void addOverlayDirtyRect(Rect r);

Builds the list of the rectangles that need to be updated the next time the updateOverlayDisplay method is called.

Return Value:

No return value.

Parameter | Description
r | The Rect object that needs to be updated.

Remarks:

This method is used for the software implementation. It is not needed if the overlay support is provided by the hardware.

See Also: updateOverlayDisplay

blt

public int blt(Rect dest, DirectDrawSurface ddS, Rect src, int flags);

Performs a bit block transfer.

Return Value:

Returns S_OK or 0 if the blit was set successfully; otherwise, returns an HRESULT error code. Use the DDBLT_WAIT flag to modify the return behavior as previously discussed.

Parameter | Description
dest | A Rect object that defines the upper-left and lower-right points of the rectangle on the destination surface to be blitted to.
ddS | The DirectDrawSurface object that is the source for the blit operation.
src | A Rect object that defines the upper-left and lower-right points of the rectangle on the source surface to be blitted from.
flags One or more of these values:
DDCOOPERATIVE_CLIPTOCOMPONENT or
DDCOOPERATIVE_OFFSETTOCOMPONENT
DDBLT_ALPHADEST
DDBLT_ASYNC
DDBLT_ALPHADESTNEG
DDBLT_KEYDEST
DDBLT_ALPHASRC
DDBLT_KEYSRC
DDBLT_ALPHASRCNEG
DDBLT_WAIT

Remarks:

This method is capable of synchronous or asynchronous blits, either display memory to display memory, display memory to system memory, system memory to display memory, or system memory to system memory. The blits can be performed by using z-information, alpha information, source color keys, and destination color keys. Arbitrary stretching or shrinking will be performed if the source and destination rectangles are not the same size.

Typically, blt returns immediately with an error if the blitter is busy and the blit could not be set up. The DDBLT_WAIT flag can alter this behavior so that the method will either wait until the blit can be set up or another error occurs before it returns.

bltColorFill

public int bltColorFill(Rect dest, int fillValue);

Fills the given rectangle on the surface with the given fill value.

Return Value:

Returns S_OK or 0 if the operation is successful; otherwise, returns an error code.

Parameter | Description
dest | A Rect object that defines the upper-left and lower-right points of the rectangle on the destination surface to be filled.
fillvalue | The fill value to fill the rectangle with.

bltFast

public int bltFast(int dx, int dy, DirectDrawSurface ddS, Rect src,
        int trans);

Performs a source copy blit or transparent blit by using a source color key or destination color key. This method always attempts an asynchronous blit if it is supported by the hardware.

Return Value:

Returns S_OK or 0 if the operation is successful; otherwise, returns an error code.

Parameter | Description
dx
dy | The x and y coordinates to blit to on the destination surface.
ddS | The DirectDrawSurface object that is the source for the blit operation.
src | The Rect object that defines the upper-left and lower-right points of the rectangle on the source surface to be blitted from.
trans | One value of DDBLTFAST_ type, specifying the type of transfer.

Remarks:

This method works only on display memory surfaces and cannot clip when blitting. The software implementation of bltFast is 10 percent faster than the blt method. However, there is no speed difference between the two if display hardware is being used.

Typically, bltFast returns immediately with an error if the blitter is busy and the blit cannot be set up. You can use the DDBLTFAST_WAIT flag, however, if you want this method to not return until either the blit can be set up or another error occurs.

bltFx

public int bltFx(Rect dest, DirectDrawSurface ddS, Rect src, int flags,
        DDBltFx bltFx);

This method is capable of synchronous or asynchronous blits, in one of the following formats:

  • display memory to display memory
  • display memory to system memory
  • system memory to display memory
  • system memory to system memory

The blits can be performed by using z-information, alpha information, source color keys, and destination color keys. Arbitrary stretching or shrinking will be performed if the source and destination rectangles are not the same size.

Return Value:

Returns S_OK or 0 if the operation is successful; otherwise, returns an error code.

Parameter | Description
dest | A Rect object that defines the upper-left and lower-right points of the rectangle on the destination surface to be blitted to.
ddS | The DirectDrawSurface object that is the source for the blit operation.
src | A Rect object that defines the upper-left and lower-right points of the rectangle on the source surface to be blitted from.
flags | This parameter is currently not used and must be set to 0.
bltfx | The DDBltFx object that defines the parameters for the blit operations.

copyBitmap

public void copyBitmap(DirectDrawBitmap val, int cx, int cy, int dx,
        int dy);

Copies a bitmap.

Return Value:

No return value.

Parameter | Description
val | The DirectDrawBitmap object
cx | The bitmap's upper-left x coordinate.
cy | The bitmap's upper-left y coordinate.
dx | The bitmap's lower-right x coordinate.
dy | The bitmap's lower-right y coordinate.

create3DDevice

public Direct3dDevice create3DDevice(_Guid g);

Creates a device from the surface if you want a rendering surface. This method emulates the IUnknown interface's HRESULT QueryInterface(REFIID riid, LPVOID* obp); COM method inherited by DirectX3 COM interfaces.

Return Value:

Returns a Direct3dDevice object that acts as a rendering surface.

Parameter | Description
g | A globally unique identifier retrieved with the enumDevices method.

deleteAttachedSurface

public void deleteAttachedSurface(int flags, DirectDrawSurface ddS);

Detaches two attached surfaces. The detached surface is not released.

Return Value:

No return value.

Parameter | Description
flags | Reserved; must be 0.
ddS | The DirectDrawSurface object to detach. If this parameter is null, all attached surfaces are detached.

See Also: flip

enumAttachedSurfaces

public void enumAttachedSurfaces(IUnknown args, IEnumSurfacesCallback fn);

Enumerates all the surfaces attached to a given surface.

Return Value:

No return value.

Parameter | Description
args | Application-defined structure that is passed to the enumeration member every time it is called.
fn | Callback interface that contains callback function that will be called for each surface that is attached to this surface.

enumOverlayZOrders

public void enumOverlayZOrders(int flags, IUnknown args,
        IEnumZOrdersCallback fn);

Enumerates the overlay surfaces on the specified destination. The overlays can be enumerated in front-to-back or back-to-front order.

Return Value:

No return value.

Parameter | Description
flags | One value of DDENUMOVERLAYZ_ type.
args | User-defined context that will be passed to the callback function for each overlay surface.
fn | Callback interface that contains the callback function that will be called for each surface being overlaid on this surface.

flip

public void flip(DirectDrawSurface ddS, int flags);

Makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the front-buffer surface.

Return Value:

No return value.

Parameter | Description
ddS | The DirectDrawSurface object that will be flipped to. The default for this parameter is null; in which case, flip cycles through the buffers in the order they are attached to each other. This parameter is used only as an override.
flags | Can be DDFLIP_WAIT.

Remarks:

This method can be called only by a surface that has the DDSCAPS_FLIP and DDSCAPS_FRONTBUFFER values set. The display memory previously associated with the front buffer is associated with the back buffer. If there is more than one back buffer, a ring is formed and the surface memory buffers cycle one step through it every time flip is called.

The ddS parameter is used in rare cases when the back buffer is not the buffer that should become the front buffer. Typically this parameter is null.

The flip method will always be synchronized with the vertical blank.

See Also: getFlipStatus

getAttachedSurface

public DirectDrawSurface getAttachedSurface(int caps);

Obtains the attached surface that has the specified capabilities.

Return Value:

Returns the DirectDrawSurface object if successful; otherwise, returns null.

Parameter | Description
caps | A value that specifies the hardware capabilities of the surface.

Remarks:

Attachments are used to connect multiple DirectDrawSurface objects into complex structures, like the ones needed to support 3D page flipping with z-buffers. This method fails if more than one surface is attached that matches the capabilities requested. In this case, the application must use the enumAttachedSurfaces method to obtain the attached surfaces.

getBltStatus

public int getBltStatus(int flags);

Obtains the blitter status.

Return Value:

Returns DD_OK if a blitter is present, DDERR_WASSTILLDRAWING if the blitter is busy.

Parameter | Description
flags | One value of DDGBS_ type.

getCaps

public int getCaps();

Retrieves the capabilities of the surface. These capabilities are not necessarily related to the capabilities of the display device.

Return Value:

Returns the hardware capabilities of the surface.

getClipper

public DirectDrawClipper getClipper();

Retrieves the DirectDrawClipper object associated with this surface.

Return Value:

Returns the DirectDrawClipper object if successful; null otherwise.

See Also: setClipper

getColorKey

public void getColorKey(int flags, DDColorKey val);

Retrieves the color key value for the DirectDrawSurface object.

Return Value:

No return value.

Parameter | Description
flags | One value of DDCKEY_ type, specifying which color key to retrieve information for.
val | The DDColorKey object that receives the current values for the specified color key of the DirectDrawSurface object.

See Also: setColorKey

getDC

public int getDC();

Creates a Graphical Device Interface-compatible handle of a device context for the surface.

Return Value:

Returns the handle of a device context.

getDDInterface

public IUnknown getDDInterface();

Retrieves an interface to the DirectDraw object that was used to create the surface.

Return Value:

Returns the IUnknown object if successful; null otherwise.

getFlipStatus

public int getFlipStatus(int flags);

Indicates whether the surface has finished its flipping process.

Return Value:

Returns DD_OK if successful, or DDERR_WASSTILLDRAWING if the surfaces has not finished its flipping process.

Parameter | Description
flags | One value of DDGFS_ type.

See Also: flip

getOverlayPositionX

public int getOverlayPositionX();

Given a visible, active overlay surface (DDSCAPS_OVERLAY flag set), this method returns the x-display coordinate of the surface.

Return Value:

Returns the x coordinate.

See Also: getOverlayPositionY, setOverlayPosition, updateOverlay

getOverlayPositionY

public int getOverlayPositionY();

Given a visible, active overlay surface (DDSCAPS_OVERLAY flag set), this method returns the y-display coordinate of the surface.

Return Value:

Returns the y coordinate.

See Also: getOverlayPositionX, setOverlayPosition, updateOverlay

getPalette

public DirectDrawPalette getPalette();

Retrieves the DirectDrawPalette structure associated with this surface.

Return Value:

Returns the DirectDrawPalette object if successful; null otherwise. This is null if no DirectDrawPalette object is associated with this surface. If the surface is the primary surface, or a back buffer to the primary surface, and the primary surface is in 8-bpp mode, this method returns the system palette.

See Also: setPalette

getPixelFormat

public void getPixelFormat(DDPixelFormat pf);

Retrieves the color and pixel format of the surface.

Return Value:

No return value.

Parameter | Description
pf | A DDPixelFormat object that receives a detailed description of the current pixel and color space format of the surface.

getSurfaceDesc

public void getSurfaceDesc(DDSurfaceDesc surface);

Retrieves a description of the surface in its current condition.

Return Value:

No return value.

Parameter | Description
surface | A DDSurfaceDesc object that receives the current description of this surface.

isLost

public int isLost();

Determines if the surface memory associated with a DirectDrawSurface object has been freed.

Return Value:

Returns DD_OK if the memory has not been freed.

Remarks:

You can use this method to reallocate surface memory. When a DirectDrawSurface object loses its surface memory, most methods perform no function.

Surfaces can lose their memory when the mode of the display card is changed, or when an application receives exclusive access to the display card and frees all of the surface memory currently allocated on the display card.

See Also: restore

lock

public void lock(Rect r, DDSurfaceDesc d, int flags, int hnd,
        byte[] memory);

Obtains the contents of the surface memory.

Return Value:

No return value.

Parameter | Description
r | A Rect object that identifies the region of surface that is being locked.
d | A DDSurfaceDesc object that receives the relevant details about the surface.
flags | One or more values of DDLOCK_ type.
hnd | Handle of a system event that is triggered when the surface is ready to be locked.
memory | Array variable that receives the contents of the surface memory.

Remarks:

The contents of the surface memory remain valid until the corresponding the unlock method is called. Applications that change the contents must flush the changes back into system memory (use the unlock for this as well).

Your application cannot blit from a region of a surface that is locked.

Typically, lock returns immediately when a lock cannot be obtained because a blit is in progress. You can use the DDLOCK_WAIT flag if you want the method to continue trying to obtain a lock.

See Also: unlock

releaseDC

public void releaseDC(int hdc);

Releases the handle of a device context previously obtained by using the getDC method.

Return Value:

No return value.

Parameter | Description
hdc | The handle of a device context.

restore

public int restore();

Restores a surface that has been lost. This occurs when the surface memory associated with the DirectDrawSurface object has been freed.

Return Value:

Returns DD_OK is successful.

Remarks:

Surfaces can be lost because the mode of the display card was changed or because an application received exclusive access to the display card and freed all of the surface memory currently allocated on the card. When a DirectDrawSurface object loses its surface memory, many methods will return DDERR_SURFACELOST and perform no other function. The restore method will reallocate surface memory and reattach it to the DirectDrawSurface object.

A single call to this method will restore a DirectDrawSurface object's associated implicit surfaces (back buffers, and so on). An attempt to restore an implicitly created surface will result in an error. restore will not work across explicit attachments created by using the addAttachedSurface method—each of these surfaces must be restored individually.

See Also: isLost, addAttachedSurface

setClipper

public void setClipper(DirectDrawClipper val);

Attaches a DirectDrawClipper object to a DirectDrawSurface object.

Return Value:

No return value.

Parameter | Description
val | The DirectDrawClipper object that will be attached to the DirectDrawSurface object. If this parameter is null, the current DirectDrawClipper object will be detached.

Remarks:

This method is primarily used by surfaces that are being overlaid on or blitted to the primary surface. However, it can be used on any surface. After a DirectDrawClipper object has been attached and a clip list is associated with it, the DirectDrawClipper object will be used for the blt and updateOverlay operations involving the parent DirectDrawSurface object. This method can also detach a DirectDrawSurface object's current DirectDrawClipper object.

If this method is called several times consecutively on the same surface for the same DirectDrawClipper object, the reference count for the object is incremented only once. Subsequent calls do not affect the object's reference count.

See Also: getClipper

setColorKey

public void setColorKey(int flags, DDColorKey val);

Sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per surface basis.

Return Value:

No return value.

Parameter | Description
flags | One value of DDCKEY_ type, specifying which color key to set.
val | A DDColorKey object that contains the new color key values for the DirectDrawSurface object.

See Also: getColorKey

setOverlayPosition

public void setOverlayPosition(int x, int y);

Changes the display coordinates of an overlay surface.

Return Value:

No return value.

Parameter | Description
x | New x-display coordinate.
y | New y-display coordinate.

See Also: getOverlayPositionX, getOverlayPositionY, updateOverlay

setPalette

public void setPalette(DirectDrawPalette ddp);

Attaches the specified DirectDrawPalette object to a surface. The surface uses this palette for all subsequent operations. The palette change takes place immediately, without regard to refresh timing.

Return Value:

No return value.

Parameter | Description
ddp | The DirectDrawPalette object that this surface should use for future operations.

Remarks:

If this method is called several times consecutively on the same surface for the same palette, the reference count for the palette is incremented only once. Subsequent calls do not effect the palette's reference count.

See Also: getPalette, com.ms.directX.DirectDraw.createPalette

unlock

public void unlock(Rect r, DDSurfaceDesc d, byte[] memory);

Notifies DirectDraw that the direct surface manipulations are complete and copies the contents of the memory buffer into the surface.

Return Value:

No return value.

Parameter | Description
r | A Rect object that identifies the region of surface that receives the changes.
d | The DDSurfaceDesc object returned by the lock method.
memory | Array variable that contains the new contents of the surface memory.

See Also: lock

updateOverlay

public void updateOverlay(Rect r, DirectDrawSurface ddS, Rect d, int flags);

Repositions or modifies the visual attributes of an overlay surface. These surfaces must have the DDSCAPS_OVERLAY value set.

Return Value:

No return value.

Parameter | Description
r | A Rect object that defines the x, y, width, and height of the region on the source surface being used as the overlay.
ddS | The DirectDrawSurface that is being overlaid.
d | A Rect object that defines the x, y, width, and height of the region on the destination surface that the overlay should be moved to.
flags | One or more values of DDOVER_ type.

updateOverlayDisplay

public void updateOverlayDisplay(int flags);

Repaints the rectangles in the dirty rectangle list of all active overlays. This clears the dirty rectangle list. This method is for software emulation only—it does nothing if the hardware supports overlays.

Return Value:

No return value.

Parameter | Description
flags | Type of update to perform. Can be DDOVER_REFRESHDIRTYRECTS or DDOVER_REFRESHALL.

See Also: addOverlayDirtyRect

updateOverlayZOrder

public void updateOverlayZOrder(int flags, DirectDrawSurface ddS);

Sets the z-order of an overlay.

Return Value:

No return value.

Parameter | Description
flags | One value of DDOVERZ_ type.
ddS | The DirectDrawSurface object to be used as a relative position in the overlay chain. This parameter is needed only for DDOVERZ_INSERTINBACKOF and DDOVERZ_INSERTINFRONTOF.

See Also: enumOverlayZOrders


Class DirectInput

public class DirectInput implements IDirectInput
{
  // Methods
  public void getDevCaps(int joyid, JoyCaps pjc);
  public String getDevCapsOEMVxd(int joyid);
  public String getDevCapsProductName(int joyid);
  public String getDevCapsRegKey(int joyid);
  public int getNumDevs();
  public void getPos(int joyid, JoyInfo info);
}

Methods

getDevCaps

public void getDevCaps(int joyid, JoyCaps pjc);

Queries a joystick to determine its capabilities.

Return Value:

No return value.

Parameter | Description
joyid | The joystick identifier.
pic | The JoyCaps object that contains the joystick capabilities.

getDevCapsOEMVxd

public String getDevCapsOEMVxd(int joyid);

Queries a joystick for the name of its original virtual device driver.

Return Value:

Returns the name of the virtual device driver.

Parameter | Description
joyid | The joystick identifier.

getDevCapsProductName

public String getDevCapsProductName(int joyid);

Queries a joystick for its manufacturer's product name.

Return Value:

Returns The joystick model name.

Parameter | Description
joyid | The joystick identifier.

getDevCapsRegKey

public String getDevCapsRegKey(int joyid);

Queries a joystick for the Microsoft® Windows® Registry key, where its capability information is stored.

Return Value:

Returns the name of the registry key.

Parameter | Description
joyid | The joystick identifier.

getNumDevs

public int getNumDevs();

Queries the joystick driver for the number of joysticks it supports.

Return Value:

Returns the number of joysticks the driver supports; otherwise, returns zero if no driver is present.

getPos

public void getPos(int joyid, JoyInfo info);

Queries a joystick for its position and button status.

Return Value:

No return value.

Parameter | Description
joyid | The joystick identifier.
info | The JoyInfo object that contains extended position information and button status of the joystick.


Class DirectPlay2

public class DirectPlay2 implements IDirectPlay2
{
  // Methods
  public void addPlayerToGroup(int groupId, int playerId);
  public void close();
  public IDirectPlay2 create(_Guid g);
  public int createGroup(String friendlyName, String formalName,
        byte[] data, int dataSize);
  public int createPlayer(String friendlyName, String formalName,
        int receiveEvent, byte[] data, int dataSize);
  public void deletePlayerFromGroup(int groupId, int playerId);
  public void destroyGroup(int groupId);
  public void destroyPlayer(int playerId);
  public void enumGroupPlayers(int groupId, _Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumGroups(_Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumPlayers(_Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumServiceProviders(
        IEnumServiceProvidersCallback callback, IUnknown context);
  public void enumSessions(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password, int timeOut,
        IEnumSessionsCallback2 callback, IUnknown context,
        int flags);
  public void getCaps(DPCaps caps, int flags);
  public void getGroupData(int groupId, byte[] data,
        int[] dataSize, int flags);
  public String getGroupFormalName(int groupId);
  public String getGroupFriendlyName(int groupId);
  public int getMessageCount(int playerId);
  public void getPlayerAddress(int playerId, byte[] addressData,
        int[] addressSize);
  public int getPlayerAddressSize(int playerId);
  public void getPlayerCaps(int playerId, DPCaps caps, int flags);
  public void getPlayerData(int playerId, byte[] data,
        int[] dataSize, int flags);
  public String getPlayerFormalName(int playerId);
  public String getPlayerFriendlyName(int playerId);
  public void getSessionDesc(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String[] sessionName, String[] password);
  public void initialize(_Guid guid);
  public void open(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName,
        String password, int flags);
  public void receive(int[] fromPlayerId, int[] toPlayerId,
        int flags, byte[] data, int[] dataSize);
  public int receiveSize(int flags);
  public void send(int fromPlayerId, int toPlayerId, int flags,
        byte[] data, int dataSize);
  public void setGroupData(int groupId, byte[] data, int dataSize,
        int flags);
  public void setGroupName(int groupId, String friendlyName, String
        formalName, int flags);
  public void setPlayerData(int playerId, byte[] data,
        int dataSize, int flags);
  public void setPlayerName(int playerId, String friendlyName,
        String formalName, int flags);
  public void setSessionDesc(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password, int flags);
  public void stopEnumGroupPlayers();
  public void stopEnumGroups();
  public void stopEnumPlayers();
  public void stopEnumServiceProviders();
  public void stopEnumSessions();
}

Applications use the methods of the DirectPlay2 class to create Microsoft® DirectPlay®2 objects and work with system-level variables.

Caution The enumeration methods provided in this class are fundamentally different from their native code counterparts. While the native code implementation return type is a boolean, the Java return type is void. This makes stopping an enumeration more difficult (you can not return false to stop the enumeration). You can use the following DirectPlay methods to stop enumerations:

  • stopEnumSessions
  • stopEnumGroups
  • stopEnumGroupPlayers
  • stopEnumPlayers
  • stopEnumServiceProviders

The stopEnumSessions is the most important method of these, because a session enumeration can proceed infinitely.

Methods

addPlayerToGroup

public void addPlayerToGroup(int groupId, int playerId);

Adds an existing player to an existing group.

Return Value:

No return value.

Parameter | Description
groupId | The ID of the group to be augmented.
playerId | The ID of the player to be added to the group.

Remarks:

Groups cannot be added to other groups, but players can be members of multiple groups. A DPSYS_ADDDIRECTPLAYERTOGROUP system message will be generated and sent to all the other players.

See Also: createGroup, deletePlayerFromGroup, DPSYS_ADDDIRECTPLAYERTOGROUP

close

public void close();

Closes a previously opened session.

Return Value:

No return value.

Remarks:

All locally created players will be destroyed, and corresponding DPSYS_DESTROYPLAYERORGROUP system messages are sent to other session participants. However, groups will not be destroyed; use destroyGroup to destroy the group.

See Also: destroyPlayer, DPMSG_DESTROYPLAYERORGROUP, open

create

public IDirectPlay2 create(_Guid g);

Creates a DirectPlay object.

Return Value:

Returns the DirectPlay object if successful; null otherwise.

Parameter | Description
g | A _Guid object that specifies the globally unique identifier (GUID) that represents the service provider that should be created.

Remarks:

This function attempts to initialize a DirectPlay object. You should call the enumServiceProviders method immediately before initialization to determine what types of service providers are available (enumServiceProviders fills in the g parameter for create).

See Also: enumServiceProviders

createGroup

public int createGroup(String friendlyName, String formalName, byte[] data,
        int dataSize);

Creates a logical group of players in the current session.

Return Value:

Returns a unique DirectPlay ID that identifies the new group.

Parameter | Description
formalName | The formal name of the group. Use null to indicate that the group has no formal name.
friendlyName | The friendly name of the group. Use null to indicate that the group has no friendly name.
data | A block of application-defined remote data to associate with the group ID. Null indicates that the group has no initial data. The data specified here is assumed to be remote data that will be propagated to all the other applications in the session as if setGroupData were called.
dataSize | The size, in bytes, of data.

Remarks:

Messages can be sent to a group, and DirectPlay will forward the message to every player in the group. The Group ID returned to the caller should be used to identify the group for message passing and data association. Player and Group identifiers assigned by DirectPlay will always be unique within the session. This method will generate a DPSYS_CREATEPLAYERORGROUP message that will be sent to all the other players.

See Also: DPMSG_CREATEPLAYERORGROUP, destroyGroup, enumGroups, enumGroupPlayers, send

createPlayer

public int createPlayer(String friendlyName, String formalName,
        int receiveEvent, byte[] data, int dataSize);

Creates a local player for the current session.

Return Value:

Returns a unique DirectPlay ID that identifies the new player.

Parameter | Description
formalName | The formal name of the player. Use null to indicate that the player has no formal name information.
friendlyName | The friendly name of the player. Use null to indicate that the player has no friendly name.
receiveEvent | An event object created by the application that will be triggered by DirectPlay2 when a message addressed to this player is received.
data | A block of application-defined remote data to associate with the group ID. Null indicates that the group has no initial data. The data specified here is assumed to be remote data that will be propagated to all the other applications in the session as if setPlayerData were called.
dataSize | The size, in bytes, of data.

Remarks:

A single process can have multiple local players that communicate through a DirectPlay object with any number of other local or remote players running on multiple computers. The player ID returned to the caller should be used to identify the player for message passing and data association. Player and Group IDs assigned by DirectPlay will always be unique within the session.

The application can associate an initial name with the player at its creation (see setPlayerName). The names in friendlyName and formalName are provided for human use only; they are not used internally and need not be unique.

Upon successful completion, this method sends a DPSYS_CREATEPLAYERORGROUP system message to all of the other players in the session announcing that a new player has joined the session.

See Also: DPMSG_CREATEPLAYERORGROUP, destroyPlayer, enumPlayers, receive, send, setPlayerName

deletePlayerFromGroup

public void deletePlayerFromGroup(int groupId, int playerId);

Removes a player from a group.

Return Value:

No return value.

Parameter | Description
groupId | The group ID of the group to be adjusted.
playerId | The ID of the player to be removed from the group.

Remarks:

A DPSYS_DELETEPLAYERFROMGROUP system message is generated to inform the other players of this change.

See Also: addPlayerToGroup, DPMSG_DELETEPLAYERFROMGROUP

destroyGroup

public void destroyGroup(int groupId);

Deletes a group from the session. The ID belonging to this group will not be reused during the current session.

Return Value:

No return value.

Parameter | Description
groupId | The ID of the group being removed from the game.

Remarks:

It is not necessary to empty a group before deleting it. The individual players belonging to the group are not destroyed. This method will generate a DPSYS_DELETEPLAYERFROMGROUP for each player in the group, and then generate a DPSYS_DESTROYPLAYERORGROUP system message.

See Also: createGroup, DPMSG_DESTROYPLAYERORGROUP

destroyPlayer

public void destroyPlayer(int playerId);

Deletes a player from the session, removes any pending messages destined for that player from the message queue, and removes the player from any groups to which that player belonged. The player ID will not be reused during the current session.

Return Value:

No return value.

Parameter | Description
playerId | The ID of the player that is being removed from the session.

Remarks:

This method will generate a DPSYS_DELETEPLAYERFROMGROUP message for each group that the player belongs to, and then generate a DPSYS_DESTROYPLAYERORGROUP system message.

See Also: createPlayer, DPMSG_DESTROYPLAYERORGROUP

enumGroupPlayers

public void enumGroupPlayers(int groupId, _Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context, int flags);

Enumerates all of the players of a particular group existing in the current session. Use the stopEnumGroupPlayers method to stop the enumeration.

Return Value:

No return value.

Parameter | Description
groupId | The Group ID, whose players are to be enumerated.
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to null unless the DPENUMPLAYERS_SESSION flag is specified.
callback | The callback interface that contains the callback function to be called for every player in the group.
context | A caller-defined context that is passed to each enumeration callback.
flags | The flags to pass to the callback function.

Remarks:

By default, this method will enumerate group players by using the local player list for the current session. This method cannot be called from within an enumSessions enumeration.

See Also: createPlayer, destroyPlayer, addPlayerToGroup, deletePlayerFromGroup, stopEnumGroupPlayers

enumGroups

public void enumGroups(_Guid sessionGuid, IEnumPlayersCallback2 callback,
        IUnknown context, int flags);

Enumerates the groups available to a session. Use the stopEnumGroups method to stop the enumeration.

Return Value:

No return value.

Parameter | Description
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
callback | The callback interface that contains the callback function to be called for every group in the session.
context | A caller-defined context that is passed to each enumeration callback.
flags | The value can be 0 or DPENUMPLAYERS_SESSION. This flag is passed to the callback function.

Remarks:

By default, this method will enumerate using the local player list for the current session. The DPENUMPLAYERS_SESSION flag can be used, along with a session instance GUID, to request that a session's host provide its list for enumeration. This method cannot be called from within an enumSessions enumeration. Furthermore, use of the DPENUMPLAYERS_SESSION flag with this method must occur after the enumSessions method has been called and before any calls to close or open.

See Also: createGroup, destroyGroup, enumSessions, stopEnumGroups

enumPlayers

public void enumPlayers(_Guid sessionGuid, IEnumPlayersCallback2 callback,
        IUnknown context, int flags);

Enumerates the players in a session. Use the stopEnumPlayers method to stop the enumeration.

Return Value:

No return value.

Parameter | Description
sessionGuid | A GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
callback | The callback instance that contains the callback function that will be called for every group in the session.
context | A caller-defined context that is passed to each enumeration callback.
flags | One or more values of the DPENUMPLAYERS_ type. The values are also passed to the callback function.

Remarks:

By default, this method will enumerate players in the current open session. Groups can also be included in the enumeration by using the DPENUMPLAYERS_GROUP flag. The DPENUMPLAYERS_SESSION flag can be used with a session instance GUID to request that a session host provide its list for enumeration. This method cannot be called from within an enumSessions enumeration. Also, use of the DPENUMPLAYERS_SESSION flag with this method must occur after the enumSessions method has been called, and before any calls to close or open.

See Also: createPlayer, destroyPlayer, enumSessions, stopEnumPlayers

enumServiceProviders

public void enumServiceProviders(IEnumServiceProvidersCallback callback,
        IUnknown context);

Enumerates the DirectPlay service providers installed on the system. Use the stopEnumServiceProviders method to stop the enumeration.

Return Value:

No return value.

Parameter | Description
callback | The IEnumServiceProvidersCallback interface that contains the callback function to be called with a description of each DirectPlay service provider interface installed in the system.
context | The caller-defined data that is passed to the callback function each time the function is invoked.

Remarks:

This method enumerates service providers installed in the system, even though the system may not be capable of using those service providers. For example, a TAPI service provider may be enumerated, even though the system may not have a modem installed.

See Also: stopEnumServiceProviders

enumSessions

public void enumSessions(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int timeOut, IEnumSessionsCallback2 callback, IUnknown context, int
        flags);

Enumerates the sessions available to this DirectPlay object. Use the stopEnumSessions method to stop the enumeration.

Return Value:

No return value.

Parameter | Description
sessionDesc | A DPSessionDesc object describing the sessions to be enumerated. Only those sessions that meet the criteria set in this structure will be enumerated. If a password is required, the password field should be set accordingly.
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
applicationGuid | The GUID of the application.
sessionName | The Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | The Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
timeOut | The total amount of time (in milliseconds) that DirectPlay will wait for replies to the enumeration message (not the time between each enumeration). It is recommended that this parameter be set to zero, so DirectPlay can compute the default timeout appropriate for the service provider.
callback | The callback interface that contains the callback function to be called for each DirectPlay session responding.
context | A user-defined context that is passed to each enumeration callback.
flags | A value of the DPENUMSESSIONS_ type. Set to 0 or DPENUMSESSIONS_AVAILABLE, to enumerate only available sessions.

Remarks:

This method is usually called immediately after the DirectPlay object is created using directPlayCreate. It cannot be called while connected to a session or after an application has created a session. enumSessions works by asking that the service provider locate one or more hosts on the network and send the hosts an enumeration request. The replies received make up the sessions that are enumerated. The amount of time DirectPlay spends listening for these replies is controlled by the f1 parameter. When this time interval has expired, your callback will be notified with the DPESC_TIMEDOUT flag. At this point, you may choose to continue the enumeration by setting f1 to a new value and returning 1 or by returning 0 to cancel the enumeration. It is recommended that f1 be set to 0. In that case, DirectPlay will compute a time out that is appropriate for the service provider.

Usually, only sessions that can be joined are enumerated. If the DPENUMSESSIONS_ALL flag is specified, sessions will be enumerated even if the creation of new players has been disabled. Be aware that the application will still not be able to join these sessions.

If the application was not launched by a lobby, the service provider may display a dialog to obtain information from the user to perform the enumeration. For example, the Microsoft serial service provider will ask for COM port settings, the modem service provider will ask for a phone number, and the Internet service provider will ask for an IP address of the host.

Password protected sessions will not be enumerated unless you supply a correct password.

See Also: open, stopEnumSessions

getCaps

public void getCaps(DPCaps caps, int flags);

Retrieves the capabilities of this DirectPlay object.

Return Value:

No return value.

Parameter | Description
caps | A DPCaps object that receives the capabilities of the DirectPlay object. The size field of the DPCaps object must be filled in before using getCaps.
flags If this parameter is set to 0, the capabilities will be computed for nonguaranteed messaging.
DPGETCAPS_GUARANTEED
Retrieves the capabilities for a guaranteed message delivery.

Remarks:

The difference between this method and getPlayerCaps is that this method returns the capabilities of the current session and getPlayerCaps returns the capabilities of the requested player.

See Also: com.ms.directX.DPCaps, getPlayerCaps, send

getGroupData

public void getGroupData(int groupId, byte[] data, int[] dataSize,
        int flags);

Retrieves data for a group of players.

Return Value:

No return value.

Parameter | Description
groupId | The group ID that data is being requested for.
data | The buffer where the application-specific group data is to be written. Set this parameter to NULL to request only the size of data. The dataSize parameter will be set to the size required to hold the data.
dataSize | The size of the buffer before the method is called. After the method returns, this parameter will be set to the size (in bytes) of the group data. If the buffer was too small (DPERR_BUFFERTOOSMALL), this parameter will be set to the buffer size required (see the note about passing null as an argument for other behavior regarding DPERR_BUFFERTOOSMALL).
flags | If this parameter is set to 0, the remote data will be retrieved.

Remarks:

DirectPlay can maintain two types of group data: local and remote. The application must specify which type of data to retrieve. Local data was set by this DirectPlay2 object by using the DPSET_LOCAL flag. Remote data might have been set by any application in the session by using the DPSET_REMOTE flag.

You can pass a null for the data buffer parameter to retrieve the size for the buffer. However, when you do this you must put the code into a try...catch block, because a DPERR_BUFFERTOOSMALL error is generated. The following example shows how you might implement a try...catch block to catch the error.

int  hr=0;
try {
      Glb.glpDPlay2.getGroupData(dpID,null, dataSize,DPGET_REMOTE);
    }
catch (ComException e){ hr= e.getHResult();}

// Check for the DPERR_BUFFERTOOSMALL error
if (hr!=DPERR_BUFFERTOOSMALL){
       //problem...
    }

See Also: com.ms.directX.DirectXConstants.DPGET_REMOTE, com.ms.directX.DirectXConstants.DPGET_LOCAL

getGroupFormalName

public String getGroupFormalName(int groupId);

Retrieves the formal name associated with the group.

Return Value:

Returns the formal name associated with the group.

Parameter | Description
groupId | The ID of the group, whose name is being requested.

getGroupFriendlyName

public String getGroupFriendlyName(int groupId);

Retrieves the friendly name associated with the group.

Return Value:

Returns the friendly name associated with the group.

Parameter | Description
groupId | The ID of the group, whose name is being requested.

getMessageCount

public int getMessageCount(int playerId);

Queries for the number of messages in a specific local player's message receive queue.

Return Value:

Returns the message count.

Parameter | Description
playerId | The layer ID that the message count is requested for. The player must be local.

See Also: receive

getPlayerAddress

public void getPlayerAddress(int playerId, byte[] addressData,
        int[] addressSize);

Retrieves the DirectPlay address for a player. The DirectPlay address is a network address for a player using a specific service provider.

Return Value:

No return value.

Parameter | Description
playerId | Player ID that the address is being requested for.
addressData | Address of a buffer where the DirectPlay2 address is to be written. Set this parameter to NULL to request only the size of data. The addressSize parameter will be set to the size required to hold the data.
addressSize | The size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the group data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size that is required.

getPlayerAddressSize

public int getPlayerAddressSize(int playerId);

Retrieves the DirectPlay address size for a player.

Return Value:

Returns the address size.

Parameter | Description
playerId | The player ID that the address size is being requested for.

getPlayerCaps

public void getPlayerCaps(int playerId, DPCaps caps, int flags);

Obtains the current capabilities of a specified player.

Return Value:

No return value.

Parameter | Description
playerId | The player ID that the capabilities should be computed for.
caps | A DPCaps object that receives the capabilities of the player. The size field of the DPCaps object must contain a value before using getPlayerCaps.
flags | If this parameter is set to 0, the capabilities will be computed for nonguaranteed messaging.

Remarks:

The difference between this method and getCaps is that this method returns the capabilities of the requested player; getCaps returns the capabilities of the current session.

See Also: com.ms.directX.DPCaps, getCaps, send, com.ms.directX.DirectXConstants.DPGETCAPS_GUARANTEED

getPlayerData

public void getPlayerData(int playerId, byte[] data, int[] dataSize,
        int flags);

Retrieves player data for the specified player ID.

Return Value:

No return value.

Parameter | Description
playerId | ID of the player for which data is being requested.
data | Application-specific player data. Set this parameter to null to request only the size of data. The dataSize parameter will be set to the size required to hold the data.
dataSize | The size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the group data. If the buffer was too small (DPERR_BUFFERTOOSMALL), this parameter will be set to the buffer size required.
flags If this parameter is set to 0, the remote data will be retrieved.
DPGET_REMOTE
Retrieves the current data from the remote shared data space.
DPGET_LOCAL
Retrieves the local data set by this application.

getPlayerFormalName

public String getPlayerFormalName(int playerId);

Obtains the formal name associated with a player.

Return Value:

Returns the name.

Parameter | Description
playerId | Player ID number for which the name information is being requested.

See Also: setPlayerName

getPlayerFriendlyName

public String getPlayerFriendlyName(int playerId);

Obtains the friendly name associated with a player.

Return Value:

Returns the name.

Parameter | Description
playerId | Player ID number for which the name information is being requested.

See Also: setPlayerName

getSessionDesc

public void getSessionDesc(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String[] sessionName, String[] password);

Retrieves a description of the specified session.

Return Value:

No return value.

Parameter | Description
sessionDesc | A DPSessionDesc object describing the sessions to be enumerated. Only those sessions that meet the criteria set in this structure will be enumerated. If a password is required, the password field should be set accordingly.
sessionGuid | The GUID of the session instance.
applicationGuid | The GUID of the application running in the session instance. It uniquely identifies the application so that DirectPlay connects only to other computers running the same application. This member can be set to GUID_NULL to enumerate sessions for any application.
sessionName | The Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | The Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.

initialize

public void initialize(_Guid guid);

Initializes the DirectPlay2 object.

Return Value:

No return value.

Parameter | Description
guid | The GUID used as the interface identifier.

Remarks:

Since the DirectPlay2 object is initialized when it is created, calling this method will always result in no action.

open

public void open(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int flags);

Establishes a gaming session instance.

Return Value:

No return value.

Parameter | Description
sessionDesc | The DPSessionDesc object describing the session to be created or joined.
sessionGuid | The GUID of the DirectPlay session of interest.
applicationGuid | The GUID of the application running in the session instance. It uniquely identifies the application so that DirectPlay connects only to other computers running the same application. This member can be set to GUID_NULL to enumerate sessions for any application.
sessionName | Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
flags Can be one of the following flags:
DPOPEN_CREATE
DPOPEN_JOIN

Remarks:

An application may either create a new session (which other remote applications join) or join an existing session. open must be called before any local players are created. Before an application can join an existing session, it will use enumSessions to obtain a list of what sessions can be joined and their session descriptions. Attempting to join a session where adding new players is disabled, joining is disabled, or the player limit has been reached will result in no action.

See Also: close, enumSessions

receive

public void receive(int[] fromPlayerId, int[] toPlayerId, int flags, byte[]
        data, int[] dataSize);

Retrieves a message from the message queue.

Return Value:

No return value.

Parameter | Description
fromPlayerId | A array that receives the player ID of the sender of the message.
toPlayerId | An array that receives the player ID of the receiver of the message.
flags | One or more values of DPRECEIVE_ type. Both DPRECEIVE_TOPLAYER and DPRECEIVE_FROMPLAYER can be specified, in which case receive will return whichever message is encountered first.
data | Array variable that receives the message data.
dataSize | The length of the array assigned to the data parameter.

Remarks:

Any message received from player ID DPID_SYSMSG is a system message that is generated by the host. For such messages, the application should interpret data as a generic system message and check for the type of message before processing it.

Messages that were sent to player ID DPID_SYSMSG as a way to broadcast them to all players, or to a group ID to send them to all the players in the group, still appear to come from the sending player ID. An application will only receive messages directed to a local player. A player cannot receive a message where the sender and receiver IDs are the same.

If DPSESSION_NOMESSAGEID is specified in the session description, the LPID_FROM and LPID_TO variables are meaningless.

All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message received will be verified. If data corruption is detected, the message will either be thrown away (if it was sent nonguaranteed) or it will be retransmitted (if it was sent guaranteed).

See Also: send

receiveSize

public int receiveSize(int flags);

Retrieves the size of the message data associated with the next or specified message on the message queue.

Return Value:

Returns the size of the message data.

Parameter | Description
flags | Can be DPRECEIVE_ALL.

send

public void send(int fromPlayerId, int toPlayerId, int flags, byte[] data,
        int dataSize);

Sends messages to other players, to a group of players, or to all players in the session.

Return Value:

No return value.

Parameter | Description
fromPlayerId | The player ID of the sending player. The player ID must correspond to one of the local players on this computer.
toPlayerId | The player ID of the player to send the message to, the group ID of the group of players to send the message to, or DPID_ALLPLAYERS to send to all players in the session. If DPSEND_OPENSTREAM or DPSEND_CLOSESTREAM flags are used, this parameter must be a player ID.
flags | One value of DPSEND_ type, indicating how the message should be sent. If this parameter is set to 0, the message is sent nonguaranteed and at normal priority.
data | Array variable that contains the data being sent. Set to null if there is no actual message to send.
dataSize | Length of the data being sent.

Remarks:

To send a message to another player, specify the target player's player ID. To send a message to a group of players, send the message to the group ID assigned to the group. To send messages to the entire session, specify the player ID DPID_ALLPLAYERS. The send method cannot be used inside a lock / unlock or a getDC / releaseDC method pair.

A player cannot send a message to itself. If a player sends a message to a group that it is part of or to DPID_ALLPLAYERS, it will not receive a copy of that message.

If DPSESSION_NOMESSAGEID was specified in the session description, it is possible for a player to receive a message that it sent to a group. Since there is no DirectPlay message ID header on the message (indicating who sent the message), it cannot filter out messages from itself when the service provider implements group sends, and the application will need to be able to evaluate this based on the content of the message.

When DPSESSION_NOMESSAGEID is used, the message is sent to one of the local players on the target computer.

Messages can be sent guaranteed or nonguaranteed. By default, messages are sent nonguaranteed, which means that DirectPlay does no verification that the message reached the intended recipient. Sending a guaranteed message takes much longer, a minimum of two to three times longer than a nonguaranteed message. Applications should try to minimize sending guaranteed messages as much as possible and design the application to tolerate lost messages.

All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message received will be verified, and if data corruption is detected, it will either be thrown away (if it was sent nonguaranteed), or it will be retransmitted (if it was sent guaranteed).

Note In this version of DirectPlay2, DPSEND_GUARANTEED will only guarantee delivery if the service provider supports it. An application can find out if delivery will be guaranteed by calling getCaps and checking for the DPCAPS_GUARANTEEDSUPPORTED flag. If this flag is not set, the DPSEND_GUARANTEED flag will be ignored and the message will be sent nonguaranteed. The next version of DirectPlay will implement guaranteed delivery on nonguaranteed service providers so the guaranteed supported CAPS flag will always be present. If the application implements its own method of guaranteeing message delivery, it must be sure not to use the DPSEND_GUARANTEED flag. When testing the performance of your application, it is important to know if the service provider supports guaranteed messaging. If it does not, every place you specified DPSEND_GUARANTEED will run slower with the next version of DirectPlay.

See Also: receive

setGroupData

public void setGroupData(int groupId, byte[] data, int dataSize, int flags);

Sets data for the group specified by the group ID.

Return Value:

No return value.

Parameter | Description
groupId | The group ID for which data is being set.
data | The data to be set. Set to NULL to clear any existing group data.
dataSize | Size of the data buffer.
flags If this parameter is set to 0, the remote group data will be set and propagated using nonguaranteed messaging. See also:
DPSET_REMOTE
DPSET_LOCAL
DPSET_GUARANTEED

setGroupName

public void setGroupName(int groupId, String friendlyName,
        String formalName, int flags);

Sets the name of a group after it has been created. A DPSYS_SETPLAYERORGROUPNAME system message will be sent to all the other players notifying them of the change, unless DPSESSION_NODATAMESSAGES is set in the session description.

Return Value:

No return value.

Parameter | Description
groupId | The ID of the group for which the name is being set.
friendlyName | The friendly name of the group.
formalName | The formal name of the group.
flags If this parameter is set to 0, the name will be propagated to all the remote systems by using nonguaranteed message passing. See also:
DPSET_GUARANTEED

setPlayerData

public void setPlayerData(int playerId, byte[] data, int dataSize,
        int flags);

Associates an application-specific data block with a player ID.

Return Value:

No return value.

Parameter | Description
playerId | The ID of the player for which data is being set.
data | The data to be set. Set this parameter to null to clear any existing player data.
dataSize | The size of the data.
flags If this parameter is set to 0, the remote player data will be set and propagated by using nonguaranteed messaging. This parameter may be one or a combination of the following flags:
DPSET_REMOTE
DPSET_LOCAL
DPSET_GUARANTEED

setPlayerName

public void setPlayerName(int playerId, String friendlyName,
        String formalName, int flags);

Sets the name of the player after it has been changed. A DPSYS_SETPLAYERORGROUPNAME system message will be sent to all other players notifying them of the change, unless DPSESSION_NODATAMESSAGES is set in the session description.

Return Value:

No return value.

Parameter | Description
playerId | The player ID for which data is being sent.
formalName | The formal name for the player. Use null if the player has no formal name.
friendlyName | The friendly name for the player. Use null if the player has no friendly name.
flags | If this parameter is set to 0, the name will be propagated to all the remote systems using nonguaranteed message passing.

See Also: DPMSG_SETPLAYERORGROUPNAME, getPlayerFormalName, getPlayerFriendlyName, send, com.ms.directX.DirectXConstants.DPSET_GUARANTEED

setSessionDesc

public void setSessionDesc(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int flags);

This method is currently not supported. Changes the properties of the current session. This method works only when called on the computer that is the host of the session.

Return Value:

Returns DPERR_UNSUPPORTED.

Parameter | Description
sessionDesc | The DPSessionDesc object describing the session to be created or joined.
sessionGuid | The GUID of the DirectPlay session of interest.
applicationGuid | The GUID of the application running in the session instance. It uniquely identifies the application so that DirectPlay connects only to other computers running the same application. This member can be set to GUID_NULL to enumerate sessions for any application.
sessionName | Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
flags | No flags are currently used by this method.

stopEnumGroupPlayers

public void stopEnumGroupPlayers();

Stops a group players enumeration. You must use this method to stop an enumeration, because, unlike native code that has a boolean return value for enumeration methods, Java enumeration methods return void.

Return Value:

No return value.

See Also: enumGroupPlayers

stopEnumGroups

public void stopEnumGroups();

Stops a group enumeration. You must use this method to stop an enumeration, because, unlike native code that has a boolean return value for enumeration methods, Java enumeration methods return void.

Return Value:

Returns no return value.

See Also: enumGroups

stopEnumPlayers

public void stopEnumPlayers();

Stops a players enumeration. You must use this method to stop an enumeration, because, unlike native code that has a boolean return value for enumeration methods, Java enumeration methods return void.

Return Value:

No return value.

See Also: enumPlayers

stopEnumServiceProviders

public void stopEnumServiceProviders();

Stops a service provider enumeration. You must use this method to stop an enumeration, because, unlike native code that has a boolean return value for enumeration methods, Java enumeration methods return void.

Return Value:

No return value.

See Also: enumServiceProviders

stopEnumSessions

public void stopEnumSessions();

Stops a session enumeration. You must use this method to stop an enumeration, because, unlike native code that has a boolean return value for enumeration methods, Java enumeration methods return void.

Return Value:

No return value.

See Also: enumSessions


Class DirectPlayLobby

public class DirectPlayLobby implements IDirectPlayLobby
{
  // Methods
  public DirectPlay2 connect();
  public DirectPlayLobby create(_Guid guid);
  public void createAddress(_Guid spGuid, _Guid addressTypeGuid,
        String addressString, byte[] addressData,
        int[] addressSize);
  public int createAddressSize(_Guid spGuid, _Guid addressTypeGuid,
        String addressString);
  public void enumAddress(IEnumAddressCallback callback,
        byte[] addressData, int addressSize, IUnknown context);
  public void enumAddressTypes(IEnumAddressTypesCallback callback,
        _Guid spGuid, IUnknown context, int flags);
  public void enumLocalApplications(
        IEnumLocalApplicationsCallback callback,
        IUnknown context, int flags);
  public void enumServiceProviders(
        IEnumServiceProvidersCallback callback, IUnknown context);
  public void getConnectionSettings(int applicationId,
        int[] connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String[] sessionName, String[] password,
        String[] playerShortName, String[] playerLongName,
        _Guid guidSP, byte[] addressData, int[] addressSize);
  public int getConnectionSettingsAddressSize(int applicationId);
  public void receiveLobbyMessage(int applicationId, int[] flags,
        byte[] data, int[] dataSize);
  public void receiveLobbyMessageSize(int applicationId,
        int[] flags, int[] dataSize);
  public void runApplication(int[] applicationId,
        int connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password,
        String playerShortName, String playerLongName,
        _Guid spGuid, byte[] addressData, int addressSize,
        int receiveEvent);
  public void sendLobbyMessage(int applicationId, byte[] data,
        int dataSize);
  public void setConnectionSettings(int applicationId,
        int connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password,
        String playerShortName, String playerLongName,
        _Guid spGuid, byte[] addressData, int addressSize);
  public void setLobbyMessageEvent(int applicationId,
        int receiveEvent);
}

Methods

connect

public DirectPlay2 connect();

Connects an application to a session by using the connection data supplied by the lobby client in the runApplication method or by calling the setConnectionSettings method.

Return Value:

Returns a Microsoft® DirectPlay® object with the correct service provider and opens the correct session without prompting the user to complete any dialog boxes.

Remarks:

If this method fails with the DPERR_NOTLOBBIED error value, the application should perform the normal steps of calling enumServiceProviders, create, enumSessions and open. If it fails on any other error value, there is a problem connecting to the session.

Before calling this method, the application can examine the connection settings that will be used to start the application by using the getConnectionSettings method. The application can then modify these settings and set them by using the setConnectionSettings method.

create

public DirectPlayLobby create(_Guid guid);

Creates an instance of a IDirectPlayLobby object and attempts to initialize it.

Return Value:

Returns an DirectPlayLobby object.

Parameter | Description
guid | A globally unique identifier (GUID).

createAddress

public void createAddress(_Guid spGuid, _Guid addressTypeGuid,
        String addressString, byte[] addressData, int[] addressSize);

Creates a DirectPlay address when given a service provider-specific network address. The resulting address contains the GUID of the service provider and data that the service provider can interpret as a network address.

Return Value:

No return value.

Parameter | Description
spGuid | The address of the service provider GUID. (In C++, it is a reference to the GUID.)
addressTypeGuid | The address of a GUID identifying the specific network address type being used.
addressString | A buffer that the constructed DirectPlay address is to be written to.
addressData | A buffer containing the specific network address.
addressSize | The size of the DirectPlay address buffer. Before calling this method, the service provider must initialize addressSize to the size of the buffer. After the method has returned, this parameter will contain the number of bytes written to the address. If the buffer was too small (DPERR_BUFFERTOOSMALL), this parameter will be set to the size required to store the DirectPlay address.

createAddressSize

public int createAddressSize(_Guid spGuid, _Guid addressTypeGuid,
        String addressString);

Return Value:

Returns

Parameter | Description
spGuid | The address of the service provider GUID.
addressTypeGuid | The address of a GUID identifying the specific network address type being used.
addressString | A buffer in which the constructed DirectPlay address is to be written.

enumAddress

public void enumAddress(IEnumAddressCallback callback, byte[] addressData,
        int addressSize, IUnknown context);

Parses out sections from the DirectPlay address buffer.

Return Value:

No return value.

Parameter | Description
callback | The EnumAddressCallback function that will be called for each information section in the DirectPlay address.
addressData | The start of the DirectPlay address buffer.
addressSize | The size of the DirectPlay address.
context | The context that will be passed to the callback function.

enumAddressTypes

public void enumAddressTypes(IEnumAddressTypesCallback callback,
        _Guid spGuid, IUnknown context, int flags);

Enumerates all the address types that a given service provider needs to build the DirectPlay address.

Return Value:

No return value.

Parameter | Description
callback | The EnumAddressTypeCallback function that will be called for each address type for a service provider. If the service provider takes no address type, the callback will not be called.
spGuid | The GUID of the service provider, whose address types are to be enumerated.
context | The context that will be passed to the callback function.
flags | Reserved; the value must be zero.

enumLocalApplications

public void enumLocalApplications(IEnumLocalApplicationsCallback callback,
        IUnknown context, int flags);

Enumerates the applications that are registered with DirectPlay.

Return Value:

No return value.

Parameter | Description
callback | The EnumLocalApplicationsCallback function that will be called for each enumerated application.
context | The context passed to the callback function.
flags | Reserved; must be zero.

enumServiceProviders

public void enumServiceProviders(IEnumServiceProvidersCallback callback,
        IUnknown context);

Enumerates the DirectPlayLobby service providers installed on the system.

Return Value:

No return value.

Parameter | Description
callback | The IEnumServiceProvidersCallback interface that contains the callback function to be called with a description of each DirectPlay service provider interface installed on the system.
context | Caller-defined data that is passed to the callback function each time the function is invoked.

Remarks:

This method enumerates service providers installed in the system, even though the system may not be enabled to use those service providers. For example, a TAPI service provider may be enumerated, even though the system may not have a modem installed.

getConnectionSettings

public void getConnectionSettings(int applicationId, int[] connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid, _Guid
        applicationGuid, String[] sessionName, String[] password, String[]
        playerShortName, String[] playerLongName, _Guid guidSP, byte[]
        addressData, int[] addressSize);

Retrieves all the information needed to start and connect an application. The data returned is the same data that was passed to the runApplication method by the lobby client or set by calling the setConnectionSettings method.

Return Value:

No return value.

Parameter | Description
applicationId | The application identifier.
connectionFlags Indicates how the connection should be made. This may be one of the following:
DPLCONNECTION_CREATESESSION
Creates a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Joins the existing session as described in the session description.
sessionDesc | A DPSessionDesc object describing the sessions to be enumerated. Only those sessions that meet the criteria set in this class will be enumerated.
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
applicationGuid | The application GUID.
sessionName | The Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
playerShortName | The short name that the player should be created with. This will be the name of the person registered in the lobby. The application can ignore this name.
playerLongName | The long name that the player should be created with.
guidSP | The GUID of the service provider used to connect to the session.
addressData | The information that the service provider needs to connect to a session.
addressSize | The address data size (in bytes).

getConnectionSettingsAddressSize

public int getConnectionSettingsAddressSize(int applicationId);

Retrieves the size of the buffer that contains the connection settings.

Return Value:

Returns the buffer size (in bytes).

Parameter | Description
applicationId | When called from a lobby client that communicates with several applications, this parameter identifies which application connection settings to retrieve.

receiveLobbyMessage

public void receiveLobbyMessage(int applicationId, int[] flags,
        byte[] data, int[] dataSize);

Retrieves the message sent between a lobby client application and a DirectPlay application. Messages are queued, so there is no danger of losing data if it is not read in time.

Return Value:

No return value.

Parameter | Description
applicationId | Identifies which application message to retrieve when called from a lobby client (that communicates with several applications). When called from an application (that communicates only with one lobby client), this parameter must be set to zero. This ID number is obtained by using the runApplication method.
flags | Flags indicating what type of message is being returned. This may be DPLAD_SYSTEM.
data | The message to be written. Set this parameter to NULL to request only the size of message. The lpdwDataSize parameter will be set to the minimum size required to hold the message.
dataSize | The size of the buffer before this method is called. After the method returns, this parameter will be set to the size, in bytes, of the message. If the buffer was too small (DPERR_BUFFERTOOSMALL), this parameter will be set to the minimum buffer size required.

receiveLobbyMessageSize

public void receiveLobbyMessageSize(int applicationId, int[] flags,
        int[] dataSize);

Retrieves the size of the message sent between a lobby client application and a DirectPlay application.

Return Value:

No return value.

Parameter | Description
applicationId | Identifies which application's message to retrieve when this method is called from a lobby client (that communicates with several applications).
flags | The flags indicating the type of message being returned.
dataSize | The size of the buffer before this method is called. After the method returns, dataSize will be set to the size (in bytes) of the message. If the buffer was too small (DPERR_BUFFERTOOSMALL), dataSize will be set to the minimum buffer size required.

runApplication

public void runApplication(int[] applicationId, int connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        String playerShortName, String playerLongName, _Guid spGuid, byte[]
        addressData, int addressSize, int receiveEvent);

Runs a DirectPlay application.

Return Value:

No return value.

Parameter | Description
applicationId | The application identifier.
connectionFlags Indicates how the connection should be made. This parameter may be one of the following flags:
DPLCONNECTION_CREATESESSION
Creates a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Joins the existing session as described in the session description.
sessionDesc | A DPSessionDesc object describing the sessions to be enumerated. Only those sessions that meet the criteria set in this class will be enumerated.
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
applicationGuid | The application GUID.
sessionName | The Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | The Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
playerShortName | The short name that the player should be created with. This will be the name of the person registered in the lobby. The application can ignore this name.
playerLongName | The long name that the player should be created with.
spGuid | The GUID of the service provider used to connect to the session.
addressData | The information that the service provider needs to connect to a session.
addressSize | Address data size (in bytes).
receiveEvent | The event handle set when a message is received.

sendLobbyMessage

public void sendLobbyMessage(int applicationId, byte[] data, int dataSize);

Sends a message between the application and the lobby client.

Return Value:

No return value.

Parameter | Description
applicationId | Identifies which application to send a message to when called from a lobby client (that communicates with several applications). When called from an application (that communicates with only one lobby client), this parameter must be zero. This ID is obtained by using the runApplication method.
data | The message to send.
dataSize | The buffer size (in bytes).

setConnectionSettings

public void setConnectionSettings(int applicationId, int connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        String playerShortName, String playerLongName, _Guid spGuid, byte[]
        addressData, int addressSize);

Modifies the connection settings needed to start and connect an application.

Return Value:

No return value.

Parameter | Description
applicationId | When this method is called from a lobby client that communicates with several applications, applicationId identifies which application connection settings to retrieve.
connectionFlags Indicates how the connection should be made. This parameter may be one of the following flags:
DPLCONNECTION_CREATESESSION
Creates a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Joins the existing session as described in the session description.
sessionDesc | A DPSessionDesc object describing the sessions to be enumerated. Only those sessions that meet the criteria set in this class will be enumerated.
sessionGuid | The GUID of the DirectPlay session of interest. This parameter must be set to NULL unless the DPENUMPLAYERS_SESSION flag is specified.
applicationGuid | The application GUID.
sessionName | The Unicode string containing the name of the session. Use this member only if the IDirectPlay2 interface is in use.
password | The Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
playerShortName | The short name that the player should be created with. This will be the name of the person registered in the lobby. The application can ignore this name.
playerLongName | The long name that the player should be created with.
spGuid | The GUID of the service provider used to connect to the session.
addressData | The information that the service provider needs to connect to a session.
addressSize | The address data size (in bytes).

setLobbyMessageEvent

public void setLobbyMessageEvent(int applicationId, int receiveEvent);

Registers an event that will be set when a lobby message is received. The application must call this method if it needs to synchronize with messages. The lobby client can call this method to change the events specified in the call to the runApplication method.

Return Value:

No return value.

Parameter | Description
applicationId | Identifies which application the event is associated with when called from a lobby client that communicates with several applications. When called from an application that communicates with only one lobby client, this parameter must be zero. This ID number is obtained from runApplication.
receiveEvent | The event handle set when a message is received.


Class DirectSound

public class DirectSound implements IDirectSound
{
  // Methods
  public void compact();
  public DirectSoundBuffer createSoundBuffer(
        DSBufferDesc bufferDesc, byte[] format);
  public DirectSoundBuffer createSoundBuffer(
        DSBufferDesc bufferDesc, WaveFormatEx format);
  public DirectSoundBuffer duplicateSoundBuffer(
        DirectSoundBuffer original);
  public void enumSoundDrivers(IEnumSoundDriversCallback callback,
        IUnknown context);
  public void getCaps(DSCaps caps);
  public void getSpeakerConfig(int[] speakerConfig);
  public void initialize(_Guid guid);
  public void setCooperativeLevel(int hwnd, int level);
  public void setSpeakerConfig(int speakerConfig);
}

Applications use the methods of the DirectSound class to create DirectSound objects and set up the environment.

Methods

compact

public void compact();

Moves the unused portions of onboard sound memory, if any, to a contiguous block so that the largest portion of free memory will be available.

Return Value:

No return value.

Remarks:

If the application calls this method, it must have exclusive cooperation with the DirectSound object. (To get exclusive access, specify DSSCL_EXCLUSIVE in a call to the setCooperativeLevel method.) This method will fail if any operations are in progress.

See Also: setCooperativeLevel

createSoundBuffer

public DirectSoundBuffer createSoundBuffer(DSBufferDesc bufferDesc,
        byte[] format);

Creates a DirectSoundBuffer object to hold a sequence of audio samples.

Return Value:

Returns the DirectSoundBuffer object if successful; null otherwise.

Parameter | Description
bufferDesc | A DSBufferDesc object that contains the description of the sound buffer to be created.
format | Array variable that specifies the wave format for the sound buffer.

Remarks:

Before it can play any sound buffers, the application must specify a cooperative level for a DirectSound object by using the setCooperativeLevel method.

The bufferDesc parameter is an object that describes the type of buffer desired, including format, size, and capabilities. The application must specify the needed capabilities, or they will not be available. For example, if the application creates a DirectSoundBuffer object without specifying the DSBCAPS_CTRLFREQUENCY flag, any call to setFrequency will fail.

The DSBCAPS_STATIC flag can also be specified, in which case DirectSound stores the buffer in onboard memory, if available, in order to take advantage of hardware mixing. To force the buffer to use either hardware or software mixing, use the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags.

See Also: com.ms.directX.DSBufferDesc, duplicateSoundBuffer, setCooperativeLevel

createSoundBuffer

public DirectSoundBuffer createSoundBuffer(DSBufferDesc bufferDesc,
        WaveFormatEx format);

Creates a DirectSoundBuffer object to hold a sequence of audio samples.

Return Value:

Returns the DirectSoundBuffer object if successful; null otherwise.

Parameter | Description
bufferDesc | A DSBufferDesc object that contains the description of the sound buffer to be created.
format | A WaveFormatEx object that specifies the wave format for the sound buffer.

Remarks:

Before it can play any sound buffers, the application must specify a cooperative level for a DirectSound object by using the setCooperativeLevel method.

The bufferDesc parameter is an object that describes the type of buffer desired, including format, size, and capabilities. The application must specify the needed capabilities, or they will not be available. For example, if the application creates a DirectSoundBuffer object without specifying the DSBCAPS_CTRLFREQUENCY flag, any call to setFrequency will fail.

The DSBCAPS_STATIC flag can also be specified, in which case DirectSound stores the buffer in onboard memory, if available, in order to take advantage of hardware mixing. To force the buffer to use either hardware or software mixing, use the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags.

See Also: com.ms.directX.DSBufferDesc, duplicateSoundBuffer, setCooperativeLevel

duplicateSoundBuffer

public DirectSoundBuffer duplicateSoundBuffer(DirectSoundBuffer original);

Creates a new DirectSoundBuffer object that uses the same buffer memory as the original object.

Return Value:

Returns the DirectSoundBuffer object if successful; null otherwise.

Parameter | Description
original | The DirectSoundBuffer object to be duplicated.

Remarks:

The new object can be used just like the original.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

If data in the buffer is changed through one object, the change will be reflected in the other object since the buffer memory is shared.

The buffer memory will be released when the last object referencing it is released.

See Also: createSoundBuffer

enumSoundDrivers

public void enumSoundDrivers(IEnumSoundDriversCallback callback,
        IUnknown context);

Enumerates the DirectSound drivers installed in the system.

Return Value:

No return value.

Parameter | Description
callback | The IEnumSoundDriversCallback interface that contains the callback function to be called for each DirectSound object installed in the system.
context | User-defined context passed to the enumeration callback function every time that function is called.

getCaps

public void getCaps(DSCaps caps);

Retrieves the capabilities of the hardware device that is represented by the DirectSound object.

Return Value:

No return value.

Parameter | Description
caps | The DSCaps object that receives the capabilities of this sound device.

Remarks:

Information retrieved in the DSCaps object describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of onboard sound memory. This information can be used to fine-tune performance and optimize resource allocation.

Because of resource sharing requirements, the maximum capabilities in one area might only be available at the cost of another area. For example, the maximum number of hardware-mixed streaming sound buffers may only be available if there are no hardware static sound buffers.

See Also: directSoundCreate, com.ms.directX.DSCaps

getSpeakerConfig

public void getSpeakerConfig(int[] speakerConfig);

Retrieves the speaker configuration specified for this DirectSound object.

Return Value:

No return value.

Parameter | Description
speakerConfig | Array variable that receives the speaker configuration for this DirectSound object. The speaker configuration is specified with one value of DSSPEAKER_ type.

See Also: setSpeakerConfig

initialize

public void initialize(_Guid guid);

Initializes the DirectSound object if it has not yet been initialized.

Return Value:

No return value.

Parameter | Description
guid | The GUID specifying the sound driver for this DirectSound object to bind to, or null to select the primary sound driver.

setCooperativeLevel

public void setCooperativeLevel(int hwnd, int level);

Sets the cooperative level of the application for this sound device.

Return Value:

No return value.

Parameter | Description
hwnd | Window handle for the application.
level | One value of DSSCL_ type, specifying the requested priority level.

Remarks:

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_NORMAL; use other priority levels when necessary.

You must call the show() or addNotify() method before calling setCooperativeLevel

class Test implements DirectXConstants{

    void run(){
                  DirectSound ds = new DirectSound();
                  this.show();
                  ds.setCooperativeLevel(this,DSSCL_EXCLUSIVE);
              }
}

See Also: compact

setSpeakerConfig

public void setSpeakerConfig(int speakerConfig);

Specifies the speaker configuration for the DirectSound object.

Return Value:

No return value.

Parameter | Description
speakerConfig | One value of DSSPEAKER_ type, specifying the speaker configuration of the specified DirectSound object.

See Also: getSpeakerConfig


Class DirectSound3dBuffer

public class DirectSound3dBuffer implements
            IDirectSound3dBuffer
{
  // Methods
  public void getAllParameters(DS3dBuffer buffer);
  public void getConeAngles(int[] inCone, int[] outCone);
  public void getConeOrientation(D3dVector orientation);
  public void getConeOutsideVolume(int[] coneOutsideVolume);
  public void getMaxDistance(float[] maxDistance);
  public void getMinDistance(float[] minDistance);
  public void getMode(int[] mode);
  public void getPosition(D3dVector position);
  public void getVelocity(D3dVector velocity);
  public void setAllParameters(DS3dBuffer buffer, int applyFlag);
  public void setConeAngles(int inCone, int outCone, int applyFlag);
  public void setConeOrientation(float x, float y, float z,
        int applyFlag);
  public void setConeOutsideVolume(int coneOutsideVolume,
        int applyFlag);
  public void setMaxDistance(float maxDistance, int applyFlag);
  public void setMinDistance(float minDistance, int applyFlag);
  public void setMode(int mode, int applyFlag);
  public void setPosition(float x, float y, float z, int applyFlag);
  public void setVelocity(float x, float y, float z, int applyFlag);
}

Methods

getAllParameters

public void getAllParameters(DS3dBuffer buffer);

Retrieves information that describes the 3D characteristics of a sound buffer at a given point in time.

Return Value:

No return value.

Parameter | Description
buffer | The DS3dBuffer that will contain the information describing the 3D characteristics of the sound buffer.

getConeAngles

public void getConeAngles(int[] inCone, int[] outCone);

Retrieves the inside and outside angles of the sound projection cone for this sound buffer.

Return Value:

No return value.

Parameter | Description
inCone | The inside angles of the sound projection cone.
outCone | The outside angles of the sound projection cone.

getConeOrientation

public void getConeOrientation(D3dVector orientation);

Retrieves the orientation of the sound projection cone for this sound buffer.

Return Value:

No return value.

Parameter | Description
orientation | The D3dVector that will contain the current orientation of the sound projection cone. The vector information represents the center of the sound cone.

Remarks:

This method has no effect unless the cone angle and cone volume factor have also been set. The default value is (0,0,1).

getConeOutsideVolume

public void getConeOutsideVolume(int[] coneOutsideVolume);

Retrieves the current cone outside volume for this sound buffer.

Return Value:

No return value.

Parameter | Description
coneOutsideVolume | The current cone outside volume for this buffer.

Remarks:

Volume levels are represented by attenuation. Allowable values are between 0 (no attenuation) and -10,000 (silence). Amplification is not currently supported by DirectSound.

getMaxDistance

public void getMaxDistance(float[] maxDistance);

Retrieves the current maximum distance for this sound buffer.

Return Value:

No return value.

Parameter | Description
maxDistance | The current maximum distance setting.

Remarks:

The maximum distance value is infinite by default.

getMinDistance

public void getMinDistance(float[] minDistance);

Retrieves the current minimum distance for this sound buffer.

Return Value:

No return value.

Parameter | Description
minDistance | The current minimum distance setting.

Remarks:

The minimum distance value is 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 m per unit) by default.

getMode

public void getMode(int[] mode);

Retrieves the current operation mode for 3D sound processing.

Return Value:

No return value.

Parameter Description
mode The current mode setting. This value will be one of the following:
DS3DMODE_DISABLE
DS3DMODE_HEADRELATIVE
DS3DMODE_NORMAL

getPosition

public void getPosition(D3dVector position);

Retrieves the sound buffer's current position, in distance units. Distance units are meters by default, but the units can be changed by using the setDistanceFactor method.

Return Value:

No return value.

Parameter | Description
position | The D3dVector that will contain the current position of the sound buffer.

getVelocity

public void getVelocity(D3dVector velocity);

Retrieves the current velocity for this sound buffer.

Return Value:

No return value.

Parameter | Description
velocity | The D3dVector that will contain the sound buffer's current velocity.

Remarks:

Velocity is used for Doppler effects only. It does not actually move the buffer.

setAllParameters

public void setAllParameters(DS3dBuffer buffer, int applyFlag);

Sets all 3D sound buffer parameters from a given DS3dBuffer that describes all aspects of the sound buffer at a moment in time.

Return Value:

No return value.

Parameter | Description
buffer | The DS3dBuffer containing the information that describes the 3D characteristics of the sound buffer.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

setConeAngles

public void setConeAngles(int inCone, int outCone, int applyFlag);

Sets the inside and outside angles of the sound projection cone for this sound buffer.

Return Value:

No return value.

Parameter | Description
inCone | Inside angle of the sound projection cone.
outCone | Outside angle of the sound projection cone.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360. For additional information see, Sound Projection Cones.

setConeOrientation

public void setConeOrientation(float x, float y, float z, int applyFlag);

Sets the orientation of the sound projection cone for this sound buffer. This method has no effect unless the cone angle and cone volume factor have also been set.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the new sound cone orientation vector.
y | The y coordinate of the new sound cone orientation vector.
z | The z-coordinate of the new sound cone orientation vector.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

The vector information in the orientation parameter of the getConeOrientation method represents the center of the sound cone. The default value is (0,0,1).

setConeOutsideVolume

public void setConeOutsideVolume(int coneOutsideVolume, int applyFlag);

Sets the current cone outside volume for this sound buffer.

Return Value:

No return value.

Parameter | Description
coneOutsideVolume | Cone outside volume for this sound buffer, in hundredths of decibels. Allowable values are between 0 (no attenuation) and -10,000 (silence).
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

Volume levels are represented by attenuation. Amplification is not currently supported by DirectSound.

setMaxDistance

public void setMaxDistance(float maxDistance, int applyFlag);

Sets the current maximum distance value.

Return Value:

No return value.

Parameter | Description
maxDistance | New maximum distance value.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

The maximum distance value is infinite by default.

setMinDistance

public void setMinDistance(float minDistance, int applyFlag);

Sets the current minimum distance value.

Return Value:

No return value.

Parameter | Description
minDistance | New minimum distance value.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

The minimum distance value is 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 m per unit) by default.

setMode

public void setMode(int mode, int applyFlag);

Sets the operation mode for 3D sound processing.

Return Value:

No return value.

Parameter Description
mode Flag specifying the 3D sound processing mode to be set.
DS3DMODE_DISABLE
Processing of 3D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

setPosition

public void setPosition(float x, float y, float z, int applyFlag);

Sets the sound buffer's current position, in distance units. Distance units are meters by default, but the units can be changed by using the setDistanceFactor method.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the new position vector.
y | The y coordinate of the new position vector.
z | The z-coordinate of the new position vector.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

setVelocity

public void setVelocity(float x, float y, float z, int applyFlag);

Sets the sound buffer's current velocity.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the new velocity vector.
y | The y coordinate of the new velocity vector.
z | The z-coordinate of the new velocity vector.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

Velocity is used for Doppler effects only. It does not actually move the buffer.


Class DirectSound3dListener

public class DirectSound3dListener implements
            IDirectSound3dListener
{
  // Methods
  public void commitDeferredSettings();
  public void getAllParameters(DS3dListener listener);
  public void getDistanceFactor(float[] distanceFactor);
  public void getDopplerFactor(float[] dopplerFactor);
  public void getOrientation(D3dVector orientFront,
        D3dVector orientTop);
  public void getPosition(D3dVector position);
  public void getRolloffFactor(float[] rolloffFactor);
  public void getVelocity(D3dVector velocity);
  public void setAllParameters(DS3dListener listener,
        int applyFlag);
  public void setDistanceFactor(float distanceFactor,
        int applyFlag);
  public void setDopplerFactor(float dopplerFactor, int applyFlag);
  public void setOrientation(float xFront, float yFront,
        float zFront, float xTop, float yTop, float zTop,
        int applyFlag);
  public void setPosition(float x, float y, float z, int applyFlag);
  public void setRolloffFactor(float rolloffFactor, int applyFlag);
  public void setVelocity(float x, float y, float z, int applyFlag);
}

Methods

commitDeferredSettings

public void commitDeferredSettings();

Commits any deferred settings made since the last call to this method.

Return Value:

No return value.

getAllParameters

public void getAllParameters(DS3dListener listener);

Retrieves information that describes the current state of the 3D world and listener.

Return Value:

No return value.

Parameter | Description
listener | The DS3dListener object that contains the current state of the 3D world and listener.

getDistanceFactor

public void getDistanceFactor(float[] distanceFactor);

Retrieves the current distance factor.

Return Value:

No return value.

Parameter | Description
distanceFactor | The array that will contain the current distance factor values.

getDopplerFactor

public void getDopplerFactor(float[] dopplerFactor);

Retrieves the current Doppler effect factor.

Return Value:

No return value.

Parameter | Description
dopplerFactor | The array that will contain the current Doppler factor values.

Remarks:

This Doppler factor has a range of 0 (no Doppler effects) to 10.0 (10 times the Doppler effects found in the physical world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

getOrientation

public void getOrientation(D3dVector orientFront, D3dVector orientTop);

Retrieves the listener's current orientation in vectors: a front vector and a top vector.

Return Value:

No return value.

Parameter | Description
orientFront | The D3dVector object that will contain the listener's front orientation vector.
orientTop | The D3dVector object that will contain the listener's top orientation vector.

Remarks:

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

getPosition

public void getPosition(D3dVector position);

Retrieves the listener's current position in distance units. By default, these units are meters, but this can be changed by calling the setDistanceFactor method.

Return Value:

No return value.

Parameter | Description
position | The D3dVector that will contain the listener's position vector.

getRolloffFactor

public void getRolloffFactor(float[] rolloffFactor);

Retrieves the current rolloff factor.

Return Value:

No return value.

Parameter | Description
rolloffFactor | Tha array that will contain the current rolloff factor values.

Remarks:

The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For additional information about the rolloff factor, see Rolloff Factor.

getVelocity

public void getVelocity(D3dVector velocity);

Retrieves the listener's current velocity.

Return Value:

No return value.

Parameter | Description
velocity | The D3dVector that will contain the listener's current velocity.

Remarks:

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the setPosition method. The default velocity is (0,0,0).

setAllParameters

public void setAllParameters(DS3dListener listener, int applyFlag);

Sets all 3D listener parameters from a given DS3dListener class that describes all aspects of the 3D listener at a moment in time.

Return Value:

No return value.

Parameter | Description
listener | Address of a DS3dListener class that contains information describing all current 3D listener parameters.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

setDistanceFactor

public void setDistanceFactor(float distanceFactor, int applyFlag);

Sets the current distance factor.

Return Value:

No return value.

Parameter | Description
distanceFactor | New distance factor.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

setDopplerFactor

public void setDopplerFactor(float dopplerFactor, int applyFlag);

Sets the current Doppler effect factor.

Return Value:

No return value.

Parameter | Description
dopplerFactor | New Doppler factor value.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

This Doppler factor has a range of 0 (no Doppler effects) to 10.0 (10 times the Doppler effects found in the physical world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

setOrientation

public void setOrientation(float xFront, float yFront, float zFront,
        float xTop, float yTop, float zTop, int applyFlag);

Sets the listeners orientation, given a front vector and a top vector.

Return Value:

No return value.

Parameter | Description
xFront | The x component of the front vector.
yFront | The y component of the front vector.
zFront | The z component of the front vector.
xTop | The x component of the top vector.
yTop | The y component of the top vector.
ztop | The x component of the top vector.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head.

setPosition

public void setPosition(float x, float y, float z, int applyFlag);

Retrieves the listener's current position in distance units. By default, these units are meters, but this can be changed by calling the DirectSound3dListener.setDistanceFactor method.

Return Value:

No return value.

Parameter | Description
x | The x component of the vector that will contain the listener's position.
y | The y component of the vector that will contain the listener's position.
z | The z component of the vector that will contain the listener's position.
applyFlag | Flag values.

setRolloffFactor

public void setRolloffFactor(float rolloffFactor, int applyFlag);

Sets the rolloff factor.

Return Value:

No return value.

Parameter | Description
rolloffFactor | New rolloff factor.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For additional information about the rolloff factor, see Rolloff Factor.

setVelocity

public void setVelocity(float x, float y, float z, int applyFlag);

Sets the listener's velocity.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the listener's new velocity vector.
y | The y coordinate of the listener's new velocity vector.
z | The z-coordinate of the listener's new velocity vector.
applyFlag Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
DS3D_IMMEDIATE

Remarks:

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the setPosition method. The default velocity is (0,0,0).


Class DirectSoundBuffer

public class DirectSoundBuffer implements IDirectSoundBuffer
{
  // Methods
  public DirectSound3dBuffer get3dBuffer();
  public DirectSound3dListener get3dListener();
  public void getCaps(DSBCaps caps);
  public void getCurrentPosition(DSCursors cursors);
  public void getFormat(byte[] format, int size);
  public WaveFormatEx getFormat();
  public int getFormatSize();
  public int getFrequency();
  public int getPan();
  public int getStatus();
  public int getVolume();
  public void play(int flags);
  public void restore();
  public void setCurrentPosition(int newPosition);
  public void setFormat(byte[] format);
  public void setFormat(WaveFormatEx format);
  public void setFrequency(int frequency);
  public void setPan(int pan);
  public void setVolume(int volume);
  public void stop();
  public void transferToSoundBuffer(DSResourceDesc resourceDesc,
        int flags);
  public void writeBuffer(int start, int size, byte[] buffer,
        int flags);
}

Applications use the methods of the DirectSoundBuffer class to create DirectSoundBuffer objects and set up the environment.

Note This class does not provide an initialize method. Use the DirectSound.createSoundBuffer method to create and initialize DirectSoundBuffer objects.

Methods

get3dBuffer

public DirectSound3dBuffer get3dBuffer();

Retrieves a DirectSound3dBuffer object for the DirectSound buffer.

get3dListener

public DirectSound3dListener get3dListener();

Retrieves a DirectSound3dListener object for the DirectSound buffer.

getCaps

public void getCaps(DSBCaps caps);

Retrieves the capabilities of the DirectSoundBuffer object.

Return Value:

No return value.

Parameter | Description
caps | A DSBCaps object that receives the capabilities of this sound buffer.

Remarks:

The DSBCaps object contains similar information to the DSBufferDesc object passed to the createSoundBuffer method, with some additional information. This additional information can include the location of the buffer, either in hardware or software, and some cost measures. Examples of cost measures include the time it takes to download to a hardware buffer and the processing overhead required to mix and play the buffer when it is in the system memory.

The flags specified in the flags field of the DSBCaps object are the same flags used by the DSBufferDesc object. The only difference is that in the DSBCaps object, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBufferDesc object, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

See Also: com.ms.directX.DirectSound, com.ms.directX.DSBCaps, com.ms.directX.DSBufferDesc

getCurrentPosition

public void getCurrentPosition(DSCursors cursors);

Retrieves the current position of the play and write cursors in the sound buffer.

Return Value:

No return value.

Parameter | Description
cursors | A DSCursors object that receives the current play and write positions in the DirectSoundBuffer object. These positions are offsets within the sound buffer and are specified in bytes.

Remarks:

The write cursor indicates the position at which it is safe to write new data into the buffer. The write cursor always leads the play cursor, typically by about 15 milliseconds worth of audio data.

It is always safe to change data that is behind the play position.

See Also: setCurrentPosition

getFormat

public void getFormat(byte[] format, int size);

Retrieves a description of the format of the sound data in the buffer.

Return Value:

No return value.

Parameter | Description
format | Array variable that receives a description of the sound data in the buffer.
size | Length of the array assigned to v1. DirectSound writes, at most, insz bytes to that array.

Remarks:

Before retrieving the format description, always use the getFormatSize method to query the DirectSoundBuffer object for the size of the format. Use this size to create an array of sufficient length to receive the format description.

See Also: getFormatSize, setFormat

getFormat

public WaveFormatEx getFormat();

Retrieves a description of the format of the sound data in the buffer.

Return Value:

Returns the WaveFormatEx object if successful; null otherwise.

See Also: setFormat

getFormatSize

public int getFormatSize();

Retrieves the size of the format information.

Return Value:

Returns the size.

getFrequency

public int getFrequency();

Retrieves the frequency, in samples per second, at which the buffer is being played. This value will be in the range of 100-100,000.

Return Value:

Returns the frequency at which the audio buffer is being played.

See Also: setFrequency

getPan

public int getPan();

Retrieves a variable that represents the relative volume between the left and right audio channels.

Return Value:

Returns the relative mix between the left and right speakers.

Remarks:

The returned value is measured in hundredths of a decibel (dB), in the range of -10,000 to 10,000. The value -10,000 means the right channel is attenuated by 100 dB. The value 10,000 means the left channel is attenuated by 100 dB. 0 is the neutral value; a return value of 0 means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than 0, one of the channels is at full volume and the other is attenuated.

A pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of -10,000 means that the right channel is silent and the sound is "all the way to the left," while a pan of 10,000 means that the left channel is silent and the sound is "all the way to the right."

The pan control acts cumulatively with the volume control.

See Also: getVolume, setPan, setVolume

getStatus

public int getStatus();

Retrieves the current status of the sound buffer.

Return Value:

Returns one value of DSBSTATUS_ type, specifying the status of the sound buffer.

getVolume

public int getVolume();

Retrieves the current volume for this sound buffer.

Return Value:

Returns the volume associated with the specified DirectSound buffer.

Remarks:

The volume is specified in hundredths of decibels (dB), and ranges from 0 to -10,000. The value 0 represents the original, unadjusted volume of the stream. The value -10,000 indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Amplification is not currently supported by DirectSound.

The decibel (dB) scale corresponds to the logarithmic hearing characteristics of the ear. For example, an attenuation of 10 dB makes a buffer sound half as loud, and an attenuation of 20 dB makes a buffer sound one quarter as loud.

See Also: setVolume

play

public void play(int flags);

Causes the sound buffer to play from the current position.

Return Value:

No return value.

Parameter | Description
flags | One value of DSBPLAY_ type, specifying how to play the buffer.

Remarks:

For secondary sound buffers, this method will cause the buffer to be mixed into the primary buffer and output to the sound device. If this is the first buffer to play, it will implicitly create a primary buffer and start playing that buffer; the application does not need to explicitly direct the primary buffer to play.

If the buffer specified in the method is already playing, the call to the method will succeed and the buffer will continue to play. However, the flags that define playback characteristics are superseded by the flags defined in the most recent call.

Primary buffers must be played with the DSBPLAY_LOOPING flag set.

For primary sound buffers, this method will cause them to start playing to the sound device. If the application is set to the DSSCL_WRITEPRIMARY cooperative level, this will cause the audio data in the primary buffer to be output to the sound device. However, if the application is set to any other cooperative level, this method will ensure that the primary buffer is playing even when no secondary buffers are playing; in that case, silence will be played. This may reduce processing overhead when sounds are started and stopped in sequence since the primary buffer will be playing continuously rather than stopping and starting between secondary buffers.

Note Before this method can be called on any sound buffer, the application must call the setCooperativeLevel method and specify a cooperative level, typically DSSCL_NORMAL. If setCooperativeLevel has not been called, the play method carries out no action.

See Also: com.ms.directX.DirectSound

restore

public void restore();

Restores the memory allocation for a lost sound buffer for the specified DirectSoundBuffer object.

Return Value:

No return value.

Remarks:

If the application does not have the input focus, restore may not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary sound buffer.

Once DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the play method. The getStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

See Also: play, getStatus

setCurrentPosition

public void setCurrentPosition(int newPosition);

Moves the current play cursor for secondary sound buffers.

Return Value:

No return value.

Parameter | Description
newPosition | New position, in bytes, from the beginning of the buffer that will be used when the sound buffer is played.

Remarks:

This method cannot be called on primary sound buffers.

If the buffer is playing, it will immediately move to the new position and continue. If it is not playing, it will begin from the new position the next time the play method is called.

See Also: getCurrentPosition, play

setFormat

public void setFormat(byte[] format);

Sets the format of the primary sound buffer for the application. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

Return Value:

No return value.

Parameter | Description
format | Array variable that specifies the new format for the primary sound buffer.

Remarks:

If this method is called on a primary buffer which is being accessed in write-primary cooperative level, the buffer must be stopped before setFormat is called. If this method is being called on a primary buffer for a non-write-primary level, DirectSound will implicitly stop the primary buffer, change the format, and restart the primary; the application does not need to do this explicitly.

A call to this method fails if the hardware does not directly support the requested pulse coded modulation (PCM) format. It will also fail if the calling application has the DSSCL_NORMAL cooperative level.

If a secondary sound buffer requires a format change, the application should create a new DirectSoundBuffer object using the new format.

DirectSound supports PCM formats; it does not currently support compressed formats.

See Also: getFormat

setFormat

public void setFormat(WaveFormatEx format);

Sets the format of the primary sound buffer for the application. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

Return Value:

No return value.

Parameter | Description
format | A WaveFormatEx object that specifies the wave format to set.

Remarks:

If this method is called on a primary buffer which is being accessed in write-primary cooperative level, the buffer must be stopped before setFormat is called. If this method is being called on a primary buffer for a non-write-primary level, DirectSound will implicitly stop the primary buffer, change the format, and restart the primary; the application does not need to do this explicitly.

A call to this method fails if the hardware does not directly support the requested pulse coded modulation (PCM) format. It will also fail if the calling application has the DSSCL_NORMAL cooperative level.

If a secondary sound buffer requires a format change, the application should create a new DirectSoundBuffer object using the new format.

DirectSound supports PCM formats; it does not currently support compressed formats.

See Also: getFormat

setFrequency

public void setFrequency(int frequency);

Sets the frequency at which the audio samples are played.

Return Value:

No return value.

Parameter | Description
frequency | New frequency, in Hz, at which to play the audio samples. The value must be between 100 and 100,000. If the value is 0, the frequency is reset to the current buffer format. This format is specified in the createSoundBuffer method.

Remarks:

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

See Also: getFrequency, play, setFormat, com.ms.directX.DirectSound

setPan

public void setPan(int pan);

Specifies the relative volume between the left and right channels.

Return Value:

No return value.

Parameter | Description
pan | Relative volume between the left and right channels. This value has a range of -10,000 to 10,000 and is measured in hundredths of a decibel.

Remarks:

0 is the neutral value for pan and indicates that both channels are at full volume (attenuated by 0 decibels). At any other setting, one of the channels is at full volume and the other is attenuated. For example, a pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume.

A pan of -10,000 means that the right channel is silent and the sound is "all the way to the left," while a pan of 10,000 means that the left channel is silent and the sound is "all the way to the right."

The pan control is cumulative with the volume control.

See Also: getPan, getVolume, setVolume

setVolume

public void setVolume(int volume);

Changes the volume of a sound buffer.

Return Value:

No return value.

Parameter | Description
volume | New volume requested for this sound buffer. Values range from 0 (0 dB, no volume adjustment) to -10,000 (-100 dB, essentially silent). DirectSound does not currently support amplification.

Remarks:

Volume units of are in hundredths of decibels, where 0 is the original volume of the stream.

Positive decibels correspond to amplification and negative decibels correspond to attenuation. The decibel scale corresponds to the logarithmic hearing characteristics of the ear. An attenuation of 10 dB makes a buffer sound half as loud; an attenuation of 20 dB makes a buffer sound one quarter as loud. DirectSound does not currently support amplification.

The pan control is cumulative with the volume control.

See Also: getPan, getVolume, setPan

stop

public void stop();

Causes the sound buffer to stop playing.

Return Value:

No return value.

Remarks:

For secondary sound buffers, stop will set the current position of the buffer to the sample that follows the last sample played. This means that if the play method is called on the buffer, it will continue playing where it left off.

For primary sound buffers, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the current position to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can only play from the beginning of the buffer.

However, if stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 dB.

See Also: play

transferToSoundBuffer

public void transferToSoundBuffer(DSResourceDesc resourceDesc, int flags);

Transfers the wave data from the given resource to the start of the sound buffer.

Return Value:

No return value.

Parameter | Description
resourceDesc | A DSResourceDesc object that specifies the wave resource to transfer.
flags | A value of DSBLOCK_ type specifying how the buffer should be locked before it receives the wave data.

Remarks:

This method automatically locks and unlocks the buffer before and after writing the data.

writeBuffer

public void writeBuffer(int start, int size, byte[] buffer, int flags);

Writes the contents of a buffer to the given position in the sound buffer.

Return Value:

No return value.

Parameter | Description
start | Offset, in bytes, from the start of the buffer to the position to begin writing the data. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the flags parameter.
size | Size, in bytes, of the portion of the buffer to write to.
buffer | Array variable that contain the data to write.
flags | A value of DSBLOCK_ type specifying how the buffer should be locked before it is written to.

Remarks:

This method automatically locks and unlocks the buffer before and after writing the data.


Class DirectSoundResource

public class DirectSoundResource implements
            IDirectSoundResource
{
  // Methods
  public void loadWaveFile(String name,
        DSResourceDesc resourceDesc, byte[] wave);
  public WaveFormatEx loadWaveFile(String name,
        DSResourceDesc resourceDesc);
  public void loadWaveResource(int handle,
        DSResourceDesc resourceDesc, byte[] wave);
  public WaveFormatEx loadWaveResource(int handle,
        DSResourceDesc resourceDesc);
  public void readBuffer(int sourceIndex, int destIndex, int size,
        DSResourceDesc resourceDesc, byte[] buffer, int maxbuf);
}

Applications use the DirectSoundResource class to load wave format objects.

Methods

loadWaveFile

public void loadWaveFile(String name, DSResourceDesc resourceDesc,
        byte[] wave);

Loads a wave resource from the given file.

Return Value:

No return value.

Parameter | Description
name | Name of the file that contains the resource.
resourceDesc | The DSResourceDesc object that receives a description of the resource.
wave | Array variable that receives the wave resource data.

loadWaveFile

public WaveFormatEx loadWaveFile(String name, DSResourceDesc resourceDesc);

Loads a wave resource from a file and returns it as a wave format object.

Return Value:

Returns the WaveFormatEx object if successful; null otherwise.

Parameter | Description
name | Name of the file that contains the resource.
resourceDesc | The DSResourceDesc object that receives a description of the resource.

loadWaveResource

public void loadWaveResource(int handle, DSResourceDesc resourceDesc,
        byte[] wave);

Loads a wave resource from the given module.

Return Value:

No return value.

Parameter | Description
handle | Handle of the module containing the resource.
resourceDesc | The DSResourceDesc object that receives a description of the resource.
wave | Array variable that receives the wave resource data.

loadWaveResource

public WaveFormatEx loadWaveResource(int handle,
        DSResourceDesc resourceDesc);

Loads a wave resource and returns it as a wave format object.

Return Value:

Returns the WaveFormatEx object if successful; null otherwise.

Parameter | Description
handle | Handle of the module containing the resource.
resourceDesc | The DSResourceDesc object that receives a description of the resource.

readBuffer

public void readBuffer(int sourceIndex, int destIndex, int size,
        DSResourceDesc resourceDesc, byte[] buffer, int maxbuf);

Reads an amount of data from a resource into the given buffer.

Return Value:

No return value.

Parameter | Description
sourceIndex | Index into the resource, indicating the first byte of data to read.
destIndex | Index into the buffer, indicating to first byte to receive the data to be read.
size | Number of bytes of data to read.
resourceDesc | The DSResourceDesc object that contains a description of the resource. The fields of this object must have been previously initialized by using loadWaveResource or loadWaveFile.
buffer | Array variable that receives the data.
maxbuf | Length of the buffer array. The method retrieves no more than this amount of data.

Remarks:

If destIndex is non-zero and destIndex + size is greater than maxbuf, the method fills to the end of the buffer, then wraps back to the beginning of the buffer and continues to fill the buffer until the method reads the requested data or encounters the position specified by destIndex.


Class DPCaps

public final class DPCaps
{
  // Fields
  public int flags;
  public int headerLength;
  public int hundredBaud;
  public int latency;
  public int maxBufferSize;
  public int maxLocalPlayers;
  public int maxPlayers;
  public int maxQueueSize;
  public int timeOut;
}

Contains the capabilities of a DirectPlay object after a call to the getCaps or getPlayerCaps methods. Any of these capabilities may differ depending on whether guaranteed or non-guaranteed capabilities are requested. This class is read-only.

See also DirectPlay2, send.

Fields

flags
One or more values of DPCAPS_ type, indicating the properties of the DirectPlay object.
headerLength
Size, in bytes, of the header that will be added to player messages by this DirectPlay object. Note that the header size depends on which service provider is in use.
hundredBaud
Bandwidth specified in multiples of one hundred bits per second. For example, a value of 24 specifies 2400 baud.
latency
Latency estimate by the service provider, in milliseconds. If this value is 0, DirectPlay cannot provide an estimate. Accuracy for some service providers rests on application-to-application testing, taking into consideration the average message size. Latency may differ depending on whether the application is interested in guaranteed or non-guaranteed message delivery.
maxBufferSize
Maximum number of bytes that can be sent in a single packet by this service provider. Larger messages will be sent using more than one packet.
maxLocalPlayers
Maximum number of local players supported in a session.
maxPlayers
Maximum number of local and remote players supported in a session by this DirectPlay object.
maxQueueSize
This field is no longer used.
timeOut
Service provider's suggested timeout value. By default, DirectPlay will use this timeout value when waiting for replies to messages.


Class DPSessionDesc

public final class DPSessionDesc
{
  // Fields
  public int currentPlayers;
  public int flags;
  public int maxPlayers;
  public int reserved1;
  public int reserved2;
  public int user1;
  public int user2;
  public int user3;
  public int user4;
}

Contains a description of the capabilities of an DirectPlay session.

See also enumSessions.

Fields

currentPlayers
Current players and groups in the session.
flags
One of DPOPEN_CREATESESSION, DPOPEN_OPENSESSION, or DPENUMSESSIONS_ALL.
maxPlayers
Maximum number of players and groups allowed in this session. This field is ignored if the application is not creating a new session.
reserved1
Reserved.
reserved2
Reserved.
user1
User-specific data for the game or session.
user2
User-specific data for the game or session.
user3
User-specific data for the game or session.
user4
User-specific data for the game or session.


Class DS3dBuffer

public final class DS3dBuffer
{
  // Fields
  public float coneOrientationX;
  public float coneOrientationY;
  public float coneOrientationZ;
  public int coneOutsideVolume;
  public int insideConeAngle;
  public float maxDistance;
  public float minDistance;
  public int mode;
  public int outsideConeAngle;
  public float positionVectorX;
  public float positionVectorY;
  public float positionVectorZ;
  public float velocityVectorX;
  public float velocityVectorY;
  public float velocityVectorZ;
}

Fields

coneOrientationX
The x component of the D3dVector that describes the current orientation of this 3D buffer's sound projection cone.
coneOrientationY
The y component of the D3dVector that describes the current orientation of this 3D buffer's sound projection cone.
coneOrientationZ
The z component of the D3dVector that describes the current orientation of this 3D buffer's sound projection cone.
coneOutsideVolume
The cone outside volume.
insideConeAngle
The angle of the inside sound projection cone.
maxDistance
The maximum distance.
minDistance
The minimum distance.
mode
The 3D sound processing mode to be set. May be one of the following:
DS3DMODE_DISABLE
DS3DMODE_HEADRELATIVE
DS3DMODE_NORMAL
outsideConeAngle
The angle of the outside sound projection cone.
positionVectorX
The x component of the D3dVector that describes the current position of this 3D sound buffer.
positionVectorY
The y component of the D3dVector that describes the current position of this 3D sound buffer.
positionVectorZ
The z component of the D3dVector that describes the current position of this 3D sound buffer.
velocityVectorX
The x component of the D3dVector that describes the current velocity of this 3D sound buffer.
velocityVectorY
The y component of the D3dVector that describes the current velocity of this 3D sound buffer.
velocityVectorZ
The z component of the D3dVector that describes the current velocity of this 3D sound buffer.


Class DS3dListener

public final class DS3dListener
{
  // Fields
  public float flDistanceFactor;
  public float flDopplerFactor;
  public float flRolloffFactor;
  public float orientFrontX;
  public float orientFrontY;
  public float orientFrontZ;
  public float orientTopX;
  public float orientTopY;
  public float orientTopZ;
  public float positionVectorX;
  public float positionVectorY;
  public float positionVectorZ;
  public float velocityVectorX;
  public float velocityVectorY;
  public float velocityVectorZ;
}

Fields

flDistanceFactor
The current distance factor.
flDopplerFactor
The current Doppler factor.
flRolloffFactor
The current rolloff factor.
orientFrontX
The x element of the D3dVector that describes the listener's front orientation.
orientFrontY
The y element of the D3dVector that describes the listener's front orientation.
orientFrontZ
The z element of the D3dVector that describes the listener's front orientation.
orientTopX
The x element of the D3dVector that describes the listener's top orientation.
orientTopY
The y element of the D3dVector that describes the listener's top orientation.
orientTopZ
The z element of the D3dVector that describes the listener's top orientation.
positionVectorX
The x element of the D3dVector that describes the listener's position.
positionVectorY
The y element of the D3dVector that describes the listener's position.
positionVectorZ
The z element of the D3dVector that describes the listener's position.
velocityVectorX
The x element of the D3dVector that describes the listener's velocity.
velocityVectorY
The y element of the D3dVector that describes the listener's velocity.
velocityVectorZ
The z element of the D3dVector that describes the listener's velocity.


Class DSBCaps

public final class DSBCaps
{
  // Fields
  public int bufferBytes;
  public int flags;
  public int playCpuOverhead;
  public int unlockTransferRate;
}

Specifies the capabilities of a DirectSound buffer object, for use by the getCaps method.

See also DirectSoundBuffer.

Fields

bufferBytes
Size of this buffer, in bytes.
flags
One or more values of DSBCAPS type that specify buffer-object capabilities.
playCpuOverhead
Specifies the processing overhead as a percentage of main processing cycles needed to mix this sound buffer. For hardware buffers, this field will be 0 because the mixing is performed by the sound device. For software buffers, this field depends on the buffer format and the speed of the system processor.
unlockTransferRate
Specifies the rate, in kilobytes per second, that data is transferred to the buffer memory when unlock is called. High-performance applications can use this value to determine the time required for unlock to execute. For software buffers located in system memory, the rate will be very high since no processing is required. For hardware buffers, the rate may be slower because the buffer might have to be downloaded to the sound card, which may have a limited transfer rate.


Class DSBufferDesc

public final class DSBufferDesc
{
  // Fields
  public int bufferBytes;
  public int flags;
}

Describes the necessary characteristics of a new DirectSoundBuffer object. This class is used by the createSoundBuffer method.

Fields

bufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating primary buffers.
flags
One or more values of DBSCAPS_ type, identifying the capabilities to include when creating a new DirectSoundBuffer object.


Class DSCaps

public final class DSCaps
{
  // Fields
  public int flags;
  public int freeHw3DAllBuffers;
  public int freeHw3DStaticBuffers;
  public int freeHw3DStreamingBuffers;
  public int freeHwMemBytes;
  public int freeHwMixingAllBuffers;
  public int freeHwMixingStaticBuffers;
  public int freeHwMixingStreamingBuffers;
  public int maxContigFreeHwMemBytes;
  public int maxHw3DAllBuffers;
  public int maxHw3DStaticBuffers;
  public int maxHw3DStreamingBuffers;
  public int maxHwMixingAllBuffers;
  public int maxHwMixingStaticBuffers;
  public int maxHwMixingStreamingBuffers;
  public int maxSecondarySampleRate;
  public int minSecondarySampleRate;
  public int playCpuOverheadSwBuffers;
  public int primaryBuffers;
  public int totalHwMemBytes;
  public int unlockTransferRateHwBuffers;
}

Specifies the capabilities of a DirectSound device for use by the getCaps method.

Fields

flags
One or more values of DSCAPS type, specifying device capabilities.
freeHw3DAllBuffers
Description of the free, or unallocated, hardware 3D positional capabilities of the device.
freeHw3DStaticBuffers
Description of the free, or unallocated, hardware 3D positional capabilities of the device.
freeHw3DStreamingBuffers
Description of the free, or unallocated, hardware 3D positional capabilities of the device. These will all be 0 for the first release.
freeHwMemBytes
Size, in bytes, of the free memory on the sound card.
freeHwMixingAllBuffers
Description of the free hardware mixing capabilities of the device.
freeHwMixingStaticBuffers
Description of the free hardware mixing capabilities of the device.
freeHwMixingStreamingBuffers
Description of the free, or unallocated, hardware mixing capabilities of the device. These freeHwMixing values can be used by an application to determine whether hardware resources are available for allocation to a secondary sound buffer. Also, by comparing these values to the fields that specify maximum mixing capabilities, the resources that are already allocated can be determined.
maxContigFreeHwMemBytes
Size, in bytes, of the largest contiguous block of free memory on the sound card.
maxHw3DAllBuffers
Description of the hardware 3D positional capabilities of the device. These will all be 0 for the first release.
maxHw3DStaticBuffers
Description of the hardware 3D positional capabilities of the device. These will all be 0 for the first release.
maxHw3DStreamingBuffers
Description of the hardware 3D positional capabilities of the device.
maxHwMixingAllBuffers
Specifies the total number of buffers that can be mixed in hardware.
maxHwMixingStaticBuffers
Specifies the maximum number of static sound buffers.
maxHwMixingStreamingBuffers
Specifies the maximum number of streaming sound buffers.

Note The value for maxHwMixingAllBuffers may be less than the sum of maxHwMixingStaticBuffers and maxHwMixingStreamingBuffers. Resource trade-offs frequently occur.

maxSecondarySampleRate
Maximum sample rate specification that is supported by this device's hardware secondary sound buffers.
minSecondarySampleRate
Minimum sample rate specification that is supported by this device's hardware secondary sound buffers.
playCpuOverheadSwBuffers
Description of the processing overhead, as a percentage of the central processing unit, needed to mix software buffers (those located in main system memory). This varies according to the bus type, the processor type, and the clock speed.

The unlock transfer rate for software buffers is 0 because the data does not need to be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

primaryBuffers
Number of primary buffers supported. This value will always be 1 for this release.
totalHwMemBytes
Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.
unlockTransferRateHwBuffers
Description of the rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers (those located in onboard sound memory). This and the number of bytes transferred determines the duration of a call to the unlock method.


Class DSCursors

public final class DSCursors
{
  // Fields
  public int play;
  public int write;
}

Contains the play and write positions in a DirectSoundBuffer object. Used with the getCurrentPosition method.

Fields

play
Current play position in the DirectSoundBuffer object. This position is an offset within the sound buffer and is specified in bytes.
write
Current write position in the DirectSoundBuffer object. This position is an offset within the sound buffer and is specified in bytes.


Class DSResourceDesc

public final class DSResourceDesc
{
  // Fields
  public int bufferBytes;
  public int flags;
}

Contains information about a loaded resource. Used by the DirectSoundResource.loadWaveResource and DirectSoundResource.loadWaveFile methods.

See also DirectSoundResource.

Fields

bufferBytes
Number of bytes in the buffer identified by the private lpBufferData member.
flags
Reserved.


Class JoyCaps

public final class JoyCaps
{
  // Fields
  public int caps;
  public int maxAxes;
  public int maxButtons;
  public char mid;
  public int numAxes;
  public int numButtons;
  public int periodMax;
  public int periodMin;
  public char pid;
  public int rMax;
  public int rMin;
  public int uMax;
  public int uMin;
  public int vMax;
  public int vMin;
  public int xMax;
  public int xMin;
  public int yMax;
  public int yMin;
  public int zMax;
  public int zMin;
}

Fields

caps
Joystick capabilities. These may be one of the following:
JOYCAPS_HASPOV
The joystick has Point-Of-View information.
JOYCAPS_HASR
The joystick has rudder (fourth axis) information.
JOYCAPS_HASU
The joystick has u-coordinate information.
JOYCAPS_HASV
The joystick has v-coordinate information.
JOYCAPS_HASZ
The joystick has z-coordinate information
JOYCAPS_POV4DIR
The joystick Point-Of-View supports discrete values.
JOYCAPS_POVCTS
The joystick Point-Of-View supports continuous degree bearings.
maxAxes
The maximum number of axes supported by the joystick.
maxButtons
The maximum number of buttons a joystick supports.
mid
Manufacturer identifier.
numAxes
The number of axes currently supported by the joystick.
numButtons
The current number of joystick buttons in use.
periodMax
The maximum polling frequency supported once an application has captured a joystick.
periodMin
The minumim polling frequency supported once an application has captured a joystick.
pid
Product identifier.
rMax
Maximum r-axis (the fourth, or rudder-axis) coordinate.
rMin
Minimum r-axis (the fourth, or rudder-axis) coordinate.
uMax
Maximum u-axis (fifth axis) coordinate.
uMin
Minimum u-axis (fifth axis) coordinate.
vMax
Maximum v-axis (sixth axis) coordinate.
vMin
Minimum v-axis (sixth axis) coordinate.
xMax
Maximum x-axis coordinate.
xMin
Minimum x-axis coordinate.
yMax
Maximum y-axis coordinate.
yMin
Minimum y-axis coordinate.
zMax
Maximum z-axis coordinate.
zMin
Minimum z-axis coordinate.


Class JoyInfo

public final class JoyInfo
{
  // Fields
  public int buttonNumber;
  public int buttons;
  public int flags;
  public int pov;
  public int rPos;
  public int uPos;
  public int vPos;
  public int xPos;
  public int yPos;
  public int zPos;
}

Fields

buttonNumber
Current button number that is pressed.
buttons
Current state of the 32 joystick buttons. The value of this member can be set to any combination of JOY_BUTTON n flags, where n is a value ranging from 1 to 32. Each value corresponds to the button that is pressed.
flags
Flags that indicate if information returned in this class is valid. Members that do not contain valid information are set to 0. These flags may be one or more of the JOY_RETURN* and JOY_CAL_ types.
pov
Current position of the Point-Of-View control. Values for this member range from 0 to 35,900. These values represent each views angle, in degress, multiplied by 100.
rPos
Current position of the rudder, or fourth joystick axis.
uPos
Current positions of the fifth joysick axis.
vPos
Current positions of the sixth joysick axis.
xPos
Current x coordinate.
yPos
Current y coordinate.
zPos
Current z coordinate.


Class PaletteEntry

public final class PaletteEntry
{
  // Fields
  public int peBlue;
  public int peFlags;
  public int peGreen;
  public int peRed;

  // Constructors
  public PaletteEntry();
  public PaletteEntry(byte[] b, int count, int flags);
}

Specifies a color palette entry when creating palettes using the createPalette method.

Note that the fields of this class take values indicating the intensity of red, green, or blue. Intensity values are unsigned values in the range 0 to 255, unlike byte values which range from -128 to 127. When assigning intensity values to these fields, you may need to cast such values to byte type.

Constructors

PaletteEntry

public PaletteEntry();

Creates an uninitialized palette entry object.

PaletteEntry

public PaletteEntry(byte[] b, int count, int flags);

Creates an initialized palette entry object.

Parameter | Description
b | Array variable that contains the initial palette entry data. The data must be in the order: red intensity, green intensity, blue intensity, and flags.
count | Index into b of palette entry data for this object.
flags | Can be 0 or DDPCAPS_8BITENTRIES.

Remarks:

Although b can contain data for more than one palette entry, count specifies which data to use to initialize the object being created.

Fields

peBlue
Intensity of blue.
peFlags
One value of D3DPAL_ type.
peGreen
Intensity of green.
peRed
Intensity of red.


Class Rect

public final class Rect
{
  // Fields
  public int bottom;
  public int left;
  public int right;
  public int top;
}

Specifies the corners of a rectangle.

Fields

bottom
The y coordinate of the lower-right corner.
left
The x coordinate of the upper-left corner.
right
The x coordinate of the lower-right corner.
top
The y coordinate of the upper-left corner.


Class WaveFormatEx

public final class WaveFormatEx
{
  // Fields
  public int avgBytesPerSec;
  public int bitsPerSample;
  public int blockAlign;
  public int channels;
  public byte[] extra;
  public int formatTag;
  public int samplesPerSec;
  public int size;
}

Specifies the format of data in a sound buffer.

Fields

avgBytesPerSec
Required average data-transfer rate, in bytes per second, for the format tag.
bitsPerSample
Bits per sample for the formatTag format type. If a compression scheme cannot define a bits-per-sample value, this field is zero.
blockAlign
Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the formatTag format type. Playback and record software must process a multiple of blockAlign bytes of data at a time. Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).
channels
Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.
extra
Array variable that contains extra format information.
formatTag
Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms.
samplesPerSec
Sample rate, in samples per second (hertz), that each channel should be played or recorded.
size
Size, in bytes, of extra format information.


Interface DirectXConstants

public interface DirectXConstants
{
  // Fields
  public final static int D3DBLEND_BOTHINVSRCALPHA;
  public final static int D3DBLEND_BOTHSRCALPHA;
  public final static int D3DBLEND_DESTALPHA;
  public final static int D3DBLEND_DESTCOLOR;
  public final static int D3DBLEND_INVDESTALPHA;
  public final static int D3DBLEND_INVDESTCOLOR;
  public final static int D3DBLEND_INVSRCALPHA;
  public final static int D3DBLEND_INVSRCCOLOR;
  public final static int D3DBLEND_ONE;
  public final static int D3DBLEND_SRCALPHA;
  public final static int D3DBLEND_SRCALPHASAT;
  public final static int D3DBLEND_SRCCOLOR;
  public final static int D3DBLEND_ZERO;
  public final static int D3DCLEAR_TARGET;
  public final static int D3DCLEAR_ZBUFFER;
  public final static int D3DCLIP_BACK;
  public final static int D3DCLIP_BOTTOM;
  public final static int D3DCLIP_FRONT;
  public final static int D3DCLIP_GEN0;
  public final static int D3DCLIP_GEN1;
  public final static int D3DCLIP_GEN2;
  public final static int D3DCLIP_GEN3;
  public final static int D3DCLIP_GEN4;
  public final static int D3DCLIP_GEN5;
  public final static int D3DCLIP_LEFT;
  public final static int D3DCLIP_RIGHT;
  public final static int D3DCLIP_TOP;
  public final static int D3DCMP_ALWAYS;
  public final static int D3DCMP_EQUAL;
  public final static int D3DCMP_GREATER;
  public final static int D3DCMP_GREATEREQUAL;
  public final static int D3DCMP_LESS;
  public final static int D3DCMP_LESSEQUAL;
  public final static int D3DCMP_NEVER;
  public final static int D3DCMP_NOTEQUAL;
  public final static int D3DCOLOR_MONO;
  public final static int D3DCOLOR_RGB;
  public final static int D3DCULL_CCW;
  public final static int D3DCULL_CW;
  public final static int D3DCULL_NONE;
  public final static int D3DDD_BCLIPPING;
  public final static int D3DDD_COLORMODEL;
  public final static int D3DDD_DEVCAPS;
  public final static int D3DDD_DEVICERENDERBITDEPTH;
  public final static int D3DDD_DEVICEZBUFFERBITDEPTH;
  public final static int D3DDD_LIGHTINGCAPS;
  public final static int D3DDD_LINECAPS;
  public final static int D3DDD_MAXBUFFERSIZE;
  public final static int D3DDD_MAXVERTEXCOUNT;
  public final static int D3DDD_TRANSFORMCAPS;
  public final static int D3DDD_TRICAPS;
  public final static int D3DDEB_BUFSIZE;
  public final static int D3DDEB_CAPS;
  public final static int D3DDEB_LPDATA;
  public final static int D3DDEBCAPS_MEM;
  public final static int D3DDEBCAPS_SYSTEMMEMORY;
  public final static int D3DDEBCAPS_VIDEOMEMORY;
  public final static int D3DDEVCAPS_EXECUTESYSTEMMEMORY;
  public final static int D3DDEVCAPS_EXECUTEVIDEOMEMORY;
  public final static int D3DDEVCAPS_FLOATTLVERTEX;
  public final static int D3DDEVCAPS_SORTDECREASINGZ;
  public final static int D3DDEVCAPS_SORTEXACT;
  public final static int D3DDEVCAPS_SORTINCREASINGZ;
  public final static int D3DDEVCAPS_TEXTURESYSTEMMEMORY;
  public final static int D3DDEVCAPS_TEXTUREVIDEOMEMORY;
  public final static int D3DDEVCAPS_TLVERTEXSYSTEMMEMORY;
  public final static int D3DDEVCAPS_TLVERTEXVIDEOMEMORY;
  public final static int D3DEXECUTE_CLIPPED;
  public final static int D3DEXECUTE_UNCLIPPED;
  public final static int D3DFDS_ALPHACMPCAPS;
  public final static int D3DFDS_COLORMODEL;
  public final static int D3DFDS_DSTBLENDCAPS;
  public final static int D3DFDS_GUID;
  public final static int D3DFDS_HARDWARE;
  public final static int D3DFDS_LINES;
  public final static int D3DFDS_MISCCAPS;
  public final static int D3DFDS_RASTERCAPS;
  public final static int D3DFDS_SHADECAPS;
  public final static int D3DFDS_SRCBLENDCAPS;
  public final static int D3DFDS_TEXTUREADDRESSCAPS;
  public final static int D3DFDS_TEXTUREBLENDCAPS;
  public final static int D3DFDS_TEXTURECAPS;
  public final static int D3DFDS_TEXTUREFILTERCAPS;
  public final static int D3DFDS_TRIANGLES;
  public final static int D3DFDS_ZCMPCAPS;
  public final static int D3DFILL_POINT;
  public final static int D3DFILL_SOLID;
  public final static int D3DFILL_WIREFRAME;
  public final static int D3DFILTER_LINEAR;
  public final static int D3DFILTER_LINEARMIPLINEAR;
  public final static int D3DFILTER_LINEARMIPNEAREST;
  public final static int D3DFILTER_MIPLINEAR;
  public final static int D3DFILTER_MIPNEAREST;
  public final static int D3DFILTER_NEAREST;
  public final static int D3DFOG_EXP;
  public final static int D3DFOG_EXP2;
  public final static int D3DFOG_LINEAR;
  public final static int D3DFOG_NONE;
  public final static int D3DLIGHT_DIRECTIONAL;
  public final static int D3DLIGHT_GLSPOT;
  public final static int D3DLIGHT_PARALLELPOINT;
  public final static int D3DLIGHT_POINT;
  public final static int D3DLIGHT_SPOT;
  public final static int D3DLIGHTSTATE_AMBIENT;
  public final static int D3DLIGHTSTATE_COLORMODEL;
  public final static int D3DLIGHTSTATE_FOGDENSITY;
  public final static int D3DLIGHTSTATE_FOGEND;
  public final static int D3DLIGHTSTATE_FOGMODE;
  public final static int D3DLIGHTSTATE_FOGSTART;
  public final static int D3DLIGHTSTATE_MATERIAL;
  public final static int D3DOP_BRANCHFORWARD;
  public final static int D3DOP_EXIT;
  public final static int D3DOP_LINE;
  public final static int D3DOP_MATRIXLOAD;
  public final static int D3DOP_MATRIXMULTIPLY;
  public final static int D3DOP_POINT;
  public final static int D3DOP_PROCESSVERTICES;
  public final static int D3DOP_SETSTATUS;
  public final static int D3DOP_SPAN;
  public final static int D3DOP_STATELIGHT;
  public final static int D3DOP_STATERENDER;
  public final static int D3DOP_STATETRANSFORM;
  public final static int D3DOP_TEXTURELOAD;
  public final static int D3DOP_TRIANGLE;
  public final static int D3DPAL_FREE;
  public final static int D3DPAL_READONLY;
  public final static int D3DPAL_RESERVED;
  public final static int D3DPBLENDCAPS_BOTHINVSRCALPHA;
  public final static int D3DPBLENDCAPS_BOTHSRCALPHA;
  public final static int D3DPBLENDCAPS_DESTALPHA;
  public final static int D3DPBLENDCAPS_DESTCOLOR;
  public final static int D3DPBLENDCAPS_INVDESTALPHA;
  public final static int D3DPBLENDCAPS_INVDESTCOLOR;
  public final static int D3DPBLENDCAPS_INVSRCALPHA;
  public final static int D3DPBLENDCAPS_INVSRCCOLOR;
  public final static int D3DPBLENDCAPS_ONE;
  public final static int D3DPBLENDCAPS_SRCALPHA;
  public final static int D3DPBLENDCAPS_SRCALPHASAT;
  public final static int D3DPBLENDCAPS_SRCCOLOR;
  public final static int D3DPBLENDCAPS_ZERO;
  public final static int D3DPCMPCAPS_ALWAYS;
  public final static int D3DPCMPCAPS_EQUAL;
  public final static int D3DPCMPCAPS_GREATER;
  public final static int D3DPCMPCAPS_GREATEREQUAL;
  public final static int D3DPCMPCAPS_LESS;
  public final static int D3DPCMPCAPS_LESSEQUAL;
  public final static int D3DPCMPCAPS_NEVER;
  public final static int D3DPCMPCAPS_NOTEQUAL;
  public final static int D3DPMISCCAPS_CONFORMANT;
  public final static int D3DPMISCCAPS_CULLCCW;
  public final static int D3DPMISCCAPS_CULLCW;
  public final static int D3DPMISCCAPS_CULLNONE;
  public final static int D3DPMISCCAPS_LINEPATTERNREP;
  public final static int D3DPMISCCAPS_MASKPLANES;
  public final static int D3DPMISCCAPS_MASKZ;
  public final static int D3DPRASTERCAPS_DITHER;
  public final static int D3DPRASTERCAPS_FOGTABLE;
  public final static int D3DPRASTERCAPS_FOGVERTEX;
  public final static int D3DPRASTERCAPS_PAT;
  public final static int D3DPRASTERCAPS_ROP2;
  public final static int D3DPRASTERCAPS_STIPPLE;
  public final static int D3DPRASTERCAPS_SUBPIXEL;
  public final static int D3DPRASTERCAPS_SUBPIXELX;
  public final static int D3DPRASTERCAPS_XOR;
  public final static int D3DPRASTERCAPS_ZTEST;
  public final static int D3DPROCESSVERTICES_COPY;
  public final static int D3DPROCESSVERTICES_NOCOLOR;
  public final static int D3DPROCESSVERTICES_OPMASK;
  public final static int D3DPROCESSVERTICES_TRANSFORM;
  public final static int D3DPROCESSVERTICES_TRANSFORMLIGHT;
  public final static int D3DPROCESSVERTICES_UPDATEEXTENTS;
  public final static int D3DPSHADECAPS_ALPHAFLATBLEND;
  public final static int D3DPSHADECAPS_ALPHAFLATSTIPPLED;
  public final static int D3DPSHADECAPS_ALPHAGOURAUDBLEND;
  public final static int D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED;
  public final static int D3DPSHADECAPS_ALPHAPHONGBLEND;
  public final static int D3DPSHADECAPS_ALPHAPHONGSTIPPLED;
  public final static int D3DPSHADECAPS_COLORFLATMONO;
  public final static int D3DPSHADECAPS_COLORFLATRGB;
  public final static int D3DPSHADECAPS_COLORGOURAUDMONO;
  public final static int D3DPSHADECAPS_COLORGOURAUDRGB;
  public final static int D3DPSHADECAPS_COLORPHONGMONO;
  public final static int D3DPSHADECAPS_COLORPHONGRGB;
  public final static int D3DPSHADECAPS_FOGFLAT;
  public final static int D3DPSHADECAPS_FOGGOURAUD;
  public final static int D3DPSHADECAPS_FOGPHONG;
  public final static int D3DPSHADECAPS_SPECULARFLATMONO;
  public final static int D3DPSHADECAPS_SPECULARFLATRGB;
  public final static int D3DPSHADECAPS_SPECULARGOURAUDMONO;
  public final static int D3DPSHADECAPS_SPECULARGOURAUDRGB;
  public final static int D3DPSHADECAPS_SPECULARPHONGMONO;
  public final static int D3DPSHADECAPS_SPECULARPHONGRGB;
  public final static int D3DPTADDRESSCAPS_CLAMP;
  public final static int D3DPTADDRESSCAPS_MIRROR;
  public final static int D3DPTADDRESSCAPS_WRAP;
  public final static int D3DPTBLENDCAPS_COPY;
  public final static int D3DPTBLENDCAPS_DECAL;
  public final static int D3DPTBLENDCAPS_DECALALPHA;
  public final static int D3DPTBLENDCAPS_DECALMASK;
  public final static int D3DPTBLENDCAPS_MODULATE;
  public final static int D3DPTBLENDCAPS_MODULATEALPHA;
  public final static int D3DPTBLENDCAPS_MODULATEMASK;
  public final static int D3DPTEXTURECAPS_ALPHA;
  public final static int D3DPTEXTURECAPS_BORDER;
  public final static int D3DPTEXTURECAPS_PERSPECTIVE;
  public final static int D3DPTEXTURECAPS_POW2;
  public final static int D3DPTEXTURECAPS_SQUAREONLY;
  public final static int D3DPTEXTURECAPS_TRANSPARENCY;
  public final static int D3DPTFILTERCAPS_LINEAR;
  public final static int D3DPTFILTERCAPS_LINEARMIPLINEAR;
  public final static int D3DPTFILTERCAPS_LINEARMIPNEAREST;
  public final static int D3DPTFILTERCAPS_MIPLINEAR;
  public final static int D3DPTFILTERCAPS_MIPNEAREST;
  public final static int D3DPTFILTERCAPS_NEAREST;
  public final static int D3DRENDERSTATE_ALPHAFUNC;
  public final static int D3DRENDERSTATE_ALPHAREF;
  public final static int D3DRENDERSTATE_ALPHATESTENABLE;
  public final static int D3DRENDERSTATE_ANTIALIAS;
  public final static int D3DRENDERSTATE_BLENDENABLE;
  public final static int D3DRENDERSTATE_CULLMODE;
  public final static int D3DRENDERSTATE_DESTBLEND;
  public final static int D3DRENDERSTATE_DITHERENABLE;
  public final static int D3DRENDERSTATE_FILLMODE;
  public final static int D3DRENDERSTATE_FOGCOLOR;
  public final static int D3DRENDERSTATE_FOGENABLE;
  public final static int D3DRENDERSTATE_FOGTABLEDENSITY;
  public final static int D3DRENDERSTATE_FOGTABLEEND;
  public final static int D3DRENDERSTATE_FOGTABLEMODE;
  public final static int D3DRENDERSTATE_FOGTABLESTART;
  public final static int D3DRENDERSTATE_LASTPIXEL;
  public final static int D3DRENDERSTATE_LINEPATTERN;
  public final static int D3DRENDERSTATE_MONOENABLE;
  public final static int D3DRENDERSTATE_PLANEMASK;
  public final static int D3DRENDERSTATE_ROP2;
  public final static int D3DRENDERSTATE_SHADEMODE;
  public final static int D3DRENDERSTATE_SPECULARENABLE;
  public final static int D3DRENDERSTATE_SRCBLEND;
  public final static int D3DRENDERSTATE_STIPPLEDALPHA;
  public final static int D3DRENDERSTATE_STIPPLEENABLE;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN00;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN01;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN02;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN03;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN04;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN05;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN06;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN07;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN08;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN09;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN10;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN11;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN12;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN13;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN14;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN15;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN16;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN17;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN18;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN19;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN20;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN21;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN22;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN23;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN24;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN25;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN26;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN27;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN28;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN29;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN30;
  public final static int D3DRENDERSTATE_STIPPLEPATTERN31;
  public final static int D3DRENDERSTATE_SUBPIXEL;
  public final static int D3DRENDERSTATE_SUBPIXELX;
  public final static int D3DRENDERSTATE_TEXTUREADDRESS;
  public final static int D3DRENDERSTATE_TEXTUREHANDLE;
  public final static int D3DRENDERSTATE_TEXTUREMAG;
  public final static int D3DRENDERSTATE_TEXTUREMAPBLEND;
  public final static int D3DRENDERSTATE_TEXTUREMIN;
  public final static int D3DRENDERSTATE_TEXTUREPERSPECTIVE;
  public final static int D3DRENDERSTATE_WRAPU;
  public final static int D3DRENDERSTATE_WRAPV;
  public final static int D3DRENDERSTATE_ZENABLE;
  public final static int D3DRENDERSTATE_ZFUNC;
  public final static int D3DRENDERSTATE_ZVISIBLE;
  public final static int D3DRENDERSTATE_ZWRITEENABLE;
  public final static int D3DRMANIMATION_CLOSED;
  public final static int D3DRMANIMATION_LINEARPOSITION;
  public final static int D3DRMANIMATION_OPEN;
  public final static int D3DRMANIMATION_POSITION;
  public final static int D3DRMANIMATION_SCALEANDROTATION;
  public final static int D3DRMANIMATION_SPLINEPOSITION;
  public final static int D3DRMCOLOR_FROMFACE;
  public final static int D3DRMCOLOR_FROMVERTEX;
  public final static int D3DRMCOMBINE_AFTER;
  public final static int D3DRMCOMBINE_BEFORE;
  public final static int D3DRMCOMBINE_REPLACE;
  public final static int D3DRMCONSTRAIN_X;
  public final static int D3DRMCONSTRAIN_Y;
  public final static int D3DRMCONSTRAIN_Z;
  public final static int D3DRMFILL_MASK;
  public final static int D3DRMFILL_MAX;
  public final static int D3DRMFILL_POINTS;
  public final static int D3DRMFILL_SOLID;
  public final static int D3DRMFILL_WIREFRAME;
  public final static int D3DRMFOG_EXPONENTIAL;
  public final static int D3DRMFOG_EXPONENTIALSQUARED;
  public final static int D3DRMFOG_LINEAR;
  public final static int D3DRMLIGHT_AMBIENT;
  public final static int D3DRMLIGHT_DIRECTIONAL;
  public final static int D3DRMLIGHT_MASK;
  public final static int D3DRMLIGHT_MAX;
  public final static int D3DRMLIGHT_OFF;
  public final static int D3DRMLIGHT_ON;
  public final static int D3DRMLIGHT_PARALLELPOINT;
  public final static int D3DRMLIGHT_POINT;
  public final static int D3DRMLIGHT_SPOT;
  public final static int D3DRMLOAD_BYGUID;
  public final static int D3DRMLOAD_BYNAME;
  public final static int D3DRMLOAD_BYPOSITION;
  public final static int D3DRMLOAD_FIRST;
  public final static int D3DRMLOAD_FROMFILE;
  public final static int D3DRMLOAD_FROMMEMORY;
  public final static int D3DRMLOAD_FROMRESOURCE;
  public final static int D3DRMLOAD_FROMSTREAM;
  public final static int D3DRMLOAD_INSTANCEBYCOPYING;
  public final static int D3DRMLOAD_INSTANCEBYREFERENCE;
  public final static int D3DRMMATERIAL_FROMFRAME;
  public final static int D3DRMMATERIAL_FROMMESH;
  public final static int D3DRMMATERIAL_FROMPARENT;
  public final static int D3DRMPALETTE_FREE;
  public final static int D3DRMPALETTE_READONLY;
  public final static int D3DRMPALETTE_RESERVED;
  public final static int D3DRMPROJECT_ORTHOGRAPHIC;
  public final static int D3DRMPROJECT_PERSPECTIVE;
  public final static int D3DRMRENDER_FLAT;
  public final static int D3DRMRENDER_GOURAUD;
  public final static int D3DRMRENDER_PHONG;
  public final static int D3DRMRENDER_UNLITFLAT;
  public final static int D3DRMRENDER_WIREFRAME;
  public final static int D3DRMSHADE_FLAT;
  public final static int D3DRMSHADE_GOURAUD;
  public final static int D3DRMSHADE_MASK;
  public final static int D3DRMSHADE_MAX;
  public final static int D3DRMSHADE_PHONG;
  public final static int D3DRMSORT_BACKTOFRONT;
  public final static int D3DRMSORT_FROMPARENT;
  public final static int D3DRMSORT_FRONTTOBACK;
  public final static int D3DRMSORT_NONE;
  public final static int D3DRMTEXTURE_LINEAR;
  public final static int D3DRMTEXTURE_LINEARMIPLINEAR;
  public final static int D3DRMTEXTURE_LINEARMIPNEAREST;
  public final static int D3DRMTEXTURE_MIPLINEAR;
  public final static int D3DRMTEXTURE_MIPNEAREST;
  public final static int D3DRMTEXTURE_NEAREST;
  public final static int D3DRMWIREFRAME_CULL;
  public final static int D3DRMWIREFRAME_HIDDENLINE;
  public final static int D3DRMWRAP_CHROME;
  public final static int D3DRMWRAP_CYLINDER;
  public final static int D3DRMWRAP_FLAT;
  public final static int D3DRMWRAP_SPHERE;
  public final static int D3DRMXOF_BINARY;
  public final static int D3DRMXOF_COMPRESSED;
  public final static int D3DRMXOF_TEXT;
  public final static int D3DRMXOFSAVE_ALL;
  public final static int D3DRMXOFSAVE_MATERIALS;
  public final static int D3DRMXOFSAVE_NORMALS;
  public final static int D3DRMXOFSAVE_TEMPLATES;
  public final static int D3DRMXOFSAVE_TEXTURECOORDINATES;
  public final static int D3DRMXOFSAVE_TEXTURENAMES;
  public final static int D3DRMZBUFFER_DISABLE;
  public final static int D3DRMZBUFFER_ENABLE;
  public final static int D3DRMZBUFFER_FROMPARENT;
  public final static int D3DSETSTATUS_ALL;
  public final static int D3DSETSTATUS_EXTENTS;
  public final static int D3DSETSTATUS_STATUS;
  public final static int D3DSHADE_FLAT;
  public final static int D3DSHADE_GOURAUD;
  public final static int D3DSHADE_PHONG;
  public final static int D3DSTATE_OVERRIDE_BIAS;
  public final static int D3DSTATUS_CLIPINTERSECTIONALL;
  public final static int D3DSTATUS_CLIPINTERSECTIONBACK;
  public final static int D3DSTATUS_CLIPINTERSECTIONBOTTOM;
  public final static int D3DSTATUS_CLIPINTERSECTIONFRONT;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN0;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN1;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN2;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN3;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN4;
  public final static int D3DSTATUS_CLIPINTERSECTIONGEN5;
  public final static int D3DSTATUS_CLIPINTERSECTIONLEFT;
  public final static int D3DSTATUS_CLIPINTERSECTIONRIGHT;
  public final static int D3DSTATUS_CLIPINTERSECTIONTOP;
  public final static int D3DSTATUS_CLIPUNIONALL;
  public final static int D3DSTATUS_CLIPUNIONBACK;
  public final static int D3DSTATUS_CLIPUNIONBOTTOM;
  public final static int D3DSTATUS_CLIPUNIONFRONT;
  public final static int D3DSTATUS_CLIPUNIONGEN0;
  public final static int D3DSTATUS_CLIPUNIONGEN1;
  public final static int D3DSTATUS_CLIPUNIONGEN2;
  public final static int D3DSTATUS_CLIPUNIONGEN3;
  public final static int D3DSTATUS_CLIPUNIONGEN4;
  public final static int D3DSTATUS_CLIPUNIONGEN5;
  public final static int D3DSTATUS_CLIPUNIONLEFT;
  public final static int D3DSTATUS_CLIPUNIONRIGHT;
  public final static int D3DSTATUS_CLIPUNIONTOP;
  public final static int D3DSTATUS_DEFAULT;
  public final static int D3DSTATUS_ZNOTVISIBLE;
  public final static int D3DTADDRESS_CLAMP;
  public final static int D3DTADDRESS_MIRROR;
  public final static int D3DTADDRESS_WRAP;
  public final static int D3DTBLEND_COPY;
  public final static int D3DTBLEND_DECAL;
  public final static int D3DTBLEND_DECALALPHA;
  public final static int D3DTBLEND_DECALMASK;
  public final static int D3DTBLEND_MODULATE;
  public final static int D3DTBLEND_MODULATEALPHA;
  public final static int D3DTBLEND_MODULATEMASK;
  public final static int D3DTRANSFORM_CLIPPED;
  public final static int D3DTRANSFORM_UNCLIPPED;
  public final static int D3DTRANSFORMSTATE_PROJECTION;
  public final static int D3DTRANSFORMSTATE_VIEW;
  public final static int D3DTRANSFORMSTATE_WORLD;
  public final static short D3DTRIFLAG_EDGEENABLE1;
  public final static short D3DTRIFLAG_EDGEENABLE2;
  public final static short D3DTRIFLAG_EDGEENABLE3;
  public final static short D3DTRIFLAG_EDGEENABLETRIANGLE;
  public final static short D3DTRIFLAG_EVEN;
  public final static short D3DTRIFLAG_ODD;
  public final static short D3DTRIFLAG_START;
  public final static int DD_OK;
  public final static int DDBD_1;
  public final static int DDBD_16;
  public final static int DDBD_2;
  public final static int DDBD_24;
  public final static int DDBD_32;
  public final static int DDBD_4;
  public final static int DDBD_8;
  public final static int DDBLT_ALPHADEST;
  public final static int DDBLT_ALPHADESTCONSTOVERRIDE;
  public final static int DDBLT_ALPHADESTNEG;
  public final static int DDBLT_ALPHADESTSURFACEOVERRIDE;
  public final static int DDBLT_ALPHAEDGEBLEND;
  public final static int DDBLT_ALPHASRC;
  public final static int DDBLT_ALPHASRCCONSTOVERRIDE;
  public final static int DDBLT_ALPHASRCNEG;
  public final static int DDBLT_ALPHASRCSURFACEOVERRIDE;
  public final static int DDBLT_ASYNC;
  public final static int DDBLT_COLORFILL;
  public final static int DDBLT_DDFX;
  public final static int DDBLT_DDROPS;
  public final static int DDBLT_DEPTHFILL;
  public final static int DDBLT_KEYDEST;
  public final static int DDBLT_KEYDESTOVERRIDE;
  public final static int DDBLT_KEYSRC;
  public final static int DDBLT_KEYSRCOVERRIDE;
  public final static int DDBLT_ROP;
  public final static int DDBLT_ROTATIONANGLE;
  public final static int DDBLT_WAIT;
  public final static int DDBLT_ZBUFFER;
  public final static int DDBLT_ZBUFFERDESTCONSTOVERRIDE;
  public final static int DDBLT_ZBUFFERDESTOVERRIDE;
  public final static int DDBLT_ZBUFFERSRCCONSTOVERRIDE;
  public final static int DDBLT_ZBUFFERSRCOVERRIDE;
  public final static int DDBLTFAST_DESTCOLORKEY;
  public final static int DDBLTFAST_NOCOLORKEY;
  public final static int DDBLTFAST_SRCCOLORKEY;
  public final static int DDBLTFAST_WAIT;
  public final static int DDBLTFX_ARITHSTRETCHY;
  public final static int DDBLTFX_MIRRORLEFTRIGHT;
  public final static int DDBLTFX_MIRRORUPDOWN;
  public final static int DDBLTFX_NOTEARING;
  public final static int DDBLTFX_ROTATE180;
  public final static int DDBLTFX_ROTATE270;
  public final static int DDBLTFX_ROTATE90;
  public final static int DDBLTFX_ZBUFFERBASEDEST;
  public final static int DDBLTFX_ZBUFFERRANGE;
  public final static int DDCAPS_3D;
  public final static int DDCAPS_ALIGNBOUNDARYDEST;
  public final static int DDCAPS_ALIGNBOUNDARYSRC;
  public final static int DDCAPS_ALIGNSIZEDEST;
  public final static int DDCAPS_ALIGNSIZESRC;
  public final static int DDCAPS_ALIGNSTRIDE;
  public final static int DDCAPS_ALPHA;
  public final static int DDCAPS_BANKSWITCHED;
  public final static int DDCAPS_BLT;
  public final static int DDCAPS_BLTCOLORFILL;
  public final static int DDCAPS_BLTDEPTHFILL;
  public final static int DDCAPS_BLTFOURCC;
  public final static int DDCAPS_BLTQUEUE;
  public final static int DDCAPS_BLTSTRETCH;
  public final static int DDCAPS_CANBLTSYSMEM;
  public final static int DDCAPS_CANCLIP;
  public final static int DDCAPS_CANCLIPSTRETCHED;
  public final static int DDCAPS_COLORKEY;
  public final static int DDCAPS_COLORKEYHWASSIST;
  public final static int DDCAPS_GDI;
  public final static int DDCAPS_NOHARDWARE;
  public final static int DDCAPS_OVERLAY;
  public final static int DDCAPS_OVERLAYCANTCLIP;
  public final static int DDCAPS_OVERLAYFOURCC;
  public final static int DDCAPS_OVERLAYSTRETCH;
  public final static int DDCAPS_PALETTE;
  public final static int DDCAPS_PALETTEVSYNC;
  public final static int DDCAPS_READSCANLINE;
  public final static int DDCAPS_STEREOVIEW;
  public final static int DDCAPS_VBI;
  public final static int DDCAPS_ZBLTS;
  public final static int DDCAPS_ZOVERLAYS;
  public final static int DDCAPS2_CERTIFIED;
  public final static int DDCAPS2_NO2DDURING3DSCENE;
  public final static int DDCKEY_COLORSPACE;
  public final static int DDCKEY_DESTBLT;
  public final static int DDCKEY_DESTOVERLAY;
  public final static int DDCKEY_SRCBLT;
  public final static int DDCKEY_SRCOVERLAY;
  public final static int DDCKEYCAPS_DESTBLT;
  public final static int DDCKEYCAPS_DESTBLTCLRSPACE;
  public final static int DDCKEYCAPS_DESTBLTCLRSPACEYUV;
  public final static int DDCKEYCAPS_DESTBLTYUV;
  public final static int DDCKEYCAPS_DESTOVERLAY;
  public final static int DDCKEYCAPS_DESTOVERLAYCLRSPACE;
  public final static int DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV;
  public final static int DDCKEYCAPS_DESTOVERLAYONEACTIVE;
  public final static int DDCKEYCAPS_DESTOVERLAYYUV;
  public final static int DDCKEYCAPS_NOCOSTOVERLAY;
  public final static int DDCKEYCAPS_SRCBLT;
  public final static int DDCKEYCAPS_SRCBLTCLRSPACE;
  public final static int DDCKEYCAPS_SRCBLTCLRSPACEYUV;
  public final static int DDCKEYCAPS_SRCBLTYUV;
  public final static int DDCKEYCAPS_SRCOVERLAY;
  public final static int DDCKEYCAPS_SRCOVERLAYCLRSPACE;
  public final static int DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV;
  public final static int DDCKEYCAPS_SRCOVERLAYONEACTIVE;
  public final static int DDCKEYCAPS_SRCOVERLAYYUV;
  public final static int DDCOOPERATIVE_CLIPTOCOMPONENT;
  public final static int DDCOOPERATIVE_OFFSETTOCOMPONENT;
  public final static int DDCREATE_EMULATIONONLY;
  public final static int DDCREATE_HARDWAREONLY;
  public final static int DDEDM_REFRESHRATES;
  public final static int DDENUMOVERLAYZ_BACKTOFRONT;
  public final static int DDENUMOVERLAYZ_FRONTTOBACK;
  public final static int DDENUMSURFACES_ALL;
  public final static int DDENUMSURFACES_CANBECREATED;
  public final static int DDENUMSURFACES_DOESEXIST;
  public final static int DDENUMSURFACES_MATCH;
  public final static int DDENUMSURFACES_NOMATCH;
  public final static int DDERR_SURFACELOST;
  public final static int DDERR_WASSTILLDRAWING;
  public final static int DDFLIP_WAIT;
  public final static int DDFXALPHACAPS_BLTALPHAEDGEBLEND;
  public final static int DDFXALPHACAPS_BLTALPHAPIXELS;
  public final static int DDFXALPHACAPS_BLTALPHAPIXELSNEG;
  public final static int DDFXALPHACAPS_BLTALPHASURFACES;
  public final static int DDFXALPHACAPS_BLTALPHASURFACESNEG;
  public final static int DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND;
  public final static int DDFXALPHACAPS_OVERLAYALPHAPIXELS;
  public final static int DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG;
  public final static int DDFXALPHACAPS_OVERLAYALPHASURFACES;
  public final static int DDFXALPHACAPS_OVERLAYALPHASURFACESNEG;
  public final static int DDFXCAPS_BLTARITHSTRETCHY;
  public final static int DDFXCAPS_BLTARITHSTRETCHYN;
  public final static int DDFXCAPS_BLTMIRRORLEFTRIGHT;
  public final static int DDFXCAPS_BLTMIRRORUPDOWN;
  public final static int DDFXCAPS_BLTROTATION;
  public final static int DDFXCAPS_BLTROTATION90;
  public final static int DDFXCAPS_BLTSHRINKX;
  public final static int DDFXCAPS_BLTSHRINKXN;
  public final static int DDFXCAPS_BLTSHRINKY;
  public final static int DDFXCAPS_BLTSHRINKYN;
  public final static int DDFXCAPS_BLTSTRETCHX;
  public final static int DDFXCAPS_BLTSTRETCHXN;
  public final static int DDFXCAPS_BLTSTRETCHY;
  public final static int DDFXCAPS_BLTSTRETCHYN;
  public final static int DDFXCAPS_OVERLAYARITHSTRETCHY;
  public final static int DDFXCAPS_OVERLAYARITHSTRETCHYN;
  public final static int DDFXCAPS_OVERLAYMIRRORLEFTRIGHT;
  public final static int DDFXCAPS_OVERLAYMIRRORUPDOWN;
  public final static int DDFXCAPS_OVERLAYSHRINKX;
  public final static int DDFXCAPS_OVERLAYSHRINKXN;
  public final static int DDFXCAPS_OVERLAYSHRINKY;
  public final static int DDFXCAPS_OVERLAYSHRINKYN;
  public final static int DDFXCAPS_OVERLAYSTRETCHX;
  public final static int DDFXCAPS_OVERLAYSTRETCHXN;
  public final static int DDFXCAPS_OVERLAYSTRETCHY;
  public final static int DDFXCAPS_OVERLAYSTRETCHYN;
  public final static int DDGBS_CANBLT;
  public final static int DDGBS_ISBLTDONE;
  public final static int DDGFS_CANFLIP;
  public final static int DDGFS_ISFLIPDONE;
  public final static int DDLOCK_EVENT;
  public final static int DDLOCK_READONLY;
  public final static int DDLOCK_SURFACEMEMORYPTR;
  public final static int DDLOCK_WAIT;
  public final static int DDLOCK_WRITEONLY;
  public final static int DDOVER_ADDDIRTYRECT;
  public final static int DDOVER_ALPHADEST;
  public final static int DDOVER_ALPHADESTCONSTOVERRIDE;
  public final static int DDOVER_ALPHADESTNEG;
  public final static int DDOVER_ALPHADESTSURFACEOVERRIDE;
  public final static int DDOVER_ALPHAEDGEBLEND;
  public final static int DDOVER_ALPHASRC;
  public final static int DDOVER_ALPHASRCCONSTOVERRIDE;
  public final static int DDOVER_ALPHASRCNEG;
  public final static int DDOVER_ALPHASRCSURFACEOVERRIDE;
  public final static int DDOVER_DDFX;
  public final static int DDOVER_HIDE;
  public final static int DDOVER_KEYDEST;
  public final static int DDOVER_KEYDESTOVERRIDE;
  public final static int DDOVER_KEYSRC;
  public final static int DDOVER_KEYSRCOVERRIDE;
  public final static int DDOVER_REFRESHALL;
  public final static int DDOVER_REFRESHDIRTYRECTS;
  public final static int DDOVER_SHOW;
  public final static int DDOVERFX_ARITHSTRETCHY;
  public final static int DDOVERFX_MIRRORLEFTRIGHT;
  public final static int DDOVERFX_MIRRORUPDOWN;
  public final static int DDOVERZ_INSERTINBACKOF;
  public final static int DDOVERZ_INSERTINFRONTOF;
  public final static int DDOVERZ_MOVEBACKWARD;
  public final static int DDOVERZ_MOVEFORWARD;
  public final static int DDOVERZ_SENDTOBACK;
  public final static int DDOVERZ_SENDTOFRONT;
  public final static int DDPCAPS_1BIT;
  public final static int DDPCAPS_2BIT;
  public final static int DDPCAPS_4BIT;
  public final static int DDPCAPS_8BIT;
  public final static int DDPCAPS_8BITENTRIES;
  public final static int DDPCAPS_ALLOW256;
  public final static int DDPCAPS_INITIALIZE;
  public final static int DDPCAPS_PRIMARYSURFACE;
  public final static int DDPCAPS_PRIMARYSURFACELEFT;
  public final static int DDPCAPS_VSYNC;
  public final static int DDPF_ALPHA;
  public final static int DDPF_ALPHAPIXELS;
  public final static int DDPF_COMPRESSED;
  public final static int DDPF_FOURCC;
  public final static int DDPF_PALETTEINDEXED1;
  public final static int DDPF_PALETTEINDEXED2;
  public final static int DDPF_PALETTEINDEXED4;
  public final static int DDPF_PALETTEINDEXED8;
  public final static int DDPF_PALETTEINDEXEDTO8;
  public final static int DDPF_RGB;
  public final static int DDPF_RGBTOYUV;
  public final static int DDPF_YUV;
  public final static int DDPF_ZBUFFER;
  public final static int DDSCAPS_3D;
  public final static int DDSCAPS_3DDEVICE;
  public final static int DDSCAPS_ALLOCONLOAD;
  public final static int DDSCAPS_ALPHA;
  public final static int DDSCAPS_BACKBUFFER;
  public final static int DDSCAPS_COMPLEX;
  public final static int DDSCAPS_FLIP;
  public final static int DDSCAPS_FRONTBUFFER;
  public final static int DDSCAPS_HWCODEC;
  public final static int DDSCAPS_LIVEVIDEO;
  public final static int DDSCAPS_MIPMAP;
  public final static int DDSCAPS_MODEX;
  public final static int DDSCAPS_OFFSCREENPLAIN;
  public final static int DDSCAPS_OVERLAY;
  public final static int DDSCAPS_OWNDC;
  public final static int DDSCAPS_PALETTE;
  public final static int DDSCAPS_PRIMARYSURFACE;
  public final static int DDSCAPS_PRIMARYSURFACELEFT;
  public final static int DDSCAPS_SYSTEMMEMORY;
  public final static int DDSCAPS_TEXTURE;
  public final static int DDSCAPS_VIDEOMEMORY;
  public final static int DDSCAPS_VISIBLE;
  public final static int DDSCAPS_WRITEONLY;
  public final static int DDSCAPS_ZBUFFER;
  public final static int DDSCL_ALLOWMODEX;
  public final static int DDSCL_ALLOWREBOOT;
  public final static int DDSCL_EXCLUSIVE;
  public final static int DDSCL_FULLSCREEN;
  public final static int DDSCL_NORMAL;
  public final static int DDSCL_NOWINDOWCHANGES;
  public final static int DDSD_ALL;
  public final static int DDSD_ALPHABITDEPTH;
  public final static int DDSD_BACKBUFFERCOUNT;
  public final static int DDSD_CAPS;
  public final static int DDSD_CKDESTBLT;
  public final static int DDSD_CKDESTOVERLAY;
  public final static int DDSD_CKSRCBLT;
  public final static int DDSD_CKSRCOVERLAY;
  public final static int DDSD_HEIGHT;
  public final static int DDSD_MIPMAPCOUNT;
  public final static int DDSD_PITCH;
  public final static int DDSD_PIXELFORMAT;
  public final static int DDSD_REFRESHRATE;
  public final static int DDSD_WIDTH;
  public final static int DDSD_ZBUFFERBITDEPTH;
  public final static int DDSVCAPS_ENIGMA;
  public final static int DDSVCAPS_FLICKER;
  public final static int DDSVCAPS_REDBLUE;
  public final static int DDSVCAPS_SPLIT;
  public final static int DDWAITVB_BLOCKBEGIN;
  public final static int DDWAITVB_BLOCKBEGINEVENT;
  public final static int DDWAITVB_BLOCKEND;
  public final static int DPCAPS_GROUPOPTIMIZED;
  public final static int DPCAPS_GUARANTEEDOPTIMIZED;
  public final static int DPCAPS_GUARANTEEDSUPPORTED;
  public final static int DPCAPS_ISHOST;
  public final static int DPCAPS_KEEPALIVEOPTIMIZED;
  public final static int DPCPA_DTRFLOW;
  public final static int DPCPA_NOFLOW;
  public final static int DPCPA_RTSDTRFLOW;
  public final static int DPCPA_RTSFLOW;
  public final static int DPCPA_XONXOFFFLOW;
  public final static int DPENUMPLAYERS_ALL;
  public final static int DPENUMPLAYERS_GROUP;
  public final static int DPENUMPLAYERS_LOCAL;
  public final static int DPENUMPLAYERS_REMOTE;
  public final static int DPENUMPLAYERS_SESSION;
  public final static int DPENUMSESSIONS_ALL;
  public final static int DPENUMSESSIONS_AVAILABLE;
  public final static int DPESC_TIMEDOUT;
  public final static int DPGET_LOCAL;
  public final static int DPGET_REMOTE;
  public final static int DPGETCAPS_GUARANTEED;
  public final static int DPLAD_SYSTEM;
  public final static int DPLCONNECTION_CREATESESSION;
  public final static int DPLCONNECTION_JOINSESSION;
  public final static int DPLSYS_APPTERMINATED;
  public final static int DPLSYS_CONNECTIONSETTINGSREAD;
  public final static int DPLSYS_DPLAYCONNECTFAILED;
  public final static int DPLSYS_DPLAYCONNECTSUCCEEDED;
  public final static int DPOPEN_CREATE;
  public final static int DPOPEN_JOIN;
  public final static int DPPLAYERTYPE_GROUP;
  public final static int DPPLAYERTYPE_PLAYER;
  public final static int DPRECEIVE_ALL;
  public final static int DPRECEIVE_FROMPLAYER;
  public final static int DPRECEIVE_PEEK;
  public final static int DPRECEIVE_TOPLAYER;
  public final static int DPSEND_CLOSESTREAM;
  public final static int DPSEND_GUARANTEED;
  public final static int DPSEND_HIGHPRIORITY;
  public final static int DPSEND_OPENSTREAM;
  public final static int DPSESSION_JOINDISABLED;
  public final static int DPSESSION_KEEPALIVE;
  public final static int DPSESSION_MIGRATEHOST;
  public final static int DPSESSION_NEWPLAYERSDISABLED;
  public final static int DPSESSION_NODATAMESSAGES;
  public final static int DPSESSION_NOMESSAGEID;
  public final static int DPSET_GUARANTEED;
  public final static int DPSET_LOCAL;
  public final static int DPSET_REMOTE;
  public final static int DPSYS_ADDPLAYERTOGROUP;
  public final static int DPSYS_CREATEPLAYERORGROUP;
  public final static int DPSYS_DELETEPLAYERFROMGROUP;
  public final static int DPSYS_DESTROYPLAYERORGROUP;
  public final static int DPSYS_HOST;
  public final static int DPSYS_SESSIONLOST;
  public final static int DPSYS_SETPLAYERORGROUPDATA;
  public final static int DPSYS_SETPLAYERORGROUPNAME;
  public final static float DS3D_DEFAULTDISTANCEFACTOR;
  public final static float DS3D_DEFAULTDOPPLERFACTOR;
  public final static int DS3D_DEFERRED;
  public final static int DS3D_IMMEDIATE;
  public final static int DS3DMODE_DISABLE;
  public final static int DS3DMODE_HEADRELATIVE;
  public final static int DS3DMODE_NORMAL;
  public final static int DSBCAPS_CTRL3D;
  public final static int DSBCAPS_CTRLALL;
  public final static int DSBCAPS_CTRLDEFAULT;
  public final static int DSBCAPS_CTRLFREQUENCY;
  public final static int DSBCAPS_CTRLPAN;
  public final static int DSBCAPS_CTRLVOLUME;
  public final static int DSBCAPS_GETCURRENTPOSITION2;
  public final static int DSBCAPS_GLOBALFOCUS;
  public final static int DSBCAPS_LOCHARDWARE;
  public final static int DSBCAPS_LOCSOFTWARE;
  public final static int DSBCAPS_PRIMARYBUFFER;
  public final static int DSBCAPS_STATIC;
  public final static int DSBCAPS_STICKYFOCUS;
  public final static int DSBLOCK_FROMWRITECURSOR;
  public final static int DSBPLAY_LOOPING;
  public final static int DSBSTATUS_BUFFERLOST;
  public final static int DSBSTATUS_LOOPING;
  public final static int DSBSTATUS_PLAYING;
  public final static int DSCAPS_CERTIFIED;
  public final static int DSCAPS_CONTINUOUSRATE;
  public final static int DSCAPS_EMULDRIVER;
  public final static int DSCAPS_PRIMARY16BIT;
  public final static int DSCAPS_PRIMARY8BIT;
  public final static int DSCAPS_PRIMARYMONO;
  public final static int DSCAPS_PRIMARYSTEREO;
  public final static int DSCAPS_SECONDARY16BIT;
  public final static int DSCAPS_SECONDARY8BIT;
  public final static int DSCAPS_SECONDARYMONO;
  public final static int DSCAPS_SECONDARYSTEREO;
  public final static int DSSCL_EXCLUSIVE;
  public final static int DSSCL_NORMAL;
  public final static int DSSCL_PRIORITY;
  public final static int DSSCL_WRITEPRIMARY;
  public final static int DSSPEAKER_HEADPHONE;
  public final static int DSSPEAKER_MONO;
  public final static int DSSPEAKER_QUAD;
  public final static int DSSPEAKER_STEREO;
  public final static int DSSPEAKER_SURROUND;
  public final static int JOY_BUTTON1;
  public final static int JOY_BUTTON10;
  public final static int JOY_BUTTON11;
  public final static int JOY_BUTTON12;
  public final static int JOY_BUTTON13;
  public final static int JOY_BUTTON14;
  public final static int JOY_BUTTON15;
  public final static int JOY_BUTTON16;
  public final static int JOY_BUTTON17;
  public final static int JOY_BUTTON18;
  public final static int JOY_BUTTON19;
  public final static int JOY_BUTTON2;
  public final static int JOY_BUTTON20;
  public final static int JOY_BUTTON21;
  public final static int JOY_BUTTON22;
  public final static int JOY_BUTTON23;
  public final static int JOY_BUTTON24;
  public final static int JOY_BUTTON25;
  public final static int JOY_BUTTON26;
  public final static int JOY_BUTTON27;
  public final static int JOY_BUTTON28;
  public final static int JOY_BUTTON29;
  public final static int JOY_BUTTON3;
  public final static int JOY_BUTTON30;
  public final static int JOY_BUTTON31;
  public final static int JOY_BUTTON32;
  public final static int JOY_BUTTON4;
  public final static int JOY_BUTTON5;
  public final static int JOY_BUTTON6;
  public final static int JOY_BUTTON7;
  public final static int JOY_BUTTON8;
  public final static int JOY_BUTTON9;
  public final static int JOY_CAL_READ3;
  public final static int JOY_CAL_READ4;
  public final static int JOY_CAL_READ5;
  public final static int JOY_CAL_READ6;
  public final static int JOY_CAL_READALWAYS;
  public final static int JOY_CAL_READRONLY;
  public final static int JOY_CAL_READUONLY;
  public final static int JOY_CAL_READVONLY;
  public final static int JOY_CAL_READXONLY;
  public final static int JOY_CAL_READXYONLY;
  public final static int JOY_CAL_READYONLY;
  public final static int JOY_CAL_READZONLY;
  public final static int JOY_POVBACKWARD;
  public final static int JOY_POVCENTERED;
  public final static int JOY_POVFORWARD;
  public final static int JOY_POVLEFT;
  public final static int JOY_POVRIGHT;
  public final static int JOY_RETURNALL;
  public final static int JOY_RETURNBUTTONS;
  public final static int JOY_RETURNCENTERED;
  public final static int JOY_RETURNPOV;
  public final static int JOY_RETURNPOVCTS;
  public final static int JOY_RETURNR;
  public final static int JOY_RETURNRAWDATA;
  public final static int JOY_RETURNU;
  public final static int JOY_RETURNV;
  public final static int JOY_RETURNX;
  public final static int JOY_RETURNY;
  public final static int JOY_RETURNZ;
  public final static int JOY_USEDEADZONE;
  public final static short JOYCAPS_HASPOV;
  public final static short JOYCAPS_HASR;
  public final static short JOYCAPS_HASU;
  public final static short JOYCAPS_HASV;
  public final static short JOYCAPS_HASZ;
  public final static short JOYCAPS_POV4DIR;
  public final static short JOYCAPS_POVCTS;
  public final static int JOYERR_BASE;
  public final static int JOYERR_NOCANDO;
  public final static int JOYERR_NOERROR;
  public final static int JOYERR_PARMS;
  public final static int JOYERR_UNPLUGGED;
  public final static int JOYSTICKID1;
  public final static int JOYSTICKID2;
}

The DirectXConstants interface defines all the constants used in DirectX for Java.

Fields

D3DBLEND_BOTHINVSRCALPHA
The destination blend selection is overridden when the source blend factor is (1-As, 1-As, 1-As, 1-As), and destination blend factor is (As, As, As, As).
D3DBLEND_BOTHSRCALPHA
The destination blend selection is overridden when the source blend factor is (As, As, As, As), and destination blend factor is (1-As, 1-As, 1-As, 1-As).
D3DBLEND_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DBLEND_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DBLEND_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DBLEND_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DBLEND_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As).
D3DBLEND_INVSRCCOLOR
Blend factor is (As, As, As, As, 1-As).
D3DBLEND_ONE
Blend factor is (1, 1, 1, 1).
D3DBLEND_SRCALPHA
Blend factor is (As, As, As, As).
D3DBLEND_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DBLEND_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DBLEND_ZERO
Blend factor is (0, 0, 0, 0).
D3DCLEAR_TARGET
Clear the rendering target to the background material (if set).
D3DCLEAR_ZBUFFER
Clear the z-buffer or set it to the current background depth field (if set).
D3DCLIP_BACK
Clipped by the back plane of the viewing frustum.
D3DCLIP_BOTTOM
Clipped by the bottom plane of the viewing frustum.
D3DCLIP_FRONT
Clipped by the front plane of the viewing frustum.
D3DCLIP_GEN0
Application-defined clipping plane.
D3DCLIP_GEN1
Application-defined clipping plane.
D3DCLIP_GEN2
Application-defined clipping plane.
D3DCLIP_GEN3
Application-defined clipping plane.
D3DCLIP_GEN4
Application-defined clipping plane.
D3DCLIP_GEN5
Application-defined clipping plane.
D3DCLIP_LEFT
Clipped by the left plane of the viewing frustum.
D3DCLIP_RIGHT
Clipped by the right plane of the viewing frustum.
D3DCLIP_TOP
Clipped by the top plane of the viewing frustum.
D3DCMP_ALWAYS
Always pass the test.
D3DCMP_EQUAL
Accept the new pixel if its value equals the value of the current pixel.
D3DCMP_GREATER
Accept the new pixel if its value is greater than the value of the current pixel.
D3DCMP_GREATEREQUAL
Accept the new pixel if its value is greater than or equal to the value of the current pixel.
D3DCMP_LESS
Accept the new pixel if its value is less than the value of the current pixel.
D3DCMP_LESSEQUAL
Accept the new pixel if its value is less than or equal to the value of the current pixel.
D3DCMP_NEVER
Always fail the test.
D3DCMP_NOTEQUAL
Accept the new pixel if its value does not equal the value of the current pixel.
D3DCOLOR_MONO
Use a monochromatic model (or ramp model). In this model, the blue component of a vertex color is used to define the brightness of a lit vertex.
D3DCOLOR_RGB
Use a full RGB model.
D3DCULL_CCW
Cull faces with counterclockwise vertices.
D3DCULL_CW
Cull faces with clockwise vertices.
D3DCULL_NONE
Do not cull faces.
D3DDD_BCLIPPING
The D3dDeviceDesc.clipping field is valid.
D3DDD_COLORMODEL
The D3dDeviceDesc.dcmColorModel field is valid.
D3DDD_DEVCAPS
The D3dDeviceDesc.devCaps field is valid.
D3DDD_DEVICERENDERBITDEPTH
The D3dDeviceDesc.deviceRenderBitDepth field is valid.
D3DDD_DEVICEZBUFFERBITDEPTH
The D3dDeviceDesc.deviceZBufferBitDepth field is valid.
D3DDD_LIGHTINGCAPS
The D3dDeviceDesc.dlcLightingCaps field is valid.
D3DDD_LINECAPS
Reserved.
D3DDD_MAXBUFFERSIZE
The D3dDeviceDesc.maxBufferSize field is valid.
D3DDD_MAXVERTEXCOUNT
The D3dDeviceDesc.maxVertexCount field is valid.
D3DDD_TRANSFORMCAPS
The D3dDeviceDesc.dtcTransformCaps field is valid.
D3DDD_TRICAPS
Reserved.
D3DDEB_BUFSIZE
The D3dExecuteBufferDesc.bufferSize field is valid.
D3DDEB_CAPS
The D3dExecuteBufferDesc.caps field is valid.
D3DDEB_LPDATA
The D3dExecuteBufferDesc.data field is valid.
D3DDEBCAPS_MEM
A logical OR of D3DDEBCAPS_SYSTEMMEMORY and D3DDEBCAPS_VIDEOMEMORY.
D3DDEBCAPS_SYSTEMMEMORY
The execute buffer data resides in system memory.
D3DDEBCAPS_VIDEOMEMORY
The execute buffer data resides in device memory.
D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_FLOATTLVERTEX
Device accepts floating point for post-transform vertex data.
D3DDEVCAPS_SORTDECREASINGZ
Device needs data sorted for decreasing depth.
D3DDEVCAPS_SORTEXACT
Device needs data sorted exactly.
D3DDEVCAPS_SORTINCREASINGZ
Device needs data sorted for increasing depth.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieves textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
D3DEXECUTE_CLIPPED
Clip any primitives in the buffer that are outside or partially outside the viewport.
D3DEXECUTE_UNCLIPPED
All primitives in the buffer are contained within the viewport.
D3DFDS_ALPHACMPCAPS
Match the D3dFindDeviceSearch.alphaCmpCaps field.
D3DFDS_COLORMODEL
Match the color model specified in the D3dFindDeviceSearch.dcmColorModel field.
D3DFDS_DSTBLENDCAPS
Match the D3dFindDeviceSearch.destBlendCaps field.
D3DFDS_GUID
Match the globally unique identifier (GUID).
D3DFDS_HARDWARE
Match the hardware or software search specification given in the D3dFindDeviceSearch.hardware field.
D3DFDS_LINES
Reserved.
D3DFDS_MISCCAPS
Match the D3dFindDeviceSearch.miscCaps field.
D3DFDS_RASTERCAPS
Match the D3dFindDeviceSearch.rasterCaps field.
D3DFDS_SHADECAPS
Match the D3dFindDeviceSearch.shadeCaps field.
D3DFDS_SRCBLENDCAPS
Match the D3dFindDeviceSearch.srcBlendCaps field.
D3DFDS_TEXTUREADDRESSCAPS
Match the D3dFindDeviceSearch.textureAddressCaps field.
D3DFDS_TEXTUREBLENDCAPS
Match the D3dFindDeviceSearch.textureBlendCaps field.
D3DFDS_TEXTURECAPS
Match the D3dFindDeviceSearch.textureCaps field.
D3DFDS_TEXTUREFILTERCAPS
Match the D3dFindDeviceSearch.textureFilterCaps field.
D3DFDS_TRIANGLES
Reserved.
D3DFDS_ZCMPCAPS
Match the D3dFindDeviceSearch.zCmpCaps field.
D3DFILL_POINT
Fill points.
D3DFILL_SOLID
Fill solid.
D3DFILL_WIREFRAME
Fill wire frames.
D3DFILTER_LINEAR
Weighted average of a 2-by-2 area of texels surrounding the desired pixel is used. This applies to both zooming in and zooming out. If either is supported, both zooming in and zooming out must be supported.
D3DFILTER_LINEARMIPLINEAR
Similar to D3DFILTER_MIPLINEAR, but interpolates between the two nearest mipmaps.
D3DFILTER_LINEARMIPNEAREST
Similar to D3DFILTER_MIPNEAREST, but interpolates between the two nearest mipmaps.
D3DFILTER_MIPLINEAR
Similar to D3DFILTER_LINEAR, but uses the appropriate mipmap for texel selection.
D3DFILTER_MIPNEAREST
Similar to D3DFILTER_NEAREST, but uses the appropriate mipmap for texel selection.
D3DFILTER_NEAREST
Texel with coordinates nearest to the desired pixel value is used. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, both must be supported.
D3DFOG_EXP
The fog effect intensifies exponentially, according to the following formula:
D3DFOG_EXP2
The fog effect intensifies exponentially with the square of the distance.
D3DFOG_LINEAR
The fog effect intensifies linearly between the start and end points.
D3DFOG_NONE
No fog effect.
D3DLIGHT_DIRECTIONAL
Light is a directional source.
D3DLIGHT_GLSPOT
Light is a GL-style spotlight.
D3DLIGHT_PARALLELPOINT
Light is a parallel point source.
D3DLIGHT_POINT
Light is a point source.
D3DLIGHT_SPOT
Light is a spotlight source.
D3DLIGHTSTATE_AMBIENT
Set the color and intensity of the current ambient light. If an application specifies this value, it should not specify a light as a parameter. The default value is 0.
D3DLIGHTSTATE_COLORMODEL
One value of D3DCOLOR_ type. The default value is D3DCOLOR_RGB.
D3DLIGHTSTATE_FOGDENSITY
Define the density setting for fog. The default value is 1.0.
D3DLIGHTSTATE_FOGEND
Define the ending value for fog. The default value is 100.0.
D3DLIGHTSTATE_FOGMODE
One value of D3DFOG_ type. The default value is D3DFOG_NONE .
D3DLIGHTSTATE_FOGSTART
Define the starting value for fog. The default value is 1.0.
D3DLIGHTSTATE_MATERIAL
Define the material that is lit and used to compute the final color and intensity values during rasterization. The default value is null.
D3DOP_BRANCHFORWARD
Enable a branching mechanism within the execute buffer.
D3DOP_EXIT
Signal that the end of the list has been reached.
D3DOP_LINE
Send a line to the renderer.
D3DOP_MATRIXLOAD
Trigger a data transfer in the rendering engine.
D3DOP_MATRIXMULTIPLY
Trigger a data transfer in the rendering engine.
D3DOP_POINT
Send a point to the renderer.
D3DOP_PROCESSVERTICES
Set both lighting and transformations for vertices.
D3DOP_SETSTATUS
Reset the status of the execute buffer.
D3DOP_SPAN
Span a list of points with the same y-value.
D3DOP_STATELIGHT
Set the value of internal state variables in the rendering engine for the lighting module. Operand data is a variable token and the new value. The token identifies the internal state variable, and the new value is the value to which that variable should be set.
D3DOP_STATERENDER
Set the value of internal state variables in the rendering engine for the rendering module. Operand data is a variable token and the new value. The token identifies the internal state variable, and the new value is the value to which that variable should be set.
D3DOP_STATETRANSFORM
Set the value of internal state variables in the rendering engine for the transformation module. Operand data is a variable token and the new value. The token identifies the internal state variable, and the new value is the value to which that variable should be set.
D3DOP_TEXTURELOAD
Trigger a data transfer in the rendering engine.
D3DOP_TRIANGLE
Send a triangle to the renderer.
D3DPAL_FREE
The renderer may use this entry freely.
D3DPAL_READONLY
The renderer may not set this entry.
D3DPAL_RESERVED
The renderer may not use this entry.
D3DPBLENDCAPS_BOTHINVSRCALPHA
The destination blend selection is overridden when the source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As).
D3DPBLENDCAPS_BOTHSRCALPHA
The destination blend selection is overridden when the source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As).
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As, 1-As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
D3DPCMPCAPS_ALWAYS
Always pass the z-test.
D3DPCMPCAPS_EQUAL
Pass the z-test if the new z-value equals the current z-value.
D3DPCMPCAPS_GREATER
Pass the z-test if the new z-value is greater than the current z-value.
D3DPCMPCAPS_GREATEREQUAL
Pass the z-test if the new z-value is greater than or equal to the current z-value.
D3DPCMPCAPS_LESS
Pass the z-test if the new z-value is less than the current z-value.
D3DPCMPCAPS_LESSEQUAL
Pass the z-test if the new z-value is less than or equal to the current z-value.
D3DPCMPCAPS_NEVER
Always fail the z-test.
D3DPCMPCAPS_NOTEQUAL
Pass the z-test if the new z-value does not equal the current z-value.
D3DPMISCCAPS_CONFORMANT
The device conforms to the OpenGL standard.
D3DPMISCCAPS_CULLCCW
The driver supports counterclockwise culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CCW value.
D3DPMISCCAPS_CULLCW
The driver supports clockwise triangle culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CW value.
D3DPMISCCAPS_CULLNONE
The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE value.
D3DPMISCCAPS_LINEPATTERNREP
Reserved.
D3DPMISCCAPS_MASKPLANES
The device can perform a bitmask of color planes.
D3DPMISCCAPS_MASKZ
The device can enable and disable modification of the z-buffer on pixel operations.
D3DPRASTERCAPS_DITHER
The device can dither to improve color resolution.
D3DPRASTERCAPS_FOGTABLE
The device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
The device calculates the fog value during the lighting operation and places the value into the alpha component of the D3DCOLOR_ value given for the specular color in the D3dLightData.out field. It then interpolates the fog value during rasterization.
D3DPRASTERCAPS_PAT
The driver can perform patterned drawing (lines or fills with D3DRENDERSTATE_LINEPATTERN or one of the D3DRENDERSTATE_STIPPLEPATTERN render states) for the primitive being queried.
D3DPRASTERCAPS_ROP2
The device can support raster operations other than R2_COPYPEN.
D3DPRASTERCAPS_STIPPLE
The device can stipple polygons to simulate translucency.
D3DPRASTERCAPS_SUBPIXEL
The device performs subpixel placement of color, texture, and z data, rather than working with the nearest integer pixel coordinate. This helps avoid bleed-through due to z-imprecision, and jitter of color and texture values for pixels. Note that there is no corresponding state that can be enabled and disabled. The device either performs subpixel placement or it does not, and this bit is present only so that the Microsoft® Direct3D™ client will be better able to determine what the rendering quality will be.
D3DPRASTERCAPS_SUBPIXELX
The device is subpixel accurate along the x-axis only and is clamped to an integer y-axis scan line. For information about subpixel accuracy, see D3DPRASTERCAPS_SUBPIXEL .
D3DPRASTERCAPS_XOR
The device can support XOR operations.
D3DPRASTERCAPS_ZTEST
The device can perform z-test operations. This effectively renders a primitive and indicates whether any z-pixels would have been rendered.
D3DPROCESSVERTICES_COPY
Vertices should be copied to the driver, because they have always been transformed and lit. If all the vertices in the execute buffer can be copied, the driver does not need to do the work of processing the vertices; the result is an improvement in performance.
D3DPROCESSVERTICES_NOCOLOR
Vertices should not be colored.
D3DPROCESSVERTICES_OPMASK
Specifies a bitmask of the other flags in the flags member, exclusive of D3DPROCESSVERTICES_NOCOLOR and D3DPROCESSVERTICES_UPDATEEXTENTS.
D3DPROCESSVERTICES_TRANSFORM
Vertices should be transformed.
D3DPROCESSVERTICES_TRANSFORMLIGHT
Vertices should be transformed and lit.
D3DPROCESSVERTICES_UPDATEEXTENTS
Extents of all transformed vertices should be updated. This information is returned in the D3dStatus.x1, D3dStatus.y1, D3dStatus.x2, and D3dStatus.y2 fields.
D3DPSHADECAPS_ALPHAFLATBLEND
Device can support an alpha component for flat blended transparency (the D3DSHADE_FLAT state).
D3DPSHADECAPS_ALPHAFLATSTIPPLED
Device can support an alpha component for flat stippled transparency (the D3DSHADE_FLAT state). In these modes, the alpha color component for a primitive is provided as part of the color for the first vertex of the primitive.
D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud blended transparency (the D3DSHADE_GOURAUD state).
D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED
Device can support an alpha component for Gouraud stippled transparency (the D3DSHADE_GOURAUD state). In these modes, the alpha color component for a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_ALPHAPHONGBLEND
Device can support an alpha component for Phong blended transparency (the D3DSHADE_PHONG state).
D3DPSHADECAPS_ALPHAPHONGSTIPPLED
Device can support an alpha component for Phong stippled transparency (the D3DSHADE_PHONG state). In these modes, vertex parameters are reevaluated on a per-pixel basis, applying lighting effects for the red, green, and blue color components. Phong shading is not currently supported.
D3DPSHADECAPS_COLORFLATMONO
Device can support colored flat shading in the D3DCOLOR_MONO color model.
D3DPSHADECAPS_COLORFLATRGB
Device can support colored flat shading in the D3DCOLOR_RGB color model. In these modes, the color component for a primitive is provided as part of the color for the first vertex of the primitive. In monochromatic lighting modes, only the blue component of the color is interpolated. In RGB lighting modes, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORGOURAUDMONO
Device can support colored Gouraud shading in the D3DCOLOR_MONOcolor model.
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the D3DCOLOR_RGB color model. In these modes, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In monochromatic lighting modes, only the blue component of the color is interpolated. In RGB lighting modes, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORPHONGMONO
Device can support colored Phong shading in the D3DCOLOR_MONO color model.
D3DPSHADECAPS_COLORPHONGRGB
Device can support colored Phong shading in the D3DCOLOR_RGB color model. In these modes, vertex parameters are reevaluated on a per-pixel basis. Lighting effects are applied for the red, green, and blue color components in RGB mode, and for the blue component only for monochromatic mode. Phong shading is not currently supported.
D3DPSHADECAPS_FOGFLAT
Device can support fog in the flat shading model.
D3DPSHADECAPS_FOGGOURAUD
Device can support fog in the Gouraud shading model.
D3DPSHADECAPS_FOGPHONG
Device can support fog in the Phong shading model. Phong shading is not currently supported.
D3DPSHADECAPS_SPECULARFLATMONO
Device can support specular highlights in flat shading in the D3DCOLOR_MONO color model.
D3DPSHADECAPS_SPECULARFLATRGB
Device can support specular highlights in flat shading in the D3DCOLOR_RGB color model.
D3DPSHADECAPS_SPECULARGOURAUDMONO
Device can support specular highlights in Gouraud shading in the D3DCOLOR_MONO color model.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device can support specular highlights in Gouraud shading in the D3DCOLOR_RGB color model.
D3DPSHADECAPS_SPECULARPHONGMONO
Device can support specular highlights in Phong shading in the D3DCOLOR_MONO color model. Phong shading is not currently supported.
D3DPSHADECAPS_SPECULARPHONGRGB
Device can support specular highlights in Phong shading in the D3DCOLOR_RGB color model. Phong shading is not currently supported.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
D3DPTBLENDCAPS_COPY
Copy texture-blending mode (D3DTBLEND_COPY ) is supported.
D3DPTBLENDCAPS_DECAL
Decal texture-blending mode (D3DTBLEND_DECAL ) is supported.
D3DPTBLENDCAPS_DECALALPHA
Decal-alpha texture-blending mode (D3DTBLEND_DECALALPHA ) is supported.
D3DPTBLENDCAPS_DECALMASK
Decal-mask texture-blending mode (D3DTBLEND_DECALMASK ) is supported.
D3DPTBLENDCAPS_MODULATE
Modulate texture-blending mode (D3DTBLEND_MODULATE ) is supported.
D3DPTBLENDCAPS_MODULATEALPHA
Modulate-alpha texture-blending mode (D3DTBLEND_MODULATEALPHA ) is supported.
D3DPTBLENDCAPS_MODULATEMASK
Modulate-mask texture-blending mode (D3DTBLEND_MODULATEMASK ) is supported.
D3DPTEXTURECAPS_ALPHA
RGBA textures are supported. If this capability is not set, only RGB textures are supported in those modes.
D3DPTEXTURECAPS_BORDER
Texture mapping along borders is supported.
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction is supported.
D3DPTEXTURECAPS_POW2
All non-mipmapped textures must have widths and heights specified as powers of two if this flag is set. (Note that all mipmapped textures must always have dimensions that are powers of two.)
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TRANSPARENCY
Texture transparency is supported. (Only those texels that are not the current transparent color are drawn.)
D3DPTFILTERCAPS_LINEAR
A weighted average of a 2-by-2 area of texels surrounding the desired pixel is used. This applies to both zooming in and zooming out. If either is supported, both zooming in and zooming out must be supported.
D3DPTFILTERCAPS_LINEARMIPLINEAR
Interpolate between the two nearest mipmaps.
D3DPTFILTERCAPS_LINEARMIPNEAREST
Interpolate between the two nearest mipmaps.
D3DPTFILTERCAPS_MIPLINEAR
Use the appropriate mipmap for texel selection.
D3DPTFILTERCAPS_MIPNEAREST
Use the appropriate mipmap for texel selection.
D3DPTFILTERCAPS_NEAREST
The texel with coordinates nearest to the desired pixel value is used. This applies to both zooming in and zooming out. If either is supported, both zooming in and zooming out must be supported.
D3DRENDERSTATE_ALPHAFUNC
One D3DCMP_ value. The default value is D3DCMP_ALWAYS. This field enables an application to accept or reject a pixel based on its alpha value.
D3DRENDERSTATE_ALPHAREF
Value specifying a reference alpha value against which pixels are tested when alpha-testing is enabled. The default value is 0.
D3DRENDERSTATE_ALPHATESTENABLE
This member enables applications to turn off the tests that otherwise would accept or reject a pixel based on its alpha value. Set to TRUE to enable alpha tests. The default value is FALSE.
D3DRENDERSTATE_ANTIALIAS
Anti-aliasing primitive edges. The default value is FALSE.
D3DRENDERSTATE_BLENDENABLE
TRUE to enable alpha blending. The default value is FALSE.
D3DRENDERSTATE_CULLMODE
One D3DCULL_ value. Software renderers have a fixed culling order and do not support changing the culling mode. The default value is D3DCULL_CCW.
D3DRENDERSTATE_DESTBLEND
One D3DBLEND_ value. The default value is D3DBLEND_ZERO.
D3DRENDERSTATE_DITHERENABLE
TRUE to enable dithering. The default value is FALSE.
D3DRENDERSTATE_FILLMODE
One or more D3DFILL_ values. The default value is D3DFILL_SOLID.
D3DRENDERSTATE_FOGCOLOR
A D3DCOLOR_ value. The default value is 0.
D3DRENDERSTATE_FOGENABLE
TRUE to enable fog. The default value is FALSE.
D3DRENDERSTATE_FOGTABLEDENSITY
Sets the maximum fog density for linear fog mode. This value can range from 0 to 1.
D3DRENDERSTATE_FOGTABLEEND
Fog table end. This is the position at which fog effects reach their maximum density for linear fog mode.
D3DRENDERSTATE_FOGTABLEMODE
A D3DFOG_ value. The default value is D3DFOG_NONE.
D3DRENDERSTATE_FOGTABLESTART
Fog table start. This is the position at which fog effects begin for linear fog mode.
D3DRENDERSTATE_LASTPIXEL
TRUE to prevent drawing the last pixel in a line. The default value is TRUE.
D3DRENDERSTATE_LINEPATTERN
Reserved.
D3DRENDERSTATE_MONOENABLE
TRUE to enable monochromatic rendering. The default value is FALSE. If the device does not support RGB rendering, the value will be TRUE. Applications can check whether the device supports RGB rendering by using the D3dDeviceDesc.dcmColorModel field.
D3DRENDERSTATE_PLANEMASK
Physical plane mask. The default value is 0.
D3DRENDERSTATE_ROP2
One of the 16 ROP2 binary raster operations that specify how the supplied pixels are combined with the pixels of the display surface. Applications can use the D3DPRASTERCAPS_ROP2 flag in the D3dFindDeviceSearch.rasterCaps field to determine whether additional raster operations are supported. The default value is R2_COPYPEN.
D3DRENDERSTATE_SHADEMODE
One or more D3DSHADE_ values. The default value is D3DSHADE_GOURAUD .
D3DRENDERSTATE_SPECULARENABLE
TRUE to enable specular. The default value is TRUE.
D3DRENDERSTATE_SRCBLEND
One D3DBLEND_ value. The default value is D3DBLEND_ONE .
D3DRENDERSTATE_STIPPLEDALPHA
TRUE to enable stippled alpha. The default value is FALSE.
D3DRENDERSTATE_STIPPLEENABLE
Enables stippling in the device driver. When stippled alpha is enabled, it must override the current stipple pattern. When stippled alpha is disabled, the stipple pattern must be returned.
D3DRENDERSTATE_STIPPLEPATTERN00
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN01
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN02
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN03
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN04
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN05
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN06
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN07
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN08
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN09
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN10
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN11
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN12
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN13
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN14
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN15
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN16
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN17
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN18
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN19
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN20
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN21
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN22
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN23
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN24
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN25
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN26
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN27
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN28
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN29
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN30
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_STIPPLEPATTERN31
Stipple pattern. Each render state applies to a separate line of the stipple pattern.
D3DRENDERSTATE_SUBPIXEL
TRUE to enable subpixel correction. The default value is FALSE.
D3DRENDERSTATE_SUBPIXELX
TRUE to enable correction in x-values only. The default value is FALSE.
D3DRENDERSTATE_TEXTUREADDRESS
One D3DTADDRESS_ value. The default value is D3DTADDRESS_WRAP .
D3DRENDERSTATE_TEXTUREHANDLE
Texture handle. The default value is null.
D3DRENDERSTATE_TEXTUREMAG
One D3DFILTER_ value. The default value is D3DFILTER_NEAREST .
D3DRENDERSTATE_TEXTUREMAPBLEND
One D3DTBLEND_ value. The default value is D3DTBLEND_MODULATE .
D3DRENDERSTATE_TEXTUREMIN
One D3DFILTER_ value. The default value is D3DFILTER_NEAREST.
D3DRENDERSTATE_TEXTUREPERSPECTIVE
TRUE for perspective correction. The default value is FALSE.
D3DRENDERSTATE_WRAPU
TRUE for wrapping in u-direction. The default value is FALSE.
D3DRENDERSTATE_WRAPV
TRUE for wrapping in v-direction. The default value is FALSE.
D3DRENDERSTATE_ZENABLE
TRUE to enable the z-buffer comparison test when writing to the frame buffer. The default value is FALSE.
D3DRENDERSTATE_ZFUNC
One D3DCMP_ value. This field enables an application to accept or reject a pixel based on its distance from the camera. The default value is D3DCMP_LESSEQUAL .
D3DRENDERSTATE_ZVISIBLE
TRUE to enable z-checking. Z-checking is a culling technique in which a polygon representing the screen space of an entire group of polygons is tested against the z-buffer to discover whether any of the polygons should be drawn. The default value is FALSE.
D3DRENDERSTATE_ZWRITEENABLE
TRUE to enable z-writes. This member enables an application to prevent the system from updating the z-buffer with new z-values. The default value is TRUE.
D3DRMANIMATION_CLOSED
Animation plays continually, looping back to the beginning whenever it reaches the end. In a closed animation, the last key in the animation should be a repeat of the first. This repeated key is used to indicate the time difference between the last and first keys in the looping animation.
D3DRMANIMATION_LINEARPOSITION
The animation's position is set linearly.
D3DRMANIMATION_OPEN
The animation plays once and stops.
D3DRMANIMATION_POSITION
The animation's position matrix overwrites any transformation matrices that could be set by other methods.
D3DRMANIMATION_SCALEANDROTATION
The animation's scale and rotation matrix overwrites any transformation matrices that could be set by other methods.
D3DRMANIMATION_SPLINEPOSITION
The animation's position is set using splines.
D3DRMCOLOR_FROMFACE
The object's color source is a face.
D3DRMCOLOR_FROMVERTEX
The object's color source is a vertex.
D3DRMCOMBINE_AFTER
The supplied matrix is multiplied with the frame's current matrix and follows the current matrix in the calculation.
D3DRMCOMBINE_BEFORE
The supplied matrix is multiplied with the frame's current matrix and precedes the current matrix in the calculation.
D3DRMCOMBINE_REPLACE
The supplied matrix replaces the frame's current matrix.
D3DRMCONSTRAIN_X
Use only y- and z-rotations.
D3DRMCONSTRAIN_Y
Use only x- and z-rotations.
D3DRMCONSTRAIN_Z
Use only x- and y-rotations.
D3DRMFILL_MASK
Fill using a mask.
D3DRMFILL_MAX
Maximum value for fill mode.
D3DRMFILL_POINTS
Fill points only; minimum fill mode.
D3DRMFILL_SOLID
Fill solid objects.
D3DRMFILL_WIREFRAME
Fill wireframes.
D3DRMFOG_EXPONENTIAL
The fog effect intensifies exponentially.
D3DRMFOG_EXPONENTIALSQUARED
The fog effect intensifies exponentially with the square of the distance.
D3DRMFOG_LINEAR
The fog effect intensifies linearly between the start and end points. This is the only fog mode currently supported.
D3DRMLIGHT_AMBIENT
Light is an ambient source.
D3DRMLIGHT_DIRECTIONAL
Light is a directional source.
D3DRMLIGHT_MASK
Lighting uses a mask.
D3DRMLIGHT_MAX
Maximum lighting mode.
D3DRMLIGHT_OFF
Lighting is off.
D3DRMLIGHT_ON
Lighting is on.
D3DRMLIGHT_PARALLELPOINT
Light is a parallel point source.
D3DRMLIGHT_POINT
Light is a point source.
D3DRMLIGHT_SPOT
Light is a spotlight source.
D3DRMLOAD_BYGUID
Load any object by using a specified globally unique identifier (GUID).
D3DRMLOAD_BYNAME
Load any object by using a specified name.
D3DRMLOAD_BYPOSITION
Load a stand-alone object based on a given zero-based position (that is, the nth object in the file). Stand-alone objects can contain other objects, but are not contained by any other objects.
D3DRMLOAD_FIRST
This is the default setting. Load the first stand-alone object of the given type (for example, a mesh if the application calls Direct3drmMeshBuilder.loadFromFileByPos). Stand-alone objects can contain other objects, but are not contained by any other objects.
D3DRMLOAD_FROMFILE
Load from a file. This is the default setting.
D3DRMLOAD_FROMMEMORY
Reserved.
D3DRMLOAD_FROMRESOURCE
Reserved.
D3DRMLOAD_FROMSTREAM
Reserved.
D3DRMLOAD_INSTANCEBYCOPYING
Check whether an object already exists with the same name as specified and, if so, copy that object.
D3DRMLOAD_INSTANCEBYREFERENCE
Check whether an object already exists with the same name as specified and, if so, use an instance of that object instead of creating a new one.
D3DRMMATERIAL_FROMFRAME
Material information is retrieved from the frame, overriding any previous material information that the visual object may have possessed.
D3DRMMATERIAL_FROMMESH
Material information is retrieved from the visual object (the mesh) itself. This is the default setting.
D3DRMMATERIAL_FROMPARENT
Material information, along with color or texture information, is inherited from the parent frame.
D3DRMPALETTE_FREE
Renderer may use this entry freely.
D3DRMPALETTE_READONLY
Fixed but may be used by renderer.
D3DRMPALETTE_RESERVED
May not be used by renderer.
D3DRMPROJECT_ORTHOGRAPHIC
The projection is orthographic.
D3DRMPROJECT_PERSPECTIVE
The projection is perspective.
D3DRMRENDER_FLAT
Flat shaded.
D3DRMRENDER_GOURAUD
Gouraud shaded.
D3DRMRENDER_PHONG
Phong shaded. Phong shading is not currently supported.
D3DRMRENDER_UNLITFLAT
Flat shaded without lighting.
D3DRMRENDER_WIREFRAME
Display only the edges.
D3DRMSHADE_FLAT
Flat shaded.
D3DRMSHADE_GOURAUD
Gouraud shaded.
D3DRMSHADE_MASK
Shading uses a mask.
D3DRMSHADE_MAX
Maximum shade.
D3DRMSHADE_PHONG
Phong shaded. Phong shading is not currently supported.
D3DRMSORT_BACKTOFRONT
Child frames are sorted back-to-front.
D3DRMSORT_FROMPARENT
Child frames inherit the sorting order of their parents. This is the default setting.
D3DRMSORT_FRONTTOBACK
Child frames are sorted front-to-back.
D3DRMSORT_NONE
Child frames are not sorted.
D3DRMTEXTURE_LINEAR
Linearly interpolate the four nearest pixels.
D3DRMTEXTURE_LINEARMIPLINEAR
Similar to D3DRMTEXTURE_MIPLINEAR, but interpolates between the two nearest mipmaps.
D3DRMTEXTURE_LINEARMIPNEAREST
Similar to D3DRMTEXTURE_MIPNEAREST, but interpolates between the two nearest mipmaps.
D3DRMTEXTURE_MIPLINEAR
Similar to D3DRMTEXTURE_LINEAR, but uses the appropriate mipmap instead of the texture.
D3DRMTEXTURE_MIPNEAREST
Similar to D3DRMTEXTURE_NEAREST, but uses the appropriate mipmap instead of the texture.
D3DRMTEXTURE_NEAREST
Choose the nearest pixel in the texture.
D3DRMWIREFRAME_CULL
The backfacing faces are not drawn.
D3DRMWIREFRAME_HIDDENLINE
Wireframe-rendered lines are obscured by nearer objects.
D3DRMWRAP_CHROME
The wrap allocates texture coordinates so that the texture appears to be reflected onto the objects.
D3DRMWRAP_CYLINDER
The wrap is cylindrical.
D3DRMWRAP_FLAT
The wrap is flat.
D3DRMWRAP_SPHERE
The wrap is spherical.
D3DRMXOF_BINARY
File is in binary format. This is the default setting.
D3DRMXOF_COMPRESSED
Not currently supported.
D3DRMXOF_TEXT
File is in text format.
D3DRMXOFSAVE_ALL
Save normal vectors, texture coordinates, materials, and texture names in addition to the basic geometry.
D3DRMXOFSAVE_MATERIALS
Save materials in addition to the basic geometry.
D3DRMXOFSAVE_NORMALS
Save normal vectors in addition to the basic geometry.
D3DRMXOFSAVE_TEMPLATES
Save templates with the file. By default, templates are not saved.
D3DRMXOFSAVE_TEXTURECOORDINATES
Save texture coordinates in addition to the basic geometry.
D3DRMXOFSAVE_TEXTURENAMES
Save texture names in addition to the basic geometry.
D3DRMZBUFFER_DISABLE
Z-buffering is disabled.
D3DRMZBUFFER_ENABLE
Z-buffering is enabled.
D3DRMZBUFFER_FROMPARENT
The frame inherits the z-buffer setting from its parent frame. This is the default setting.
D3DSETSTATUS_ALL
D3DSETSTATUS_EXTENTS
Sets the extents of the bounding box specified in the D3dStatus.x1, D3dStatus.y1, D3dStatus.x2, and D3dStatus.y2 fields.
D3DSETSTATUS_STATUS
Sets the status.
D3DSHADE_FLAT
Flat shade mode. The color of the first vertex in the triangle is used to determine the color of the face.
D3DSHADE_GOURAUD
Gouraud shade mode. The color of the face is determined by a linear interpolation between all three of the triangle's vertices.
D3DSHADE_PHONG
Phong shade mode. This mode is not currently supported.
D3DSTATE_OVERRIDE_BIAS
Override bias.
D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
D3DSTATUS_CLIPINTERSECTIONBACK
Logical AND of the clip flags for the vertices compared to the back clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONBOTTOM
Logical AND of the clip flags for the vertices compared to the bottom of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONFRONT
Logical AND of the clip flags for the vertices compared to the front clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONGEN0
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONGEN1
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONGEN2
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONGEN3
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONGEN4
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONGEN5
Logical AND of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONLEFT
Logical AND of the clip flags for the vertices compared to the left side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONRIGHT
Logical AND of the clip flags for the vertices compared to the right side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONTOP
Logical AND of the clip flags for the vertices compared to the top of the viewing frustum.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
D3DSTATUS_CLIPUNIONBACK
Equal to D3DCLIP_BACK.
D3DSTATUS_CLIPUNIONBOTTOM
Equal to D3DCLIP_BOTTOM.
D3DSTATUS_CLIPUNIONFRONT
Equal to D3DCLIP_FRONT.
D3DSTATUS_CLIPUNIONGEN0
Equal to D3DCLIP_GEN0
D3DSTATUS_CLIPUNIONGEN1
Equal to D3DCLIP_GEN1.
D3DSTATUS_CLIPUNIONGEN2
Equal to D3DCLIP_GEN2.
D3DSTATUS_CLIPUNIONGEN3
Equal to D3DCLIP_GEN3.
D3DSTATUS_CLIPUNIONGEN4
Equal to D3DCLIP_GEN4.
D3DSTATUS_CLIPUNIONGEN5
Equal to D3DCLIP_GEN5.
D3DSTATUS_CLIPUNIONLEFT
Equal to D3DCLIP_LEFT.
D3DSTATUS_CLIPUNIONRIGHT
Equal to D3DCLIP_RIGHT.
D3DSTATUS_CLIPUNIONTOP
Equal to D3DCLIP_TOP.
D3DSTATUS_DEFAULT
Combination of D3DSTATUS_CLIPINTERSECTION and D3DSTATUS_ZNOTVISIBLE flags. This value is the default.
D3DSTATUS_ZNOTVISIBLE
Reserved.
D3DTADDRESS_CLAMP
Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0.
D3DTADDRESS_MIRROR
Equivalent to a tiling texture-addressing mode (that is, when neither D3DRENDERSTATE_WRAPU nor D3DRENDERSTATE_WRAPV is used), except that the texture is flipped at every integer junction. For u-values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again, and so on.
D3DTADDRESS_WRAP
The D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV render states are used. This is the default setting.
D3DTBLEND_COPY
Copy texture-blending is supported.
D3DTBLEND_DECAL
Decal texture-blending is supported. In this mode, the RGB and alpha values of the texture replace the colors that would have been used with no texturing.
D3DTBLEND_DECALALPHA
Decal-alpha texture-blending is supported. In this mode, the RGB and alpha values of the texture are blended with the colors that would have been used with no texturing.

In the D3DTBLEND_DECALALPHA mode, any alpha values in the texture replace the alpha values in the colors that would have been used with no texturing.

D3DTBLEND_DECALMASK
Decal-mask texture-blending is supported.
D3DTBLEND_MODULATE
Modulate texture-blending is supported. In this mode, the RGB values of the texture are multiplied with the RGB values that would have been used with no texturing. Any alpha values in the texture replace the alpha values that would have been used with no texturing.
D3DTBLEND_MODULATEALPHA
Modulate-alpha texture-blending is supported. In this mode, the RGB values of the texture are multiplied with the RGB values that would have been used with no texturing, and the alpha values of the texture are multiplied with the alpha values that would have been used with no texturing.
D3DTBLEND_MODULATEMASK
Modulate-mask texture-blending is supported.
D3DTRANSFORM_CLIPPED
The method uses the current transformation matrix to transform a set of vertices, checking the resulting vertices to see if they are within the viewing frustum. The homogeneous part of the D3dTransformData.in field will be set if the vertex is clipped. Otherwise, only the screen coordinates will be set. The D3dTransformData.x1, D3dTransformData.y1, D3dTransformData.x2, and D3dTransformData.y2 fields will also be set to the 2D bounding rectangle of the resulting vertices.
D3DTRANSFORM_UNCLIPPED
The method uses the current transformation matrix to transform a set of vertices. In this case, the system assumes that all the resulting coordinates will be within the viewing frustum. The D3dTransformData.x1, D3dTransformData.y1, D3dTransformData.x2, and D3dTransformData.y2 fields will be set to the bounding rectangle of the resulting vertices.
D3DTRANSFORMSTATE_PROJECTION
Define the matrix for the projection transformation. The default value is null (the identity matrix).
D3DTRANSFORMSTATE_VIEW
Define the matrix for the view transformation. The default value is null (the identity matrix).
D3DTRANSFORMSTATE_WORLD
Define the matrix for the world transformation. The default values is null (the identity matrix).
D3DTRIFLAG_EDGEENABLE1
Edge defined by v1–v2.
D3DTRIFLAG_EDGEENABLE2
Edge defined by v2–v3.
D3DTRIFLAG_EDGEENABLE3
Edge defined by v3–v1.
D3DTRIFLAG_EDGEENABLETRIANGLE
All edges.
D3DTRIFLAG_EVEN
The v1–v2 edge of the current triangle is adjacent to the v3–v1 edge of the previous triangle; that is, v1 is the previous v1, and v2 is the previous v3.
D3DTRIFLAG_ODD
The v1–v2 edge of the current triangle is adjacent to the v2–v3 edge of the previous triangle; that is, v1 is the previous v3, and v2 is the previous v2.
D3DTRIFLAG_START
Begin the strip or fan, loading all three vertices.
DD_OK
The request completed successfully.
DDBD_1
One bit per pixel.
DDBD_16
Sixteen bits per pixel.
DDBD_2
Two bits per pixel.
DDBD_24
Twenty-four bits per pixel.
DDBD_32
Thirty-two bits per pixel.
DDBD_4
Four bits per pixel.
DDBD_8
Eight bits per pixel.
DDBLT_ALPHADEST
Use either the alpha information in the pixel format or the alpha channel surface attached to the destination surface as the alpha channel for this blit.
DDBLT_ALPHADESTCONSTOVERRIDE
Uses the DDBltFx.alphaDestConst field as the alpha channel for the destination surface for this blit.
DDBLT_ALPHADESTNEG
Indicates that the destination surface becomes more transparent as the alpha value increases (0 is opaque).
DDBLT_ALPHADESTSURFACEOVERRIDE
Reserved.
DDBLT_ALPHAEDGEBLEND
Uses the DDBltFx.alphaEdgeBlend field as the alpha channel for the edges of the image that border the colors of the color key.
DDBLT_ALPHASRC
Uses either the alpha information in the pixel format or the alpha channel surface attached to the source surface as the alpha channel for this blit.
DDBLT_ALPHASRCCONSTOVERRIDE
Uses the DDBltFx.alphaSrcConst field as the alpha channel for the source for this blit.
DDBLT_ALPHASRCNEG
Indicates that the source surface becomes more transparent as the alpha value increases (0 is opaque).
DDBLT_ALPHASRCSURFACEOVERRIDE
Reserved.
DDBLT_ASYNC
Processes this blit asynchronously through the FIFO hardware in the order received. If there is no room in the FIFO hardware, the call fails.
DDBLT_COLORFILL
Uses the DDBltFx.fillValue field as the RGB color with which to fill the destination rectangle on the destination surface.
DDBLT_DDFX
Uses the DDBltFx.ddfx field to specify the effects to be used for this blit.
DDBLT_DDROPS
Uses the DDBltFx.ddrop field to specify the raster operations that are not part of the Microsoft® Win32® API.
DDBLT_DEPTHFILL
Reserved.
DDBLT_KEYDEST
Uses the color key associated with the destination surface.
DDBLT_KEYDESTOVERRIDE
Uses the DDBltFx.destColorSpaceLowValue and DDBltFx.destColorSpaceHighValue fields as the color key for the destination surface.
DDBLT_KEYSRC
Uses the color key associated with the source surface.
DDBLT_KEYSRCOVERRIDE
Uses the DDBltFx.srcColorSpaceLowValue and DDBltFx.srcColorSpaceHighValue fields as the color key for the source surface.
DDBLT_ROP
Uses the DDBltFx.rop field for the raster operation for this blit. The raster operations are the same as those defined in the Win32 API.
DDBLT_ROTATIONANGLE
Uses the DDBltFx.rotationAngle field as the rotation angle (specified in 1/100th of a degree) for the surface.
DDBLT_WAIT
Returns as soon as the blit can be set up.
DDBLT_ZBUFFER
Performs a z-buffered blit using the z-buffers attached to the source and destination surfaces and the DDBltFx.zbufferOpCode field as the z-buffer opcode.
DDBLT_ZBUFFERDESTCONSTOVERRIDE
Performs a z-buffered blit using the DDBltFx.zDestConst and DDBltFx.zbufferOpCode fields as the z-buffer and z-buffer opcode, respectively, for the destination.
DDBLT_ZBUFFERDESTOVERRIDE
Reserved.
DDBLT_ZBUFFERSRCCONSTOVERRIDE
Performs a z-buffered blit using the DDBltFx.zSrcConst and DDBltFx.zbufferOpCode fields as the z-buffer and z-buffer opcode, respectively, for the source.
DDBLT_ZBUFFERSRCOVERRIDE
Reserved.
DDBLTFAST_DESTCOLORKEY
A transparent blit that uses the destination's color key.
DDBLTFAST_NOCOLORKEY
A normal copy blit with no transparency.
DDBLTFAST_SRCCOLORKEY
A transparent blit that uses the source's color key.
DDBLTFAST_WAIT
Returns as soon as the blit can be set up.
DDBLTFX_ARITHSTRETCHY
Use arithmetic stretching along the y-axis for this blit.
DDBLTFX_MIRRORLEFTRIGHT
Turn the surface on its y-axis. This blit mirrors the surface from left to right.
DDBLTFX_MIRRORUPDOWN
Turn the surface on its x-axis. This blit mirrors the surface from top to bottom.
DDBLTFX_NOTEARING
Schedule this blit to avoid tearing.
DDBLTFX_ROTATE180
Rotate the surface 180 degrees clockwise during this blit.
DDBLTFX_ROTATE270
Rotate the surface 270 degrees clockwise during this blit.
DDBLTFX_ROTATE90
Rotate the surface 90 degrees clockwise during this blit.
DDBLTFX_ZBUFFERBASEDEST
Adds the DDBltFx.zbufferBaseDest field to each of the source z-values before comparing them with the destination z-values during this z-blit.
DDBLTFX_ZBUFFERRANGE
Use the DDBltFx.zbufferLow and DDBltFx.zbufferHigh fields as range values to specify limits to the bits copied from a source surface during this z-blit.
DDCAPS_3D
Display hardware has 3D acceleration.
DDCAPS_ALIGNBOUNDARYDEST
DirectDraw will support only those source rectangles with the x-axis aligned to the DDCaps.alignBoundaryDest boundaries of the surface.
DDCAPS_ALIGNBOUNDARYSRC
DirectDraw will support only those source rectangles with the x-axis aligned to the DDCaps.alignBoundarySrc boundaries of the surface.
DDCAPS_ALIGNSIZEDEST
DirectDraw will support only those source rectangles whose x-axis sizes, in bytes, are DDCaps.alignSizeDest multiples.
DDCAPS_ALIGNSIZESRC
DirectDraw will support only those source rectangles whose x-axis sizes, in bytes, are DDCaps.alignSizeSrc multiples.
DDCAPS_ALIGNSTRIDE
DirectDraw will create display memory surfaces that have a stride alignment equal to the DDCaps.alignStrideAlign value.
DDCAPS_ALPHA
Indicates that the display hardware supports an alpha channel during blit operations.
DDCAPS_BANKSWITCHED
Display hardware is bank-switched and is potentially very slow at random access to display memory.
DDCAPS_BLT
Display hardware is capable of blit operations.
DDCAPS_BLTCOLORFILL
Display hardware is capable of color filling with a blitter.
DDCAPS_BLTDEPTHFILL
Display hardware is capable of depth filling z-buffers with a blitter.
DDCAPS_BLTFOURCC
Display hardware is capable of color-space conversions during blit operations.
DDCAPS_BLTQUEUE
Display hardware is capable of asynchronous blit operations.
DDCAPS_BLTSTRETCH
Display hardware is capable of stretching during blit operations.
DDCAPS_CANBLTSYSMEM
Display hardware is capable of blitting to or from system memory.
DDCAPS_CANCLIP
Display hardware is capable of clipping with blitting.
DDCAPS_CANCLIPSTRETCHED
Display hardware is capable of clipping while stretch blitting.
DDCAPS_COLORKEY
Support some form of color key in either overlay or blit operations. More specific color key capability information can be found in the DDCaps.colorkeyCaps field.
DDCAPS_COLORKEYHWASSIST
The color key is hardware assisted.
DDCAPS_GDI
Display hardware is shared with GDI.
DDCAPS_NOHARDWARE
There is no hardware support for DirectDraw.
DDCAPS_OVERLAY
Display hardware supports overlays.
DDCAPS_OVERLAYCANTCLIP
Display hardware supports overlays, but cannot clip them.
DDCAPS_OVERLAYFOURCC
Overlay hardware is capable of color-space conversions during overlay operations.
DDCAPS_OVERLAYSTRETCH
Overlay hardware is capable of stretching.
DDCAPS_PALETTE
DirectDraw is capable of creating and supporting DirectDrawPalette objects for more surfaces than only the primary surface.
DDCAPS_PALETTEVSYNC
DirectDraw® is capable of updating a palette synchronized with the vertical refresh.
DDCAPS_READSCANLINE
Display hardware is capable of returning the current scan line.
DDCAPS_STEREOVIEW
Display hardware has stereo vision capabilities.
DDCAPS_VBI
Display hardware is capable of generating a vertical-blank interrupt.
DDCAPS_ZBLTS
Supports the use of z-buffers with blit operations.
DDCAPS_ZOVERLAYS
Supports the use of the DirectDrawSurface.updateOverlayZOrder method as a z-value for overlays to control their layering.
DDCAPS2_CERTIFIED
Display hardware is certified.
DDCAPS2_NO2DDURING3DSCENE
Between calls to the Direct3dDevice.beginScene and Direct3dDevice.endScene methods, 2D operations such as DirectDrawSurface.blt and DirectDrawSurface.lock cannot be performed on any surfaces that Direct3D™ is using.
DDCKEY_COLORSPACE
A color space.
DDCKEY_DESTBLT
Color key or color space to use as a destination color key for blit operations.
DDCKEY_DESTOVERLAY
Color key or color space to use as a destination color key for overlay operations.
DDCKEY_SRCBLT
Color key or color space to use as a source color key for blit operations.
DDCKEY_SRCOVERLAY
Color key or color space to use as a source color key for overlay operations.
DDCKEYCAPS_DESTBLT
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACE
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACEYUV
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTBLTYUV
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTOVERLAY
Supports overlays with color keying of the replaceable bits of the destination surface being overlaid for RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACE
Support a color space as the color key for the destination of RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV
Supports a color space as the color key for the destination of YUV colors.
DDCKEYCAPS_DESTOVERLAYONEACTIVE
Support only one active destination color key value for visible overlay surfaces.
DDCKEYCAPS_DESTOVERLAYYUV
Supports overlays using color keying of the replaceable bits of the destination surface being overlaid for YUV colors.
DDCKEYCAPS_NOCOSTOVERLAY
There are no bandwidth tradeoffs for using the color key with an overlay.
DDCKEYCAPS_SRCBLT
Supports transparent blitting using the color key for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACE
Supports transparent blitting using a color space for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACEYUV
Supports transparent blitting using a color space for the source with this surface for YUV colors.
DDCKEYCAPS_SRCBLTYUV
Supports transparent blitting using the color key for the source with this surface for YUV colors.
DDCKEYCAPS_SRCOVERLAY
Supports overlays using the color key for the source with this overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACE
Supports overlays using a color space as the source color key for the overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV
Supports overlays using a color space as the source color key for the overlay surface for YUV colors.
DDCKEYCAPS_SRCOVERLAYONEACTIVE
Supports only one active source color key value for visible overlay surfaces.
DDCKEYCAPS_SRCOVERLAYYUV
Supports overlays using the color key for the source with this overlay surface for YUV colors.
DDCOOPERATIVE_CLIPTOCOMPONENT
Used in the blt and the bltFast methods to specify that the DirectDraw object clips completely to a component's region.
DDCOOPERATIVE_OFFSETTOCOMPONENT
Used in the blt and the bltFast methods to specify that the DirectDraw object will only offset the blt to the component but will not clip to other components.
DDCREATE_EMULATIONONLY
Reserved.
DDCREATE_HARDWAREONLY
Reserved.
DDEDM_REFRESHRATES
Enumerates modes with different refresh rates. DirectDraw.enumDisplayModes guarantees that a particular mode will be enumerated only once. This flag specifies whether the refresh rate is taken into account when determining if a mode is unique.
DDENUMOVERLAYZ_BACKTOFRONT
Enumerates overlays back to front.
DDENUMOVERLAYZ_FRONTTOBACK
Enumerates overlays front to back.
DDENUMSURFACES_ALL
Enumerates all of the surfaces that meet the search criterion.
DDENUMSURFACES_CANBECREATED
Enumerates the first surface that can be created and meets the search criterion.
DDENUMSURFACES_DOESEXIST
Enumerates the already existing surfaces that meet the search criterion.
DDENUMSURFACES_MATCH
Searches for any surface that matches the surface description.
DDENUMSURFACES_NOMATCH
Searches for any surface that does not match the surface description.
DDERR_SURFACELOST
Access to the surface is refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have the DirectDrawSurface.restore method called on it.
DDERR_WASSTILLDRAWING
The previous blit operation that is transferring information to or from this surface is incomplete.
DDFLIP_WAIT
Typically, if the flip cannot be set up because the state of the display hardware is not appropriate, the DirectDrawSurface.flip method returns immediately and no flip occurs. Setting this flag causes the method to continue trying to flip. DirectDrawSurface.flip does not return until the flipping operation has been successfully set up or an error that prevents flipping occurs.
DDFXALPHACAPS_BLTALPHAEDGEBLEND
Supports alpha blending around the edge of a source color-keyed surface. Used for blit operations.
DDFXALPHACAPS_BLTALPHAPIXELS
Supports alpha information in pixel format. The bit depth of alpha information in the pixel format can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for blit operations.
DDFXALPHACAPS_BLTALPHAPIXELSNEG
Supports alpha information in pixel format. The bit depth of alpha information in the pixel format can be 1, 2, 4, or 8. The alpha value becomes more transparent as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDCAPS_ALPHA is set. Used for blit operations.
DDFXALPHACAPS_BLTALPHASURFACES
Supports alpha-only surfaces. The bit depth of an alpha-only surface can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for blit operations.
DDFXALPHACAPS_BLTALPHASURFACESNEG
Indicates that the alpha channel becomes more transparent as the alpha value increases. The depth of the alpha channel data can be 1, 2, 4, or 8. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be set only if DDFXCAPS_ALPHASURFACES has been set. Used for blit operations.
DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND
Supports alpha blending around the edge of a source color-keyed surface. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELS
Supports alpha information in pixel format. The bit depth of alpha information in pixel format can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG
Supports alpha information in pixel format. The bit depth of alpha information in pixel format can be 1, 2, 4, or 8. The alpha value becomes more transparent as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDFXCAPS_ALPHAPIXELS has been set. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACES
Supports alpha-only surfaces. The bit depth of an alpha-only surface can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACESNEG
Indicates that the alpha channel becomes more transparent as the alpha value increases. The depth of the alpha channel data can be 1, 2, 4, or 8. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDFXCAPS_ALPHASURFACES has been set. Used for overlays.
DDFXCAPS_BLTARITHSTRETCHY
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically).
DDFXCAPS_BLTARITHSTRETCHYN
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically), and works only for integer stretching ( x 1, x 2, and so on).
DDFXCAPS_BLTMIRRORLEFTRIGHT
Supports mirroring left to right in a blit operation.
DDFXCAPS_BLTMIRRORUPDOWN
Supports mirroring top to bottom in a blit operation.
DDFXCAPS_BLTROTATION
Supports arbitrary rotation in a blit operation.
DDFXCAPS_BLTROTATION90
Supports 90-degree rotations in a blit operation.
DDFXCAPS_BLTSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKXN
Supports integer shrinking ( x 1, x 2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKYN
Supports integer shrinking ( x 1, x 2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHXN
Supports integer stretching ( x1, x2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHYN
Supports integer stretching ( x1, x2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_OVERLAYARITHSTRETCHY
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during an overlay operation. Occurs along the y-axis (vertically).
DDFXCAPS_OVERLAYARITHSTRETCHYN
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during an overlay operation. Occurs along the y-axis (vertically), and works only for integer stretching ( x 1, x 2, and so on).
DDFXCAPS_OVERLAYMIRRORLEFTRIGHT
Supports mirroring of overlays around the vertical axis.
DDFXCAPS_OVERLAYMIRRORUPDOWN
Supports mirroring of overlays across the horizontal axis.
DDFXCAPS_OVERLAYSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKXN
Supports integer shrinking ( x 1, x 2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKYN
Supports integer shrinking ( x1, x2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHXN
Supports integer stretching ( x1, x2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHYN
Supports integer stretching ( x1, x2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDGBS_CANBLT
Inquires whether a blit involving this surface can occur immediately, and returns DD_OK if the blit can be completed.
DDGBS_ISBLTDONE
Inquires whether the blit is done, and returns DD_OK if the last blit on this surface has completed.
DDGFS_CANFLIP
Inquires whether this surface can be flipped immediately. Returns DD_OK if the flip can be completed.
DDGFS_ISFLIPDONE
Inquires whether the flip has finished. Returns DD_OK if the last flip on this surface has completed.
DDLOCK_EVENT
Triggers the event when DirectDrawSurface.lock can return the surface memory requested. This flag is set if an event handle is being passed to DirectDrawSurface.lock. If multiple locks of this type are placed on a surface, events are triggered in FIFO order.
DDLOCK_READONLY
Indicates that the surface being locked will be read-only.
DDLOCK_SURFACEMEMORYPTR
Indicates that valid memory at the top of the specified rectangle should be returned. If no rectangle is specified, the top of the surface is returned. This is the default.
DDLOCK_WAIT
Typically, if a lock cannot be obtained because a blit operation is in progress, no action is taken. If this flag is set, however, DirectDrawSurface.lock retries until a lock is obtained.
DDLOCK_WRITEONLY
Indicates that the surface being locked will be write-only.
DDOVER_ADDDIRTYRECT
Adds a dirty rectangle to an emulated overlay surface.
DDOVER_ALPHADEST
Uses either the alpha information in pixel format or the alpha channel surface attached to the destination surface as the alpha channel for this overlay.
DDOVER_ALPHADESTCONSTOVERRIDE
Reserved.
DDOVER_ALPHADESTNEG
Indicates that the destination surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHADESTSURFACEOVERRIDE
Reserved.
DDOVER_ALPHAEDGEBLEND
Reserved.
DDOVER_ALPHASRC
Uses either the alpha information in pixel format or the alpha channel surface attached to the source surface as the source alpha channel for this overlay.
DDOVER_ALPHASRCCONSTOVERRIDE
Reserved.
DDOVER_ALPHASRCNEG
Indicates that the source surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHASRCSURFACEOVERRIDE
Reserved.
DDOVER_DDFX
Uses the overlay FX flags to define special overlay effects.
DDOVER_HIDE
Turns this overlay off.
DDOVER_KEYDEST
Uses the color key associated with the destination surface.
DDOVER_KEYDESTOVERRIDE
Reserved.
DDOVER_KEYSRC
Uses the color key associated with the source surface.
DDOVER_KEYSRCOVERRIDE
Reserved.
DDOVER_REFRESHALL
Ignores the dirty rectangle list and updates the overlay display completely. This clears the dirty rectangle list.
DDOVER_REFRESHDIRTYRECTS
Updates the overlay display using the list of dirty rectangles previously constructed for this destination. This clears the dirty rectangle list.
DDOVER_SHOW
Turns on this overlay.
DDOVERFX_ARITHSTRETCHY
If stretching, uses arithmetic stretching along the y-axis for this overlay.
DDOVERFX_MIRRORLEFTRIGHT
Mirrors the overlay around the vertical axis.
DDOVERFX_MIRRORUPDOWN
Mirrors the overlay around the horizontal axis.
DDOVERZ_INSERTINBACKOF
Inserts this overlay behind the reference overlay in the overlay chain.
DDOVERZ_INSERTINFRONTOF
Inserts this overlay in front of the reference overlay in the overlay chain.
DDOVERZ_MOVEBACKWARD
Moves this overlay one position backward in the overlay chain.
DDOVERZ_MOVEFORWARD
Moves this overlay one position forward in the overlay chain.
DDOVERZ_SENDTOBACK
Moves this overlay to the back of the overlay chain.
DDOVERZ_SENDTOFRONT
Moves this overlay to the front of the overlay chain.
DDPCAPS_1BIT
Indicates that the index is 1 bit. There are two entries in the color table.
DDPCAPS_2BIT
Indicates that the index is 2 bits. There are four entries in the color table.
DDPCAPS_4BIT
Indicates that the index is 4 bits. There are 16 entries in the color table.
DDPCAPS_8BIT
Indicates that the index is 8 bits. There are 256 entries in the color table.
DDPCAPS_8BITENTRIES
Specifies an index to an 8-bit color index. This field is valid only when used with the DDPCAPS_1BIT, DDPCAPS_2BIT, or DDPCAPS_4BIT capability and when the target surface is in 8 bits per pixel (bpp). Each color entry is 1 byte long and is an index to an 8-bpp palette on the destination surface.
DDPCAPS_ALLOW256
Indicates that this palette can have all 256 entries defined.
DDPCAPS_INITIALIZE
Reserved.
DDPCAPS_PRIMARYSURFACE
Indicates that the palette is attached to the primary surface. Changing the palette has an immediate effect on the display unless the DDPCAPS_VSYNC capability is specified and supported.
DDPCAPS_PRIMARYSURFACELEFT
Indicates that the palette is attached to the primary surface on the left. Changing the palette has an immediate effect on the display unless the DDPCAPS_VSYNC capability is specified and supported.
DDPCAPS_VSYNC
Indicates that the palette can be modified synchronously with the monitor's refresh rate.
DDPF_ALPHA
The pixel format describes an alpha-only surface.
DDPF_ALPHAPIXELS
The surface has alpha channel information in the pixel format.
DDPF_COMPRESSED
The surface will accept pixel data in the specified format and compress it during the write operation.
DDPF_FOURCC
The FourCC code is valid.
DDPF_PALETTEINDEXED1
The surface is 1-bit color indexed.
DDPF_PALETTEINDEXED2
The surface is 2-bit color indexed.
DDPF_PALETTEINDEXED4
The surface is 4-bit color indexed.
DDPF_PALETTEINDEXED8
The surface is 8-bit color indexed.
DDPF_PALETTEINDEXEDTO8
The surface is 1-, 2-, or 4-bit color indexed to an 8-bit palette.
DDPF_RGB
The RGB data in the pixel format structure is valid.
DDPF_RGBTOYUV
The surface will accept RGB data and translate it during the write operation to YUV data. The format of the data to be written will be contained in the pixel format structure. The DDPF_RGB flag will be set.
DDPF_YUV
The YUV data in the pixel format structure is valid.
DDPF_ZBUFFER
The pixel format describes a z-buffer-only surface.
DDSCAPS_3D
Supported for backwards compatibility. Applications should use the DDSCAPS_3DDEVICE flag, instead.
DDSCAPS_3DDEVICE
Indicates that this surface can be used for 3D rendering. Applications can use this flag to ensure that a device that can only render to a certain heap has off-screen surfaces allocated from the correct heap. If this flag is set for a heap, the surface is not allocated from that heap.
DDSCAPS_ALLOCONLOAD
Indicates that memory for the surface is not allocated until the surface is loaded by using the Direct3dTexture.load method.
DDSCAPS_ALPHA
Indicates that this surface contains alpha information. The pixel format must be interrogated to determine whether this surface contains only alpha information or alpha information interlaced with pixel color data (such as RGBA or YUVA).
DDSCAPS_BACKBUFFER
Indicates that this surface is the back buffer of a surface flipping structure. Typically, this capability is set by the DirectDraw.createSurface method when the DDSCAPS_FLIP flag is used. Only the surface that immediately precedes the DDSCAPS_FRONTBUFFER surface has this capability set. The other surfaces are identified as back buffers by the presence of the DDSCAPS_FLIP flag, their attachment order, and the absence of the DDSCAPS_FRONTBUFFER and DDSCAPS_BACKBUFFER capabilities. If this capability is sent to the DirectDraw.createSurface method, a stand-alone back buffer is being created. After this method is called, this surface could be attached to a front buffer, another back buffer, or both to form a surface flipping structure. For more information, see DirectDrawSurface.addAttachedSurface . DirectDraw® supports an arbitrary number of surfaces in a flipping structure.
DDSCAPS_COMPLEX
Indicates a complex surface is being described. A complex surface results in the creation of more than one surface. The additional surfaces are attached to the root surface. The complex surface can be destroyed only by destroying the root.
DDSCAPS_FLIP
Indicates that this surface is a part of a surface flipping structure. When this capability is passed to the DirectDraw.createSurface method, a front buffer and one or more back buffers are created. DirectDraw® sets the DDSCAPS_FRONTBUFFER bit on the front-buffer surface and the DDSCAPS_BACKBUFFER bit on the surface adjacent to the front-buffer surface. The DDSurfaceDesc.backBufferCount field must be set to at least 1 for the method call to succeed. The DDSCAPS_COMPLEX capability must always be set when creating multiple surfaces by using the Class_DirectDraw.createSurface method.
DDSCAPS_FRONTBUFFER
Indicates that this surface is the front buffer of a surface flipping structure. This flag is typically set by the DirectDraw.createSurface method when the DDSCAPS_FLIP capability is set. If this capability is sent to the createSurface method, a stand-alone front buffer is created. This surface will not have the DDSCAPS_FLIP capability. It can be attached to other back buffers to form a flipping structure by using DirectDrawSurface.addAttachedSurface.
DDSCAPS_HWCODEC
Indicates that this surface should be able to have a stream decompressed to it by the hardware.
DDSCAPS_LIVEVIDEO
Indicates that this surface should be able to receive live video.
DDSCAPS_MIPMAP
Indicates that this surface is one level of a mipmap. This surface will be attached to other DDSCAPS_MIPMAP surfaces to form the mipmap. This can be done explicitly by creating a number of surfaces and attaching them by using the DirectDrawSurface.addAttachedSurface method, or implicitly by the DirectDraw.createSurface method. If this capability is set, DDSCAPS_TEXTURE must also be set.
DDSCAPS_MODEX
Indicates that this surface is a 320 x 200 or 320 x 240 Mode X surface.
DDSCAPS_OFFSCREENPLAIN
Indicates that this surface is any off-screen surface that is not an overlay, texture, z-buffer, front-buffer, back-buffer, or alpha surface. It is used to identify plain surfaces.
DDSCAPS_OVERLAY
Indicates that this surface is an overlay. It may or may not be directly visible, depending on whether it is currently being overlaid onto the primary surface. DDSCAPS_VISIBLE can be used to determine if it is being overlaid at the moment.
DDSCAPS_OWNDC
Indicates that this surface will have a device context (DC) association for a long period.
DDSCAPS_PALETTE
Indicates that this device driver allows unique DirectDrawPalette objects to be created and attached to this surface.
DDSCAPS_PRIMARYSURFACE
Indicates the surface is the primary surface. It represents what is visible to the user at the moment.
DDSCAPS_PRIMARYSURFACELEFT
Indicates that this surface is the primary surface for the left eye. It represents what is visible to the user's left eye at the moment. When this surface is created, the surface with the DDSCAPS_PRIMARYSURFACE capability represents what is seen by the user's right eye.
DDSCAPS_SYSTEMMEMORY
Indicates that this surface memory was allocated in system memory.
DDSCAPS_TEXTURE
Indicates that this surface can be used as a 3D texture. It does not indicate whether the surface is being used for that purpose.
DDSCAPS_VIDEOMEMORY
Indicates that this surface exists in display memory.
DDSCAPS_VISIBLE
Indicates that changes made to this surface are immediately visible. It is always set for the primary surface, as well as for overlays while they are being overlaid and texture maps while they are being textured.
DDSCAPS_WRITEONLY
Indicates that only write access is permitted to the surface. Read access from the surface may generate a general protection (GP) fault, but the read results from this surface will not be meaningful.
DDSCAPS_ZBUFFER
Indicates that this surface is the z-buffer. The z-buffer contains information that cannot be displayed. Instead, it contains bit-depth information that is used to determine which pixels are visible and which are obscured.
DDSCL_ALLOWMODEX
Allows the use of Mode X display modes.
DDSCL_ALLOWREBOOT
Allows CTRL+ALT+DEL to function while in exclusive (full-screen) mode.
DDSCL_EXCLUSIVE
Requests the exclusive level.
DDSCL_FULLSCREEN
Indicates that the exclusive-mode owner will be responsible for the entire primary surface. GDI can be ignored.
DDSCL_NORMAL
Indicates that the application will function as a regular Windows® application.
DDSCL_NOWINDOWCHANGES
Indicates that DirectDraw® is not allowed to minimize or restore the application window on activation.
DDSD_ALL
All input fields are valid.
DDSD_ALPHABITDEPTH
Indicates the DDSurfaceDesc.alphaBitDepth field is valid.
DDSD_BACKBUFFERCOUNT
Indicates the DDSurfaceDesc.backBufferCount field is valid.
DDSD_CAPS
Indicates the DDSurfaceDesc.ddsCaps field is valid.
DDSD_CKDESTBLT
Indicates the DDSurfaceDesc.colorkeyDestBltLow and DDSurfaceDesc.colorkeyDestBltHigh fields are valid.
DDSD_CKDESTOVERLAY
Indicates the DDSurfaceDesc.colorkeyDestOverlayLow and DDSurfaceDesc.colorkeyDestOverlayHigh fields are valid.
DDSD_CKSRCBLT
Indicates the DDSurfaceDesc.colorkeySrcBltLow and DDSurfaceDesc.colorkeySrcBltHigh fields are valid.
DDSD_CKSRCOVERLAY
Indicates the DDSurfaceDesc.colorkeySrcOverlayLow and DDSurfaceDesc.colorkeySrcOverlayHigh fields are valid.
DDSD_HEIGHT
Indicates the DDSurfaceDesc.height field is valid.
DDSD_MIPMAPCOUNT
Mip map count.
DDSD_PITCH
Indicates the DDSurfaceDesc.pitch field is valid.
DDSD_PIXELFORMAT
Reserved.
DDSD_REFRESHRATE
Refresh rate.
DDSD_WIDTH
Indicates the DDSurfaceDesc.width field is valid.
DDSD_ZBUFFERBITDEPTH
Z-buffer bit depth.
DDSVCAPS_ENIGMA
Indicates that the stereo view is accomplished using Enigma encoding.
DDSVCAPS_FLICKER
Indicates that the stereo view is accomplished using high-frequency flickering.
DDSVCAPS_REDBLUE
Indicates that the stereo view is accomplished when the viewer looks at the image through red and blue filters placed over the left and right eyes. All images must adapt their color spaces for this process.
DDSVCAPS_SPLIT
Indicates that the stereo view is accomplished with split-screen technology.
DDWAITVB_BLOCKBEGIN
Returns when the vertical-blank interval begins.
DDWAITVB_BLOCKBEGINEVENT
Triggers an event when the vertical blank begins. This value is not currently supported.
DDWAITVB_BLOCKEND
Returns when the vertical-blank interval ends and the display begins.
DPCAPS_GROUPOPTIMIZED
Indicates that the service provider bound to this DirectPlay2 object can optimize group (multicast) messaging.
DPCAPS_GUARANTEEDOPTIMIZED
Indicates that the service provider bound to this DirectPlay2 object supports guaranteed message delivery.
DPCAPS_GUARANTEEDSUPPORTED
Indicates that the DirectPlay object supports guaranteed message delivery, either because the service provider supports it or because DirectPlay implements it on a nonguaranteed service provider.
DPCAPS_ISHOST
Indicates that the DirectPlay2 object created by the calling application is the session host.
DPCAPS_KEEPALIVEOPTIMIZED
The service provider can detect when the connection to the session has been lost.
DPCPA_DTRFLOW
Indicates hardware flow control with DTR.
DPCPA_NOFLOW
Indicates no flow control.
DPCPA_RTSDTRFLOW
Indicates hardware flow control with RTS and DTR
DPCPA_RTSFLOW
Indicates hardware flow control with RTS
DPCPA_XONXOFFFLOW
Indicates software flow control (xon/xoff).
DPENUMPLAYERS_ALL
Enumerates all players.
DPENUMPLAYERS_GROUP
Enumerates groups as well as players.
DPENUMPLAYERS_LOCAL
Enumerates only those players that were created locally by this DirectPlay® object.
DPENUMPLAYERS_REMOTE
Enumerates only those players that were created by remote DirectPlay® objects.
DPENUMPLAYERS_SESSION
Enumerates the players in the session or the group in the session.
DPENUMSESSIONS_ALL
Enumerates all active sessions, whether they are available to join or not. Sessions where the player limit has been reached, new players have been disabled, or joining has been disabled will be enumerated. The application can examine the DPSessionDesc.flags field to determine if the session will allow new applications to join.
DPENUMSESSIONS_AVAILABLE
Enumerates all sessions with a matching password (if provided) that is allowing new applications to join.
DPESC_TIMEDOUT
The enumeration has timed out. Reset the timeOut parameter and return.
DPGET_LOCAL
Retrieves the local data set by this application.
DPGET_REMOTE
Retrieves the current data from the remote shared data space.
DPGETCAPS_GUARANTEED
Retrieves the capabilities for a guaranteed message delivery.
DPLAD_SYSTEM
Indicates that this is a system message informing the application of an event.
DPLCONNECTION_CREATESESSION
Create a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Join the existing session as described in the session description
DPLSYS_APPTERMINATED
Indicates the application started by DirectPlayLobby.runApplication has terminated.
DPLSYS_CONNECTIONSETTINGSREAD
Indicates the application started by the DirectPlayLobby.runApplication method has read the connection settings.
DPLSYS_DPLAYCONNECTFAILED
Indicates the application started by DirectPlayLobby.runApplication failed to connect to a session.
DPLSYS_DPLAYCONNECTSUCCEEDED
Indicates the application started by DirectPlayLobby.runApplication has created a session and is ready for other applications to join or successfully join a session.
DPOPEN_CREATE
Creates a new instance of a gaming session.
DPOPEN_JOIN
Joins an existing instance of a gaming session.
DPPLAYERTYPE_GROUP
Indicates that the message applies to a group.
DPPLAYERTYPE_PLAYER
Indicates that the message applies to a player.
DPRECEIVE_ALL
Returns the first available message. This is the default.
DPRECEIVE_FROMPLAYER
Returns the first message from the player whose ID is specified in the PlayerIDs.sender field. System messages come from player ID DPID_SYSMSG.
DPRECEIVE_PEEK
Returns a message as specified by the other flags, but does not remove it from the message queue.
DPRECEIVE_TOPLAYER
Returns the first message intended for the player whose ID is specified in the PlayerIDs.receiver field.
DPSEND_CLOSESTREAM
Indicates that there will no longer be a lot of guaranteed messages being sent to this player.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery if it is available.
DPSEND_HIGHPRIORITY
Sends the message high-priority. This will force the message to the front of the send queue for immediate transmission. The message will also go to the top of the receiving application's receive buffer.
DPSEND_OPENSTREAM
Indicates an optimization hint to the service provider that there will be a lot of guaranteed messages being sent to this player.
DPSESSION_JOINDISABLED
No new applications can join this session. Any call to the DirectPlay2.open method with the DPOPEN_JOIN flag and the globally unique identifier (GUID) of this session instance will cause an error. If this flag is not specified, new remote applications can join the session until the session player limit is reached.
DPSESSION_KEEPALIVE
Automatically detect when remote players drop out of the game abnormally. Those players will be deleted from the session. If a temporary network outage caused the loss of the players, they will be informed when they return that they were dropped from the session. For more information, see the description for the DPSYS_SESSIONLOST system message in Using System Messages. If this flag is not specified, DirectPlay will not support this feature.
DPSESSION_MIGRATEHOST
If the current host exits, the host will attempt to migrate to another computer so that new players can continue to join. If this flag is not specified, the host will not migrate and new players cannot be created.
DPSESSION_NEWPLAYERSDISABLED
Indicates that new players cannot be created in the session. Any call to the DirectPlay2.createPlayer method by an application in the session will result in an error. Also, new applications cannot join the session. If this flag is not specified, players can be created until the session player limit is reached.
DPSESSION_NODATAMESSAGES
Do not send system messages when remote player or group data changes, by using the DirectPlay2.setPlayerData, DirectPlay2.setGroupData, DirectPlay2.setPlayerName, or DirectPlay2.setGroupName method. If this flag is not specified, messages will be generated indicating that the data changed.
DPSESSION_NOMESSAGEID
Do not attach data to messages indicating who the message is from and who it is to. Saves message overhead if this information is not relevant. (For more information, see the DirectPlay2.receive method.) If this flag is not specified, the message ID will be added.
DPSET_GUARANTEED
Propagates the data by using guaranteed messaging (if available). This flag can only be used with DPSET_REMOTE .
DPSET_LOCAL
This data is for local use only and will not be propagated.
DPSET_REMOTE
This data is for use by all the applications, and will be propagated to all the other applications in the session.
DPSYS_ADDPLAYERTOGROUP
An identifier for a system message sent when a player is added to a group.
DPSYS_CREATEPLAYERORGROUP
An identifier for a system message sent when a player or group is created in a session.
DPSYS_DELETEPLAYERFROMGROUP
An identifier for a system message sent when a player is deleted from a group.
DPSYS_DESTROYPLAYERORGROUP
An identifier for a system message sent when a player or group is deleted from a session.
DPSYS_HOST
An identifier for a system message sent when the current session host exits the session.
DPSYS_SESSIONLOST
DPSYS_SETPLAYERORGROUPDATA
An identifier for a system message sent when the application changes remote player or group data.
DPSYS_SETPLAYERORGROUPNAME
An identifier for a system message sent when the name of a player or group has changed.
DS3D_DEFAULTDISTANCEFACTOR
An application can retrieve the current distance factor set for a listener by using the DirectSound3dListener.getDistanceFactor method. The default value is DS3D_DEFAULTDISTANCEFACTOR (1.0), meaning that one distance unit corresponds to 1 meter.
DS3D_DEFAULTDOPPLERFACTOR
DirectSound can apply to a sound up to 10 times the Doppler shift experienced in the real world by setting a Doppler factor. This Doppler factor has a range of 0 (no Doppler effects) to 10.0 (10 times the Doppler effects found in the physical world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3dListener.commitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.
DS3DMODE_DISABLE
Processing of 3D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
DSBCAPS_CTRL3D
The buffer is a primary buffer that uses 3D control.
DSBCAPS_CTRLALL
The buffer must have all control capabilities.
DSBCAPS_CTRLDEFAULT
The buffer should have default control options. This is the same as specifying the DSBCAPS_CTRLPAN, DSBCAPS_CTRLVOLUME, and DSBCAPS_CTRLFREQUENCY flags.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_GETCURRENTPOSITION2
Indicates that DirectSoundBuffer.getCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards. If a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of Microsoft® DirectX™.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCHARDWARE
Forces the buffer to use hardware mixing, even if DSBCAPS_STATIC is not specified. If the device does not support hardware mixing or the required hardware memory is not available, the call to initialize will fail. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
Forces the buffer to be stored in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. With this flag set, an application using Microsoft ® DirectSound® can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for non-game applications, such as movie playback (ActiveMovie™), when the user wants to hear the soundtrack while typing in Microsoft® Word or Microsoft® Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.
DSBLOCK_FROMWRITECURSOR
Locks from the current write cursor, making a call to DirectSoundBuffer.getCurrentPosition unnecessary. If this flag is specified, the start parameter is ignored. This flag is optional.
DSBPLAY_LOOPING
Once the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing primary sound buffers.
DSBSTATUS_BUFFERLOST
The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING
The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. Note that if this value is set, the buffer must also be playing.
DSBSTATUS_PLAYING
The buffer is playing. If this value is not set, the buffer is stopped.
DSCAPS_CERTIFIED
This driver has been tested and certified by Microsoft.
DSCAPS_CONTINUOUSRATE
The device supports all sample rates between the DSCaps.minSecondarySampleRate and DSCaps.maxSecondarySampleRate field values. Typically, this means that the actual output rate will be within +/-10Hz of the requested frequency.
DSCAPS_EMULDRIVER
The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT
The device supports primary sound buffers with 16-bit samples.
DSCAPS_PRIMARY8BIT
The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO
The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO
The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT
The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT
The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO
The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO
The device supports hardware-mixed stereo secondary buffers.
DSSCL_EXCLUSIVE
Sets the application to the exclusive level. When it has the input focus, the application will be the only one audible (sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted). With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the DirectSoundBuffer.setFormat method, once the application gains the input focus. (Note that DirectSound will always restore the wave format, no matter what priority level is set.)
DSSCL_NORMAL
Sets the application to a fully cooperative status. Most applications should use this level, because it has the smoothest multitasking and resource-sharing behavior.
DSSCL_PRIORITY
Sets the application to the priority level. Applications with this cooperative level can call the DirectSoundBuffer.setFormat and DirectSound.compact methods.
DSSCL_WRITEPRIMARY
This is the highest priority level. The application has write access to the primary sound buffers. No secondary sound buffers in any application can be played.
DSSPEAKER_HEADPHONE
The speakers are headphones.
DSSPEAKER_MONO
The speakers are monaural.
DSSPEAKER_QUAD
The speakers are quadraphonic.
DSSPEAKER_STEREO
The speakers are stereo (default value).
DSSPEAKER_SURROUND
The speakers are surround sound.
JOY_BUTTON1
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON10
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON11
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON12
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON13
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON14
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON15
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON16
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON17
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON18
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON19
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON2
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON20
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON21
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON22
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON23
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON24
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON25
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON26
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON27
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON28
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON29
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON3
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON30
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON31
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON32
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON4
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON5
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON6
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON7
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON8
Identifier for one of the up to 32 joystick buttons.
JOY_BUTTON9
Identifier for one of the up to 32 joystick buttons.
JOY_CAL_READ3
Reads the x, y, and z axis information, and then stores the raw values in JoyInfo.xPos , JoyInfo.yPos , and JoyInfo.zPos fields.
JOY_CAL_READ4
Reads the rudder, x, y, and z axis information, and then stores the raw values in JoyInfo.rPos , JoyInfo.xPos , JoyInfo.yPos , and JoyInfo.zPos fields.
JOY_CAL_READ5
Reads the rudder, x, y, z, and u axis information, and then stores the raw values in JoyInfo.rPos , JoyInfo.xPos , JoyInfo.yPos , JoyInfo.zPos , and JoyInfo.uPos fields.
JOY_CAL_READ6
Reads the raw v axis data if a joystick minidriver is present to provide the information. Returns 0 otherwise.
JOY_CAL_READALWAYS
Reads the joystick port even if the driver does not detect a device.
JOY_CAL_READRONLY
Reads the rudder (fouth axis) information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.rPos field. Returns 0 otherwise.
JOY_CAL_READUONLY
Reads the u axis (fifth axis) information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.uPos field. Returns 0 otherwise.
JOY_CAL_READVONLY
Reads the v axis (sixth axis) information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.vPos field. Returns 0 otherwise.
JOY_CAL_READXONLY
Reads the x axis information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.xPos field.
JOY_CAL_READXYONLY
Reads the x and y axis information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.xPos and JoyInfo.yPos fields respectively.
JOY_CAL_READYONLY
Reads the y axis information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.yPos field.
JOY_CAL_READZONLY
Reads the z axis information if a joystick minidriver is present to provide the data, and then stores the raw value in the JoyInfo.zPos field.
JOY_POVBACKWARD
Point-Of-View hat is pressed backward. The value 18,000 represents an orientation of 180.00 degrees.
JOY_POVCENTERED
Point-Of-View hat is in the neutral position. The value -1 means the POV hat has no angle to report.
JOY_POVFORWARD
Point-Of_View hat is pressed forward. The value 0 represents an orientation of 0.00 degrees.
JOY_POVLEFT
Point-Of-View hat is pressed to the left. The value 27,000 represents an orientation of 270.00 degrees.
JOY_POVRIGHT
Point-Of-View hat is pressed to the right. The value 9000 represents an orientation of 90.00 degrees.
JOY_RETURNALL
Equivalent to setting all of the JOY_RETURN* values except JOY_RETURNRAWDATA.
JOY_RETURNBUTTONS
The buttons field contains valid state information for each joystick button.
JOY_RETURNCENTERED
Centers the joystick neutral position to the middle value of each movement axis.
JOY_RETURNPOV
The pov field contains valid information about the Point-Of-View control, expressed in discrete units.
JOY_RETURNPOVCTS
The pov field contains valid information about the Point-Of-View control, expressed in continuous, one-hundredth of a degree units.
JOY_RETURNR
The JoyInfo.rPos field contains valid rudder information. This indicates the existance of a fourth axis.
JOY_RETURNRAWDATA
Indicates that uncalibrated joystick readings are stored in this class.
JOY_RETURNU
The JoyInfo.uPos field contains valid data for the fifth axis of the joystick. If this axis is not available, 0 is returned.
JOY_RETURNV
The JoyInfo.vPos field contains valid data for the sixth axis of the joystick. If this axis is not available, 0 is returned.
JOY_RETURNX
The JoyInfo.xPos field contains valid data for the x coordinate of the joystick.
JOY_RETURNY
The JoyInfo.yPos member contains valid data for the y coordinate of the joystick.
JOY_RETURNZ
The JoyInfo.zPos field contains valid data for the z-coordinate of the joystick.
JOY_USEDEADZONE
Expand the range for the neutral position of the joystick. The joystick driver returs a constant value for all positions in the dead zone.
JOYCAPS_HASPOV
The joystick has Point-Of-View information.
JOYCAPS_HASR
The joystick has rudder (fourth axis) information.
JOYCAPS_HASU
The joystick has u-coordinate information.
JOYCAPS_HASV
The joystick has v-coordinate information.
JOYCAPS_HASZ
The joystick has z-coordinate information
JOYCAPS_POV4DIR
The joystick Point-Of-View supports discrete values.
JOYCAPS_POVCTS
The joystick Point-Of-View supports continuous degree bearings.
JOYERR_BASE
JOYERR_NOCANDO
Request was not completed.
JOYERR_NOERROR
There is no error.
JOYERR_PARMS
Bad parameters.
JOYERR_UNPLUGGED
The joystick is unplugged.
JOYSTICKID1
Identifier of the joystick.
JOYSTICKID2
Identifier of the joystick.


Interface Id3dEnumDevicesCallback

public interface Id3dEnumDevicesCallback extends IUnknown
{
  // Methods
  public void callbackd3dEnumDevices(_Guid g, String devDesc,
        String devName, D3dDeviceDesc hwDevDesc,
        D3dDeviceDesc helDevDesc, IUnknown args);
}

Use with enumDevices method to set the callback function to be called for each device.

IUnknown
  |
  +--Id3dEnumDevicesCallback

Methods

callbackd3dEnumDevices

public void callbackd3dEnumDevices(_Guid g, String devDesc, String devName,
        D3dDeviceDesc hwDevDesc, D3dDeviceDesc helDevDesc, IUnknown args);

Enumerates installed Direct3D devices.

Return Value:

No return value.

Parameter | Description
g | A _Guid object that contains a globally unique identifier (GUID).
devDesc | A textual description of the device.
devName | The device name.
hwDeviceDesc | A D3dDeviceDesc object that contains the hardware capabilities of the Direct3D device.
helDeviceDesc | A D3dDeviceDesc object that contains the emulated capabilities of the Direct3D device.
args | Application-defined data passed to this callback function.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface Id3drmCallback

public interface Id3drmCallback extends IUnknown
{
  // Methods
  public void callbackDestroyObject(IUnknown pArgs);
}

Use with Direct3dRMObject.addDestroyCallback and Direct3dRMObject.deleteDestroyCallback to set or remove the callback function to be called when an object is destroyed.

See also Direct3dRMAnimation , Direct3dRMAnimationSet , Direct3dRMDevice , Direct3dRMFace , Direct3dRMFrame , Direct3dRMLight , Direct3dRMMaterial , Direct3dRMMesh , Direct3dRMMeshBuilder , Direct3dRMTexture , Direct3dRMUserVisual , Direct3dRMViewport , Direct3dRMWinDevice , Direct3dRMWrap .

IUnknown
  |
  +--Id3drmCallback

Methods

callbackDestroyObject

public void callbackDestroyObject(IUnknown pArgs);

Enumerates an object that is being destroyed. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
pArgs | Application-defined data passed to this callback function.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface IDeviceUpdateCallback

public interface IDeviceUpdateCallback extends IUnknown
{
  // Methods
  public void callbackDeviceUpdate(Direct3dRMDevice f,
        IUnknown pArgs, int x, D3dRect update);
}

Use with addUpdateCallback and deleteUpdateCallback to set or remove the callback function that is called whenever a device is updated.

Also see com.ms.directX.Direct3dRMDevice

IUnknown
  |
  +--IDeviceUpdateCallback

Methods

callbackDeviceUpdate

public void callbackDeviceUpdate(Direct3dRMDevice f, IUnknown pArgs, int x,
        D3dRect update);

Alerts the application whenever the device changes. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMDevice object that this callback function applies to.
pArgs | The application-defined data passed to this callback function.
x | The number of rectangles specified in the update parameter.
update | A D3dRect object that describes the area to be updated. The coordinates are specified in device units.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface IDirect3d

public interface IDirect3d extends IUnknown
{
  // Methods
  public Direct3dLight createLight();
  public Direct3dMaterial createMaterial();
  public Direct3dViewport createViewport();
  public void enumDevices(Id3dEnumDevicesCallback fn, IUnknown p);
  public void findDevice(D3dFindDeviceSearch ds,
        D3dFindDeviceResult hresult, D3dFindDeviceResult sresult);
  public _Guid findDeviceForColorModel(int cm, int hardware);
  public void initialize(_Guid id);
  public int systemBpp();
}

For a description of methods and parameters, see Direct3d.

IUnknown
  |
  +--IDirect3d

Methods

createLight

public Direct3dLight createLight();

createMaterial

public Direct3dMaterial createMaterial();

createViewport

public Direct3dViewport createViewport();

enumDevices

public void enumDevices(Id3dEnumDevicesCallback fn, IUnknown p);

findDevice

public void findDevice(D3dFindDeviceSearch ds, D3dFindDeviceResult hresult,
        D3dFindDeviceResult sresult);

findDeviceForColorModel

public _Guid findDeviceForColorModel(int cm, int hardware);

initialize

public void initialize(_Guid id);

systemBpp

public int systemBpp();


Interface IDirect3dDevice

public interface IDirect3dDevice extends IUnknown
{
  // Methods
  public void addViewport(Direct3dViewport vport);
  public void beginScene();
  public Direct3dExecuteBuffer createExecuteBuffer(
        D3dExecuteBufferDesc Desc);
  public int createMatrix();
  public void deleteMatrix(int hdl);
  public void deleteViewport(Direct3dViewport vport);
  public void endScene();
  public void enumTextureFormats(IEnumTextureFormatsCallback fn,
        IUnknown args);
  public void execute(Direct3dExecuteBuffer eb,
        Direct3dViewport vp, int flags);
  public void flushExecuteBuffer(D3dExecuteBufferDesc buf,
        int[] buffer);
  public void getCaps(D3dDeviceDesc HWDesc, D3dDeviceDesc HELDesc);
  public Direct3d getDirect3D();
  public void getMatrix(int hdl, D3dMatrix mat);
  public void getPickRecords(int[] flags, D3dPickRecord val);
  public void getStats(D3dStats stat);
  public void initialize(Direct3d dev, _Guid g, D3dDeviceDesc Desc);
  public Direct3dViewport nextViewport(Direct3dViewport vp1,
        int flags);
  public void pick(Direct3dExecuteBuffer eb,
        Direct3dViewport vport, int flags, D3dRect Rect);
  public void setMatrix(int hdl, D3dMatrix mat);
  public void swapTextureHandles(Direct3dTexture tex1,
        Direct3dTexture tex2);
}

For a description of methods and parameters, see Direct3dDevice

IUnknown
  |
  +--IDirect3dDevice

Methods

addViewport

public void addViewport(Direct3dViewport vport);

beginScene

public void beginScene();

createExecuteBuffer

public Direct3dExecuteBuffer createExecuteBuffer(D3dExecuteBufferDesc Desc);

createMatrix

public int createMatrix();

deleteMatrix

public void deleteMatrix(int hdl);

deleteViewport

public void deleteViewport(Direct3dViewport vport);

endScene

public void endScene();

enumTextureFormats

public void enumTextureFormats(IEnumTextureFormatsCallback fn,
        IUnknown args);

execute

public void execute(Direct3dExecuteBuffer eb, Direct3dViewport vp,
        int flags);

flushExecuteBuffer

public void flushExecuteBuffer(D3dExecuteBufferDesc buf, int[] buffer);

getCaps

public void getCaps(D3dDeviceDesc HWDesc, D3dDeviceDesc HELDesc);

getDirect3D

public Direct3d getDirect3D();

getMatrix

public void getMatrix(int hdl, D3dMatrix mat);

getPickRecords

public void getPickRecords(int[] flags, D3dPickRecord val);

getStats

public void getStats(D3dStats stat);

initialize

public void initialize(Direct3d dev, _Guid g, D3dDeviceDesc Desc);

nextViewport

public Direct3dViewport nextViewport(Direct3dViewport vp1, int flags);

pick

public void pick(Direct3dExecuteBuffer eb, Direct3dViewport vport,
        int flags, D3dRect Rect);

setMatrix

public void setMatrix(int hdl, D3dMatrix mat);

swapTextureHandles

public void swapTextureHandles(Direct3dTexture tex1, Direct3dTexture tex2);


Interface IDirect3dExecuteBuffer

public interface IDirect3dExecuteBuffer extends IUnknown
{
  // Methods
  public int addLVertexData(D3dLVertex vertex, int bufferindex);
  public int addTLVertexData(D3dTLVertex vertex, int bufferindex);
  public int addVertexData(D3dVertex vertex, int bufferindex);
  public int exit(int bufferindex);
  public void getExecuteData(D3dExecuteData data);
  public void lock(D3dExecuteBufferDesc Desc);
  public int processVertices(int cnt, int bufferindex);
  public int processVerticesData(int flags, int start, int dest,
        int cnt, int bufferindex);
  public void setExecuteData(D3dExecuteData data);
  public int setStatus(int flags, int status, int x1, int y1,
        int x2, int y2, int bufferindex);
  public int stateLight(int cnt, int bufferindex);
  public int stateLightData(int flags, float Arg, int bufferindex);
  public int stateRender(int cnt, int bufferindex);
  public int stateRenderData(int flags, int Arg, int bufferindex);
  public int stateTransForm(int cnt, int bufferindex);
  public int stateTransFormData(int flags, int Arg,
        int bufferindex);
  public int triangleList(int cnt, int bufferindex);
  public int triangleListData(D3dTriangle triangle,
        int bufferindex);
  public void unlock();
}

For a description of methods and parameters, see Direct3dExecuteBuffer.

IUnknown
  |
  +--IDirect3dExecuteBuffer

Methods

addLVertexData

public int addLVertexData(D3dLVertex vertex, int bufferindex);

addTLVertexData

public int addTLVertexData(D3dTLVertex vertex, int bufferindex);

addVertexData

public int addVertexData(D3dVertex vertex, int bufferindex);

exit

public int exit(int bufferindex);

getExecuteData

public void getExecuteData(D3dExecuteData data);

lock

public void lock(D3dExecuteBufferDesc Desc);

processVertices

public int processVertices(int cnt, int bufferindex);

processVerticesData

public int processVerticesData(int flags, int start, int dest, int cnt, int
        bufferindex);

setExecuteData

public void setExecuteData(D3dExecuteData data);

setStatus

public int setStatus(int flags, int status, int x1, int y1, int x2, int y2,
        int bufferindex);

stateLight

public int stateLight(int cnt, int bufferindex);

stateLightData

public int stateLightData(int flags, float Arg, int bufferindex);

stateRender

public int stateRender(int cnt, int bufferindex);

stateRenderData

public int stateRenderData(int flags, int Arg, int bufferindex);

stateTransForm

public int stateTransForm(int cnt, int bufferindex);

stateTransFormData

public int stateTransFormData(int flags, int Arg, int bufferindex);

triangleList

public int triangleList(int cnt, int bufferindex);

triangleListData

public int triangleListData(D3dTriangle triangle, int bufferindex);

unlock

public void unlock();


Interface IDirect3dLight

public interface IDirect3dLight extends IUnknown
{
  // Methods
  public void getLight(D3dLightDesc light);
  public void setLight(D3dLightDesc light);
}

For a description of methods and parameters, see Direct3dLight

IUnknown
  |
  +--IDirect3dLight

Methods

getLight

public void getLight(D3dLightDesc light);

setLight

public void setLight(D3dLightDesc light);


Interface IDirect3dMaterial

public interface IDirect3dMaterial extends IUnknown
{
  // Methods
  public int getHandle(Direct3dDevice dev);
  public void getMaterial(D3dMaterialDesc mat);
  public void reserve();
  public void setMaterial(D3dMaterialDesc mat);
  public void unreserve();
}

For a description of methods and parameters, see Direct3dMaterial.

IUnknown
  |
  +--IDirect3dMaterial

Methods

getHandle

public int getHandle(Direct3dDevice dev);

getMaterial

public void getMaterial(D3dMaterialDesc mat);

reserve

public void reserve();

setMaterial

public void setMaterial(D3dMaterialDesc mat);

unreserve

public void unreserve();


Interface IDirect3dRM

public interface IDirect3dRM extends IUnknown
{
  // Methods
  public void addSearchPath(String name);
  public Direct3dRMAnimation createAnimation();
  public Direct3dRMAnimationSet createAnimationSet();
  public int createColorRGB(float red, float green, float blue);
  public Direct3dRMDevice createDevice(int v1, int v2);
  public Direct3dRMDevice createDeviceFromClipper(DirectDrawClipper
        lpDDClipper, _Guid g, int width, int height);
  public Direct3dRMDevice createDeviceFromD3D(Direct3d d3d,
        Direct3dDevice dev);
  public Direct3dRMDevice createDeviceFromSurface(_Guid g,
        DirectDraw dd, DirectDrawSurface DDsBack);
  public Direct3dRMFace createFace();
  public Direct3dRMFrame createFrame(Direct3dRMFrame parent);
  public Direct3dRMLight createLight(int t, int c);
  public Direct3dRMLight createLightRGB(int lt, float vred,
        float vgreen, float vblue);
  public Direct3dRMMaterial createMaterial(float d);
  public Direct3dRMMesh createMesh();
  public Direct3dRMMeshBuilder createMeshBuilder();
  public Direct3dRM createObject(_Guid rclsid, IUnknown p,
        _Guid rid);
  public Direct3dRMVisual createShadow(Direct3dRMVisual v,
        Direct3dRMLight l, float px, float py, float pz,
        float nx, float ny, float nz);
  public Direct3dRMTexture createTexture(D3dRMImage image,
        byte[] buffer1, byte[] pal);
  public Direct3dRMTexture createTextureFromSurface(
        DirectDrawSurface ddS);
  public Direct3dRMUserVisual createUserVisual(
        IUserVisualCallback fn, IUnknown Arg);
  public Direct3dRMViewport createViewport(Direct3dRMDevice dev,
        Direct3dRMFrame fr, int l, int t, int w, int h);
  public Direct3dRMWrap createWrap(int t, Direct3dRMFrame f,
        float ox, float oy, float oz, float dx, float dy,
        float dz, float ux, float uy, float uz, float ou,
        float ov, float su, float sv);
  public void enumerateObjects(IEnumerateObjectsCallback fn,
        IUnknown pArgs);
  public Direct3dRMDeviceArray getDevices();
  public Direct3dRMObject getNamedObject(String name);
  public String getSearchPath();
  public void loadFromFileByPos(String fnam, int[] id, _Guid g, int
        cnt, int options, ILoadCallback fn1, int[] arg1,
        ILoadTextureCallback fn2, int[] arg2, Direct3dRMFrame f);
  public Direct3dRMTexture loadTexture(String name);
  public Direct3dRMTexture loadTextureFromResource(int hnd);
  public void setDefaultTextureColors(int ds);
  public void setDefaultTextureShades(int ds);
  public void setSearchPath(String name);
  public void tick(float val);
  public void vectorCrossProduct(D3dVector lpd, D3dVector lps1,
        D3dVector lps2);
  public void vectorNormalise(D3dVector d);
}

For a description of methods and parameters, see Direct3dRM.

IUnknown
  |
  +--IDirect3dRM

Methods

addSearchPath

public void addSearchPath(String name);

createAnimation

public Direct3dRMAnimation createAnimation();

createAnimationSet

public Direct3dRMAnimationSet createAnimationSet();

createColorRGB

public int createColorRGB(float red, float green, float blue);

createDevice

public Direct3dRMDevice createDevice(int v1, int v2);

createDeviceFromClipper

public Direct3dRMDevice createDeviceFromClipper(
        DirectDrawClipper lpDDClipper, _Guid g, int width, int height);

createDeviceFromD3D

public Direct3dRMDevice createDeviceFromD3D(Direct3d d3d,
        Direct3dDevice dev);

createDeviceFromSurface

public Direct3dRMDevice createDeviceFromSurface(_Guid g, DirectDraw dd,
        DirectDrawSurface DDsBack);

createFace

public Direct3dRMFace createFace();

createFrame

public Direct3dRMFrame createFrame(Direct3dRMFrame parent);

createLight

public Direct3dRMLight createLight(int t, int c);

createLightRGB

public Direct3dRMLight createLightRGB(int lt, float vred, float vgreen,
        float vblue);

createMaterial

public Direct3dRMMaterial createMaterial(float d);

createMesh

public Direct3dRMMesh createMesh();

createMeshBuilder

public Direct3dRMMeshBuilder createMeshBuilder();

createObject

public Direct3dRM createObject(_Guid rclsid, IUnknown p, _Guid rid);

createShadow

public Direct3dRMVisual createShadow(Direct3dRMVisual v, Direct3dRMLight l,
        float px, float py, float pz, float nx, float ny, float nz);

createTexture

public Direct3dRMTexture createTexture(D3dRMImage image, byte[] buffer1,
        byte[] pal);

createTextureFromSurface

public Direct3dRMTexture createTextureFromSurface(DirectDrawSurface ddS);

createUserVisual

public Direct3dRMUserVisual createUserVisual(IUserVisualCallback fn,
        IUnknown Arg);

createViewport

public Direct3dRMViewport createViewport(Direct3dRMDevice dev,
        Direct3dRMFrame fr, int l, int t, int w, int h);

createWrap

public Direct3dRMWrap createWrap(int t, Direct3dRMFrame f, float ox,
        float oy, float oz, float dx, float dy, float dz, float ux,
        float uy, float uz, float ou, float ov, float su, float sv);

enumerateObjects

public void enumerateObjects(IEnumerateObjectsCallback fn, IUnknown pArgs);

getDevices

public Direct3dRMDeviceArray getDevices();

getNamedObject

public Direct3dRMObject getNamedObject(String name);

getSearchPath

public String getSearchPath();

loadFromFileByPos

public void loadFromFileByPos(String fnam, int[] id, _Guid g, int cnt,
        int options, ILoadCallback fn1, int[] arg1,
        ILoadTextureCallback fn2, int[] arg2, Direct3dRMFrame f);

loadTexture

public Direct3dRMTexture loadTexture(String name);

loadTextureFromResource

public Direct3dRMTexture loadTextureFromResource(int hnd);

setDefaultTextureColors

public void setDefaultTextureColors(int ds);

setDefaultTextureShades

public void setDefaultTextureShades(int ds);

setSearchPath

public void setSearchPath(String name);

tick

public void tick(float val);

vectorCrossProduct

public void vectorCrossProduct(D3dVector lpd, D3dVector lps1,
        D3dVector lps2);

vectorNormalise

public void vectorNormalise(D3dVector d);


Interface IDirect3dRMAnimation

public interface IDirect3dRMAnimation extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addPositionKey(float time, float x, float y, float z)
        public void addScaleKey(float time, float x, float y,
        float z);
  public void addRotateKey(float time, D3dRMQuaternion q);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public void deleteKey(float time);
  public Direct3dRMAnimation duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public int getOptions();
  public void setAppData(int data);
  public void setFrame(Direct3dRMFrame frame);
  public void setName(String name);
  public void setOptions(int flags);
  public void setTime(float time);
}

For a description of methods and parameters, see Direct3dRMAnimation.

IUnknown
  |
  +--IDirect3dRMAnimation

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addPositionKey

public void addPositionKey(float time, float x, float y,
        float z) public void addScaleKey(float time, float x, float y,
        float z);

addRotateKey

public void addRotateKey(float time, D3dRMQuaternion q);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

deleteKey

public void deleteKey(float time);

duplicate

public Direct3dRMAnimation duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

getOptions

public int getOptions();

setAppData

public void setAppData(int data);

setFrame

public void setFrame(Direct3dRMFrame frame);

setName

public void setName(String name);

setOptions

public void setOptions(int flags);

setTime

public void setTime(float time);


Interface IDirect3dRMAnimationSet

public interface IDirect3dRMAnimationSet extends IUnknown
{
  // Methods
  public void addAnimation(Direct3dRMAnimation aid);
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteAnimation(Direct3dRMAnimation aid);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMAnimationSet duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser,
        Direct3dRMFrame f);
  public void setAppData(int data);
  public void setName(String name);
  public void setTime(float time);
}

For a description of methods and parameters, see Direct3dRMAnimationSet.

IUnknown
  |
  +--IDirect3dRMAnimationSet

Methods

addAnimation

public void addAnimation(Direct3dRMAnimation aid);

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteAnimation

public void deleteAnimation(Direct3dRMAnimation aid);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMAnimationSet duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser, Direct3dRMFrame f);

setAppData

public void setAppData(int data);

setName

public void setName(String name);

setTime

public void setTime(float time);


Interface IDirect3dRMArray

public interface IDirect3dRMArray extends IUnknown
{
  // Methods
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMArray.

IUnknown
  |
  +--IDirect3dRMArray

Methods

getSize

public int getSize();


Interface IDirect3dRMDevice

public interface IDirect3dRMDevice extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addUpdateCallback(IDeviceUpdateCallback fn,
        IUnknown args);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public void deleteUpdateCallback(IDeviceUpdateCallback fn,
        IUnknown args);
  public Direct3dRMDevice duplicate();
  public int getAppData();
  public int getBufferCount();
  public String getClassName();
  public int getColorModel();
  public Direct3dRMWinDevice getd3drmWinDevice();
  public Direct3dDevice getDirect3DDevice();
  public int getDither();
  public int getHeight();
  public String getName();
  public int getQuality();
  public int getShades();
  public int getTextureQuality();
  public int getTrianglesDrawn();
  public Direct3dRMViewportArray getViewports();
  public int getWidth();
  public int getWireframeOptions();
  public void init(int width, int height);
  public void initFromClipper(DirectDrawClipper DDclipper, _Guid g,
        int width, int height);
  public void initFromD3D(Direct3d d3d, Direct3dDevice dev);
  public void setAppData(int data);
  public void setBufferCount(int count);
  public void setDither(int dith);
  public void setName(String name);
  public void setQuality(int q);
  public void setShades(int s);
  public void setTextureQuality(int d);
  public void update();
}

For a description of methods and parameters, see Direct3dRMDevice.

IUnknown
  |
  +--IDirect3dRMDevice

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addUpdateCallback

public void addUpdateCallback(IDeviceUpdateCallback fn, IUnknown args);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

deleteUpdateCallback

public void deleteUpdateCallback(IDeviceUpdateCallback fn, IUnknown args);

duplicate

public Direct3dRMDevice duplicate();

getAppData

public int getAppData();

getBufferCount

public int getBufferCount();

getClassName

public String getClassName();

getColorModel

public int getColorModel();

getd3drmWinDevice

public Direct3dRMWinDevice getd3drmWinDevice();

getDirect3DDevice

public Direct3dDevice getDirect3DDevice();

getDither

public int getDither();

getHeight

public int getHeight();

getName

public String getName();

getQuality

public int getQuality();

getShades

public int getShades();

getTextureQuality

public int getTextureQuality();

getTrianglesDrawn

public int getTrianglesDrawn();

getViewports

public Direct3dRMViewportArray getViewports();

getWidth

public int getWidth();

getWireframeOptions

public int getWireframeOptions();

init

public void init(int width, int height);

initFromClipper

public void initFromClipper(DirectDrawClipper DDclipper, _Guid g,
        int width, int height);

initFromD3D

public void initFromD3D(Direct3d d3d, Direct3dDevice dev);

setAppData

public void setAppData(int data);

setBufferCount

public void setBufferCount(int count);

setDither

public void setDither(int dith);

setName

public void setName(String name);

setQuality

public void setQuality(int q);

setShades

public void setShades(int s);

setTextureQuality

public void setTextureQuality(int d);

update

public void update();


Interface IDirect3dRMDeviceArray

public interface IDirect3dRMDeviceArray extends IUnknown
{
  // Methods
  public Direct3dRMDevice getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMDeviceArray.

IUnknown
  |
  +--IDirect3dRMDeviceArray

Methods

getElement

public Direct3dRMDevice getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMFace

public interface IDirect3dRMFace extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addVertex(float x, float y, float z);
  public void addVertexAndNormalIndexed(int vertex, int normal);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMFace duplicate();
  public int getAppData();
  public String getClassName();
  public int getColor();
  public Direct3dRMMaterial getMaterial();
  public String getName();
  public void getNormal(D3dVector val);
  public Direct3dRMTexture getTexture();
  public int getTextureCoordinateIndex(int which);
  public void getTextureCoordinates(int vertex, float[] u,
        float[] v);
  public void getTextureTopology(int[] u, int[] v);
  public void getVertex(int idx, D3dVector vert, D3dVector norm);
  public int getVertexCount();
  public int getVertexIndex(int which);
  public void getVertices(int[] vertex_cnt, D3dVector coord,
        D3dVector normals);
  public void getVerticesSize(int[] v_cnt);
  public void setAppData(int data);
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setMaterial(Direct3dRMMaterial ref);
  public void setName(String name);
  public void setTexture(Direct3dRMTexture ref);
  public void setTextureCoordinates(int vertex, float u, float v);
  public void setTextureTopology(int wrap_u, int wrap_v);
}

For a description of methods and parameters, see Direct3dRMFace.

IUnknown
  |
  +--IDirect3dRMFace

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addVertex

public void addVertex(float x, float y, float z);

addVertexAndNormalIndexed

public void addVertexAndNormalIndexed(int vertex, int normal);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMFace duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getColor

public int getColor();

getMaterial

public Direct3dRMMaterial getMaterial();

getName

public String getName();

getNormal

public void getNormal(D3dVector val);

getTexture

public Direct3dRMTexture getTexture();

getTextureCoordinateIndex

public int getTextureCoordinateIndex(int which);

getTextureCoordinates

public void getTextureCoordinates(int vertex, float[] u, float[] v);

getTextureTopology

public void getTextureTopology(int[] u, int[] v);

getVertex

public void getVertex(int idx, D3dVector vert, D3dVector norm);

getVertexCount

public int getVertexCount();

getVertexIndex

public int getVertexIndex(int which);

getVertices

public void getVertices(int[] vertex_cnt, D3dVector coord,
        D3dVector normals);

getVerticesSize

public void getVerticesSize(int[] v_cnt);

setAppData

public void setAppData(int data);

setColor

public void setColor(int c);

setColorRGB

public void setColorRGB(float r, float g, float b);

setMaterial

public void setMaterial(Direct3dRMMaterial ref);

setName

public void setName(String name);

setTexture

public void setTexture(Direct3dRMTexture ref);

setTextureCoordinates

public void setTextureCoordinates(int vertex, float u, float v);

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);


Interface IDirect3dRMFaceArray

public interface IDirect3dRMFaceArray extends IUnknown
{
  // Methods
  public Direct3dRMFace getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMFaceArray.

IUnknown
  |
  +--IDirect3dRMFaceArray

Methods

getElement

public Direct3dRMFace getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMFrame

public interface IDirect3dRMFrame extends IUnknown
{
  // Methods
  public void addChild(Direct3dRMFrame child);
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addLight(Direct3dRMLight val);
  public void addMoveCallback(IFrameMoveCallback fmC,
        IUnknown args);
  public void addRotation(int typ, float x, float y, float z, float
        theta);
  public void addScale(int typ, float sx, float sy, float sz);
  public void addTransform(int t, float[] val);
  public void addTranslation(int t, float x, float y, float z);
  public void addVisual(Direct3dRMVisual v);
  public void addVisualFrame(Direct3dRMFrame v);
  public void addVisualMesh(Direct3dRMMesh v);
  public void addVisualMeshBuilder(Direct3dRMMeshBuilder v);
  public void addVisualShadow(Direct3dRMShadow v);
  public void addVisualTexture(Direct3dRMTexture v);
  public void addVisualUserVisual(Direct3dRMUserVisual v);
  public void deleteChild(Direct3dRMFrame c);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public void deleteLight(Direct3dRMLight l);
  public void deleteMoveCallback(IFrameMoveCallback fn,
        IUnknown args);
  public void deleteVisual(Direct3dRMVisual v);
  public void deleteVisualFrame(Direct3dRMFrame v);
  public void deleteVisualMesh(Direct3dRMMesh v);
  public void deleteVisualMeshBuilder(Direct3dRMMeshBuilder v);
  public void deleteVisualShadow(Direct3dRMShadow v);
  public void deleteVisualTexture(Direct3dRMTexture v);
  public void deleteVisualUserVisual(Direct3dRMUserVisual v);
  public Direct3dRMFrame duplicate();
  public int getAppData();
  public Direct3dRMFrameArray getChildren();
  public String getClassName();
  public int getColor();
  public Direct3dRMLightArray getLights();
  public int getMaterialMode();
  public String getName();
  public void getOrientation(Direct3dRMFrame ref, D3dVector dir,
        D3dVector up);
  public Direct3dRMFrame getParent();
  public void getPosition(Direct3dRMFrame ref, D3dVector position);
  public void getRotation(Direct3dRMFrame ref, D3dVector axis,
        float[] theta);
  public Direct3dRMFrame getScene();
  public int getSceneBackground();
  public DirectDrawSurface getSceneBackgroundDepth();
  public int getSceneFogColor();
  public int getSceneFogEnable();
  public int getSceneFogMode();
  public void getSceneFogParams(float[] start, float[] end, float[]
        density);
  public int getSortMode();
  public Direct3dRMTexture getTexture();
  public void getTextureTopology(int[] u, int[] v);
  public void getTransform(float[] val);
  public void getVelocity(Direct3dRMFrame ref, D3dVector vel,
        int rotation);
  public Direct3dRMVisualArray getVisuals();
  public int getZbufferMode();
  public void inverseTransform(D3dVector d, D3dVector s);
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser);
  public void lookAt(Direct3dRMFrame tgt, Direct3dRMFrame ref,
        int val);
  public void move(float delta);
  public void setAppData(int data);
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setMaterialMode(int val);
  public void setName(String name);
  public void setOrientation(Direct3dRMFrame reference, float dx,
        float dy, float dz, float ux, float uy, float uz);
  public void setPosition(Direct3dRMFrame reference, float x, float
        y, float z);
  public void setRotation(Direct3dRMFrame reference, float x, float
        y, float z, float theta);
  public void setSceneBackground(int c);
  public void setSceneBackgroundDepth(DirectDrawSurface s);
  public void setSceneBackgroundImage(Direct3dRMTexture i);
  public void setSceneBackgroundRGB(float r, float g, float b);
  public void setSceneFogColor(int c);
  public void setSceneFogEnable(int enable);
  public void setSceneFogMode(int c);
  public void setSceneFogParams(float s, float e, float d);
  public void setSortMode(int val);
  public void setTexture(Direct3dRMTexture t);
  public void setTextureTopology(int wrap_u, int wrap_v);
  public void setVelocity(Direct3dRMFrame reference, float x, float
        y, float z, int with_rotation);
  public void setZbufferMode(int val);
  public void transform(D3dVector d, D3dVector s);
}

For a description of methods and parameters, see Direct3dRMFrame

IUnknown
  |
  +--IDirect3dRMFrame

Methods

addChild

public void addChild(Direct3dRMFrame child);

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addLight

public void addLight(Direct3dRMLight val);

addMoveCallback

public void addMoveCallback(IFrameMoveCallback fmC, IUnknown args);

addRotation

public void addRotation(int typ, float x, float y, float z, float theta);

addScale

public void addScale(int typ, float sx, float sy, float sz);

addTransform

public void addTransform(int t, float[] val);

addTranslation

public void addTranslation(int t, float x, float y, float z);

addVisual

public void addVisual(Direct3dRMVisual v);

addVisualFrame

public void addVisualFrame(Direct3dRMFrame v);

addVisualMesh

public void addVisualMesh(Direct3dRMMesh v);

addVisualMeshBuilder

public void addVisualMeshBuilder(Direct3dRMMeshBuilder v);

addVisualShadow

public void addVisualShadow(Direct3dRMShadow v);

addVisualTexture

public void addVisualTexture(Direct3dRMTexture v);

addVisualUserVisual

public void addVisualUserVisual(Direct3dRMUserVisual v);

deleteChild

public void deleteChild(Direct3dRMFrame c);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

deleteLight

public void deleteLight(Direct3dRMLight l);

deleteMoveCallback

public void deleteMoveCallback(IFrameMoveCallback fn, IUnknown args);

deleteVisual

public void deleteVisual(Direct3dRMVisual v);

deleteVisualFrame

public void deleteVisualFrame(Direct3dRMFrame v);

deleteVisualMesh

public void deleteVisualMesh(Direct3dRMMesh v);

deleteVisualMeshBuilder

public void deleteVisualMeshBuilder(Direct3dRMMeshBuilder v);

deleteVisualShadow

public void deleteVisualShadow(Direct3dRMShadow v);

deleteVisualTexture

public void deleteVisualTexture(Direct3dRMTexture v);

deleteVisualUserVisual

public void deleteVisualUserVisual(Direct3dRMUserVisual v);

duplicate

public Direct3dRMFrame duplicate();

getAppData

public int getAppData();

getChildren

public Direct3dRMFrameArray getChildren();

getClassName

public String getClassName();

getColor

public int getColor();

getLights

public Direct3dRMLightArray getLights();

getMaterialMode

public int getMaterialMode();

getName

public String getName();

getOrientation

public void getOrientation(Direct3dRMFrame ref, D3dVector dir,
        D3dVector up);

getParent

public Direct3dRMFrame getParent();

getPosition

public void getPosition(Direct3dRMFrame ref, D3dVector position);

getRotation

public void getRotation(Direct3dRMFrame ref, D3dVector axis, float[] theta);

getScene

public Direct3dRMFrame getScene();

getSceneBackground

public int getSceneBackground();

getSceneBackgroundDepth

public DirectDrawSurface getSceneBackgroundDepth();

getSceneFogColor

public int getSceneFogColor();

getSceneFogEnable

public int getSceneFogEnable();

getSceneFogMode

public int getSceneFogMode();

getSceneFogParams

public void getSceneFogParams(float[] start, float[] end, float[] density);

getSortMode

public int getSortMode();

getTexture

public Direct3dRMTexture getTexture();

getTextureTopology

public void getTextureTopology(int[] u, int[] v);

getTransform

public void getTransform(float[] val);

getVelocity

public void getVelocity(Direct3dRMFrame ref, D3dVector vel, int rotation);

getVisuals

public Direct3dRMVisualArray getVisuals();

getZbufferMode

public int getZbufferMode();

inverseTransform

public void inverseTransform(D3dVector d, D3dVector s);

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser);

lookAt

public void lookAt(Direct3dRMFrame tgt, Direct3dRMFrame ref, int val);

move

public void move(float delta);

setAppData

public void setAppData(int data);

setColor

public void setColor(int c);

setColorRGB

public void setColorRGB(float r, float g, float b);

setMaterialMode

public void setMaterialMode(int val);

setName

public void setName(String name);

setOrientation

public void setOrientation(Direct3dRMFrame reference, float dx, float dy,
        float dz, float ux, float uy, float uz);

setPosition

public void setPosition(Direct3dRMFrame reference, float x, float y,
        float z);

setRotation

public void setRotation(Direct3dRMFrame reference, float x, float y,
        float z, float theta);

setSceneBackground

public void setSceneBackground(int c);

setSceneBackgroundDepth

public void setSceneBackgroundDepth(DirectDrawSurface s);

setSceneBackgroundImage

public void setSceneBackgroundImage(Direct3dRMTexture i);

setSceneBackgroundRGB

public void setSceneBackgroundRGB(float r, float g, float b);

setSceneFogColor

public void setSceneFogColor(int c);

setSceneFogEnable

public void setSceneFogEnable(int enable);

setSceneFogMode

public void setSceneFogMode(int c);

setSceneFogParams

public void setSceneFogParams(float s, float e, float d);

setSortMode

public void setSortMode(int val);

setTexture

public void setTexture(Direct3dRMTexture t);

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);

setVelocity

public void setVelocity(Direct3dRMFrame reference, float x, float y,
        float z, int with_rotation);

setZbufferMode

public void setZbufferMode(int val);

transform

public void transform(D3dVector d, D3dVector s);


Interface IDirect3dRMFrameArray

public interface IDirect3dRMFrameArray extends IUnknown
{
  // Methods
  public Direct3dRMFrame getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMFrameArray.

IUnknown
  |
  +--IDirect3dRMFrameArray

Methods

getElement

public Direct3dRMFrame getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMLight

public interface IDirect3dRMLight extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMLight duplicate();
  public int getAppData();
  public String getClassName();
  public int getColor();
  public float getConstantAttenuation();
  public Direct3dRMFrame getEnableFrame();
  public float getLinearAttenuation();
  public String getName();
  public float getPenumbra();
  public float getQuadraticAttenuation();
  public float getRange();
  public int getType();
  public float getUmbra();
  public void setAppData(int data);
  public void setColor(int c);
  public void setColorRGB(float r, float g, float b);
  public void setConstantAttenuation(float atn);
  public void setEnableFrame(Direct3dRMFrame f);
  public void setLinearAttenuation(float atn);
  public void setName(String name);
  public void setPenumbra(float p);
  public void setQuadraticAttenuation(float atn);
  public void setRange(float rng);
  public void setType(int t);
  public void setUmbra(float u);
}

For a description of methods and parameters, see Direct3dRMLight.

IUnknown
  |
  +--IDirect3dRMLight

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMLight duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getColor

public int getColor();

getConstantAttenuation

public float getConstantAttenuation();

getEnableFrame

public Direct3dRMFrame getEnableFrame();

getLinearAttenuation

public float getLinearAttenuation();

getName

public String getName();

getPenumbra

public float getPenumbra();

getQuadraticAttenuation

public float getQuadraticAttenuation();

getRange

public float getRange();

getType

public int getType();

getUmbra

public float getUmbra();

setAppData

public void setAppData(int data);

setColor

public void setColor(int c);

setColorRGB

public void setColorRGB(float r, float g, float b);

setConstantAttenuation

public void setConstantAttenuation(float atn);

setEnableFrame

public void setEnableFrame(Direct3dRMFrame f);

setLinearAttenuation

public void setLinearAttenuation(float atn);

setName

public void setName(String name);

setPenumbra

public void setPenumbra(float p);

setQuadraticAttenuation

public void setQuadraticAttenuation(float atn);

setRange

public void setRange(float rng);

setType

public void setType(int t);

setUmbra

public void setUmbra(float u);


Interface IDirect3dRMLightArray

public interface IDirect3dRMLightArray extends IUnknown
{
  // Methods
  public Direct3dRMLight getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMLightArray.

IUnknown
  |
  +--IDirect3dRMLightArray

Methods

getElement

public Direct3dRMLight getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMMaterial

public interface IDirect3dRMMaterial extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMMaterial duplicate();
  public int getAppData();
  public String getClassName();
  public void getEmissive(float[] r, float[] g, float[] b);
  public String getName();
  public float getPower();
  public void getSpecular(float[] r, float[] g, float[] b);
  public void setAppData(int data);
  public void setEmissive(float r, float g, float b);
  public void setName(String name);
  public void setPower(float power);
  public void setSpecular(float r, float g, float b);
}

For a description of methods and parameters, see Direct3dRMMaterial.

IUnknown
  |
  +--IDirect3dRMMaterial

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMMaterial duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getEmissive

public void getEmissive(float[] r, float[] g, float[] b);

getName

public String getName();

getPower

public float getPower();

getSpecular

public void getSpecular(float[] r, float[] g, float[] b);

setAppData

public void setAppData(int data);

setEmissive

public void setEmissive(float r, float g, float b);

setName

public void setName(String name);

setPower

public void setPower(float power);

setSpecular

public void setSpecular(float r, float g, float b);


Interface IDirect3dRMMesh

public interface IDirect3dRMMesh extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addGroup(int vcnt, int fcnt, int vPerFace,
        int[] fdata, int[] retId);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMMesh duplicate();
  public int getAppData();
  public void getBox(D3dRMBox vector);
  public String getClassName();
  public void getGroup(int id, int[] vcnt, int[] fcnt,
        int[] vPerFace, int[] fDataSize, int[] fdata);
  public int getGroupColor(int id);
  public int getGroupCount();
  public int getGroupMapping(int id);
  public Direct3dRMMaterial getGroupMaterial(int id);
  public int getGroupQuality(int id);
  public void getGroupSize(int id, int[] val);
  public Direct3dRMTexture getGroupTexture(int id);
  public String getName();
  public void getVertices(int id, int idx, int vCount,
        D3dRMVertex[] v);
  public void getVerticesSize(int id, int idx, int[] cnt);
  public void scale(float sx, float sy, float sz);
  public void setAppData(int data);
  public void setGroupColor(int id, int val);
  public void setGroupColorRGB(int id, float r, float g, float b);
  public void setGroupMapping(int id, int value);
  public void setGroupMaterial(int id, Direct3dRMMaterial val);
  public void setGroupQuality(int id, int value);
  public void setGroupTexture(int id, Direct3dRMTexture val);
  public void setName(String name);
  public void setVertices(int id, int idx, int vCount,
        D3dRMVertex[] v);
  public void setVerticesAsFloats(int id, int idx, int vCount,
        float[] v);
  public void translate(float tx, float ty, float tz);
}

For a description of methods and parameters, see Direct3dRMMesh.

IUnknown
  |
  +--IDirect3dRMMesh

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addGroup

public void addGroup(int vcnt, int fcnt, int vPerFace, int[] fdata,
        int[] retId);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMMesh duplicate();

getAppData

public int getAppData();

getBox

public void getBox(D3dRMBox vector);

getClassName

public String getClassName();

getGroup

public void getGroup(int id, int[] vcnt, int[] fcnt, int[] vPerFace,
        int[] fDataSize, int[] fdata);

getGroupColor

public int getGroupColor(int id);

getGroupCount

public int getGroupCount();

getGroupMapping

public int getGroupMapping(int id);

getGroupMaterial

public Direct3dRMMaterial getGroupMaterial(int id);

getGroupQuality

public int getGroupQuality(int id);

getGroupSize

public void getGroupSize(int id, int[] val);

getGroupTexture

public Direct3dRMTexture getGroupTexture(int id);

getName

public String getName();

getVertices

public void getVertices(int id, int idx, int vCount, D3dRMVertex[] v);

getVerticesSize

public void getVerticesSize(int id, int idx, int[] cnt);

scale

public void scale(float sx, float sy, float sz);

setAppData

public void setAppData(int data);

setGroupColor

public void setGroupColor(int id, int val);

setGroupColorRGB

public void setGroupColorRGB(int id, float r, float g, float b);

setGroupMapping

public void setGroupMapping(int id, int value);

setGroupMaterial

public void setGroupMaterial(int id, Direct3dRMMaterial val);

setGroupQuality

public void setGroupQuality(int id, int value);

setGroupTexture

public void setGroupTexture(int id, Direct3dRMTexture val);

setName

public void setName(String name);

setVertices

public void setVertices(int id, int idx, int vCount, D3dRMVertex[] v);

setVerticesAsFloats

public void setVerticesAsFloats(int id, int idx, int vCount, float[] v);

translate

public void translate(float tx, float ty, float tz);


Interface IDirect3dRMMeshBuilder

public interface IDirect3dRMMeshBuilder extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void addFace(Direct3dRMFace f);
  public void addFaces(int vCount, float[] ver, int nCount, float[]
        norm, int[] data);
  public void addFrame(Direct3dRMFrame f);
  public void addMesh(Direct3dRMMesh m);
  public void addMeshBuilder(Direct3dRMMeshBuilder mb);
  public void addNormal(float x, float y, float z);
  public void addVertex(float x, float y, float z);
  public Direct3dRMFace createFace();
  public Direct3dRMFaceArray createFaceArray(int vCount,
        float[] vertices, int nCount, float[] normals,
        int[] data);
  public Direct3dRMMesh createMesh();
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMMeshBuilder duplicate();
  public void generateNormals();
  public int getAppData();
  public void getBox(D3dRMBox retv);
  public String getClassName();
  public int getColorSource();
  public Direct3dRMMeshBuilder getd3drmMeshBuilder();
  public int getFaceCount();
  public Direct3dRMFaceArray getFaces();
  public String getName();
  public int getPerspective();
  public int getQuality();
  public void getTextureCoordinates(int idx, float[] u, float[] v);
  public int getVertexColor(int index);
  public int getVertexCount();
  public void getVertices(int[] vc, D3dVector v, int[] nc,
        D3dVector n, int[] fs, int[] fc);
  public int getVerticesSize();
  public void loadFromFileByPos(String filename, int position,
        int flags, ILoadTextureCallback c, IUnknown pUser);
  public void reserveSpace(int v_cnt, int n_cnt, int f_cnt);
  public void save(String fname, int xFormat, int save);
  public void scale(float sx, float sy, float sz);
  public void setAppData(int data);
  public void setColor(int col);
  public void setColorRGB(float red, float green, float blue);
  public void setColorSource(int val);
  public void setMaterial(Direct3dRMMaterial val);
  public void setName(String name);
  public void setNormal(int idx, float x, float y, float z);
  public void setPerspective(int persp);
  public void setQuality(int q);
  public void setTexture(Direct3dRMTexture val);
  public void setTextureCoordinates(int idx, float u, float v);
  public void setTextureTopology(int wrap_u, int wrap_v);
  public void setVertex(int idx, float x, float y, float z);
  public void setVertexColor(int idx, int c);
  public void setVertexColorRGB(int idx, float r, float g, float b);
  public void translate(float tx, float ty, float tz);
}

For a description of methods and parameters, see Direct3dRMMeshBuilder.

IUnknown
  |
  +--IDirect3dRMMeshBuilder

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

addFace

public void addFace(Direct3dRMFace f);

addFaces

public void addFaces(int vCount, float[] ver, int nCount, float[] norm,
        int[] data);

addFrame

public void addFrame(Direct3dRMFrame f);

addMesh

public void addMesh(Direct3dRMMesh m);

addMeshBuilder

public void addMeshBuilder(Direct3dRMMeshBuilder mb);

addNormal

public void addNormal(float x, float y, float z);

addVertex

public void addVertex(float x, float y, float z);

createFace

public Direct3dRMFace createFace();

createFaceArray

public Direct3dRMFaceArray createFaceArray(int vCount, float[] vertices,
        int nCount, float[] normals, int[] data);

createMesh

public Direct3dRMMesh createMesh();

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMMeshBuilder duplicate();

generateNormals

public void generateNormals();

getAppData

public int getAppData();

getBox

public void getBox(D3dRMBox retv);

getClassName

public String getClassName();

getColorSource

public int getColorSource();

getd3drmMeshBuilder

public Direct3dRMMeshBuilder getd3drmMeshBuilder();

getFaceCount

public int getFaceCount();

getFaces

public Direct3dRMFaceArray getFaces();

getName

public String getName();

getPerspective

public int getPerspective();

getQuality

public int getQuality();

getTextureCoordinates

public void getTextureCoordinates(int idx, float[] u, float[] v);

getVertexColor

public int getVertexColor(int index);

getVertexCount

public int getVertexCount();

getVertices

public void getVertices(int[] vc, D3dVector v, int[] nc, D3dVector n, int[]
        fs, int[] fc);

getVerticesSize

public int getVerticesSize();

loadFromFileByPos

public void loadFromFileByPos(String filename, int position, int flags,
        ILoadTextureCallback c, IUnknown pUser);

reserveSpace

public void reserveSpace(int v_cnt, int n_cnt, int f_cnt);

save

public void save(String fname, int xFormat, int save);

scale

public void scale(float sx, float sy, float sz);

setAppData

public void setAppData(int data);

setColor

public void setColor(int col);

setColorRGB

public void setColorRGB(float red, float green, float blue);

setColorSource

public void setColorSource(int val);

setMaterial

public void setMaterial(Direct3dRMMaterial val);

setName

public void setName(String name);

setNormal

public void setNormal(int idx, float x, float y, float z);

setPerspective

public void setPerspective(int persp);

setQuality

public void setQuality(int q);

setTexture

public void setTexture(Direct3dRMTexture val);

setTextureCoordinates

public void setTextureCoordinates(int idx, float u, float v);

setTextureTopology

public void setTextureTopology(int wrap_u, int wrap_v);

setVertex

public void setVertex(int idx, float x, float y, float z);

setVertexColor

public void setVertexColor(int idx, int c);

setVertexColorRGB

public void setVertexColorRGB(int idx, float r, float g, float b);

translate

public void translate(float tx, float ty, float tz);


Interface IDirect3dRMObject

public interface IDirect3dRMObject extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMObject duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void setAppData(int data);
  public void setName(String name);
}

For a description of methods and parameters, see Direct3dRMObject.

IUnknown
  |
  +--IDirect3dRMObject

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMObject duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

setAppData

public void setAppData(int data);

setName

public void setName(String name);


Interface IDirect3dRMPickArray

public interface IDirect3dRMPickArray extends IUnknown
{
  // Methods
  public Direct3dRMFrameArray getPickFrame(int index, D3dRMPickDesc
        desc);
  public Direct3dRMVisual getPickVisual(int index,
        D3dRMPickDesc desc);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMPickArray.

IUnknown
  |
  +--IDirect3dRMPickArray

Methods

getPickFrame

public Direct3dRMFrameArray getPickFrame(int index, D3dRMPickDesc desc);

getPickVisual

public Direct3dRMVisual getPickVisual(int index, D3dRMPickDesc desc);

getSize

public int getSize();


Interface IDirect3dRMTexture

public interface IDirect3dRMTexture extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void changed(int pixels, int palette);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMTexture duplicate();
  public int getAppData();
  public String getClassName();
  public int getColors();
  public void getDecalOrigin(int[] x, int[] y);
  public int getDecalScale();
  public void getDecalSize(float[] w, float[] h);
  public int getDecalTransparency();
  public int getDecalTransparentColor();
  public D3dRMImage getImage();
  public void getImageBuffer(byte[] buffer1);
  public void getImagePalette(byte[] pal);
  public String getName();
  public int getShades();
  public void initFromFile(String filename);
  public void initFromResource(int rs);
  public void initFromSurface(DirectDrawSurface ddS);
  public void setAppData(int data);
  public void setColors(int c);
  public void setDecalOrigin(int x, int y);
  public void setDecalScale(int s);
  public void setDecalSize(float width, float height);
  public void setDecalTransparency(int trans);
  public void setDecalTransparentColor(int tcolor);
  public void setName(String name);
  public void setShades(int s);
}

For a description of methods and parameters, see Direct3dRMTexture.

IUnknown
  |
  +--IDirect3dRMTexture

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

changed

public void changed(int pixels, int palette);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMTexture duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getColors

public int getColors();

getDecalOrigin

public void getDecalOrigin(int[] x, int[] y);

getDecalScale

public int getDecalScale();

getDecalSize

public void getDecalSize(float[] w, float[] h);

getDecalTransparency

public int getDecalTransparency();

getDecalTransparentColor

public int getDecalTransparentColor();

getImage

public D3dRMImage getImage();

getImageBuffer

public void getImageBuffer(byte[] buffer1);

getImagePalette

public void getImagePalette(byte[] pal);

getName

public String getName();

getShades

public int getShades();

initFromFile

public void initFromFile(String filename);

initFromResource

public void initFromResource(int rs);

initFromSurface

public void initFromSurface(DirectDrawSurface ddS);

setAppData

public void setAppData(int data);

setColors

public void setColors(int c);

setDecalOrigin

public void setDecalOrigin(int x, int y);

setDecalScale

public void setDecalScale(int s);

setDecalSize

public void setDecalSize(float width, float height);

setDecalTransparency

public void setDecalTransparency(int trans);

setDecalTransparentColor

public void setDecalTransparentColor(int tcolor);

setName

public void setName(String name);

setShades

public void setShades(int s);


Interface IDirect3dRMUserVisual

public interface IDirect3dRMUserVisual extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMUserVisual duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void setAppData(int data);
  public void setName(String name);
}

For a description of methods and parameters, see Direct3dRMUserVisual

IUnknown
  |
  +--IDirect3dRMUserVisual

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMUserVisual duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

setAppData

public void setAppData(int data);

setName

public void setName(String name);


Interface IDirect3dRMViewport

public interface IDirect3dRMViewport extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void clear();
  public void configure(int x, int y, int width, int height);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMViewport duplicate();
  public void forceUpdate(int x1, int y1, int x2, int y2);
  public int getAppData();
  public float getBack();
  public Direct3dRMFrame getCamera();
  public String getClassName();
  public Direct3dRMDevice getDevice();
  public Direct3dViewport getDirect3DViewport();
  public float getField();
  public float getFront();
  public int getHeight();
  public String getName();
  public void getPlane(float[] l, float[] r, float[] b, float[] t);
  public int getProjection();
  public int getUniformScaling();
  public int getWidth();
  public int getX();
  public int getY();
  public void inverseTransform(D3dVector d, D3dRMvector4d s);
  public Direct3dRMPickArray pick(int x, int y);
  public void render(Direct3dRMFrame f);
  public void setAppData(int data);
  public void setBack(float v);
  public void setCamera(Direct3dRMFrame f);
  public void setField(float v);
  public void setFront(float v);
  public void setName(String name);
  public void setPlane(float left, float right, float bottom, float
        top);
  public void setProjection(int val);
  public void setUniformScaling(int flag);
  public void transform(D3dRMvector4d d, D3dVector s);
}

For a description of methods and parameters, see Direct3dRMViewport.

IUnknown
  |
  +--IDirect3dRMViewport

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

clear

public void clear();

configure

public void configure(int x, int y, int width, int height);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMViewport duplicate();

forceUpdate

public void forceUpdate(int x1, int y1, int x2, int y2);

getAppData

public int getAppData();

getBack

public float getBack();

getCamera

public Direct3dRMFrame getCamera();

getClassName

public String getClassName();

getDevice

public Direct3dRMDevice getDevice();

getDirect3DViewport

public Direct3dViewport getDirect3DViewport();

getField

public float getField();

getFront

public float getFront();

getHeight

public int getHeight();

getName

public String getName();

getPlane

public void getPlane(float[] l, float[] r, float[] b, float[] t);

getProjection

public int getProjection();

getUniformScaling

public int getUniformScaling();

getWidth

public int getWidth();

getX

public int getX();

getY

public int getY();

inverseTransform

public void inverseTransform(D3dVector d, D3dRMvector4d s);

pick

public Direct3dRMPickArray pick(int x, int y);

render

public void render(Direct3dRMFrame f);

setAppData

public void setAppData(int data);

setBack

public void setBack(float v);

setCamera

public void setCamera(Direct3dRMFrame f);

setField

public void setField(float v);

setFront

public void setFront(float v);

setName

public void setName(String name);

setPlane

public void setPlane(float left, float right, float bottom, float top);

setProjection

public void setProjection(int val);

setUniformScaling

public void setUniformScaling(int flag);

transform

public void transform(D3dRMvector4d d, D3dVector s);


Interface IDirect3dRMViewportArray

public interface IDirect3dRMViewportArray extends IUnknown
{
  // Methods
  public Direct3dRMViewport getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMViewportArray.

IUnknown
  |
  +--IDirect3dRMViewportArray

Methods

getElement

public Direct3dRMViewport getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMVisual

public interface IDirect3dRMVisual extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMVisual duplicate();
  public int getAppData();
  public String getClassName();
  public Direct3dRMMeshBuilder getd3drmMeshBuilder();
  public String getName();
  public void setAppData(int data);
  public void setName(String name);
}

For a description of methods and parameters, see Direct3dRMVisual.

IUnknown
  |
  +--IDirect3dRMVisual

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMVisual duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getd3drmMeshBuilder

public Direct3dRMMeshBuilder getd3drmMeshBuilder();

getName

public String getName();

setAppData

public void setAppData(int data);

setName

public void setName(String name);


Interface IDirect3dRMVisualArray

public interface IDirect3dRMVisualArray extends IUnknown
{
  // Methods
  public Direct3dRMVisual getElement(int index);
  public int getSize();
}

For a description of methods and parameters, see Direct3dRMVisualArray.

IUnknown
  |
  +--IDirect3dRMVisualArray

Methods

getElement

public Direct3dRMVisual getElement(int index);

getSize

public int getSize();


Interface IDirect3dRMWinDevice

public interface IDirect3dRMWinDevice extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMWinDevice duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void handleActivate(int wparam);
  public void handlePaint(int hdc);
  public void setAppData(int data);
  public void setName(String name);
}

For a description of methods and parameters, see Direct3dRMWinDevice.

IUnknown
  |
  +--IDirect3dRMWinDevice

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMWinDevice duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

handleActivate

public void handleActivate(int wparam);

handlePaint

public void handlePaint(int hdc);

setAppData

public void setAppData(int data);

setName

public void setName(String name);


Interface IDirect3dRMWrap

public interface IDirect3dRMWrap extends IUnknown
{
  // Methods
  public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);
  public void apply(Direct3dRMObject o);
  public void applyRelative(Direct3dRMFrame f, Direct3dRMObject o);
  public void deleteDestroyCallback(Id3drmCallback fn,
        IUnknown args);
  public Direct3dRMWrap duplicate();
  public int getAppData();
  public String getClassName();
  public String getName();
  public void setAppData(int data);
  public void setName(String name);
}

For a description of methods and parameters, see Direct3dRMWrap.

IUnknown
  |
  +--IDirect3dRMWrap

Methods

addDestroyCallback

public void addDestroyCallback(Id3drmCallback fn, IUnknown Arg);

apply

public void apply(Direct3dRMObject o);

applyRelative

public void applyRelative(Direct3dRMFrame f, Direct3dRMObject o);

deleteDestroyCallback

public void deleteDestroyCallback(Id3drmCallback fn, IUnknown args);

duplicate

public Direct3dRMWrap duplicate();

getAppData

public int getAppData();

getClassName

public String getClassName();

getName

public String getName();

setAppData

public void setAppData(int data);

setName

public void setName(String name);


Interface IDirect3dTexture

public interface IDirect3dTexture extends IUnknown
{
  // Methods
  public int getHandle(Direct3dDevice dev);
  public void initialize(Direct3dDevice dev,
        DirectDrawSurface surf);
  public void load(Direct3dTexture tex);
  public void paletteChanged(int start, int count);
  public void unload();
}

For a description of methods and parameters, see Direct3dTexture.

IUnknown
  |
  +--IDirect3dTexture

Methods

getHandle

public int getHandle(Direct3dDevice dev);

initialize

public void initialize(Direct3dDevice dev, DirectDrawSurface surf);

load

public void load(Direct3dTexture tex);

paletteChanged

public void paletteChanged(int start, int count);

unload

public void unload();


Interface IDirect3dViewport

public interface IDirect3dViewport extends IUnknown
{
  // Methods
  public void clear(D3dRect rec, int flags);
  public void getBackground(int[] hdl, int[] stat);
  public DirectDrawSurface getBackgroundDepth(int[] status);
  public void getViewport(D3dViewportDesc vp);
  public void setBackground(int hdl);
  public void setBackgroundDepth(DirectDrawSurface surface);
  public void setViewport(D3dViewportDesc vp);
}

For a description of methods and parameters, see Direct3dViewport.

IUnknown
  |
  +--IDirect3dViewport

Methods

clear

public void clear(D3dRect rec, int flags);

getBackground

public void getBackground(int[] hdl, int[] stat);

getBackgroundDepth

public DirectDrawSurface getBackgroundDepth(int[] status);

getViewport

public void getViewport(D3dViewportDesc vp);

setBackground

public void setBackground(int hdl);

setBackgroundDepth

public void setBackgroundDepth(DirectDrawSurface surface);

setViewport

public void setViewport(D3dViewportDesc vp);


Interface IDirectDraw

public interface IDirectDraw extends IUnknown
{
  // Methods
  public void Compact();
  public DirectDrawClipper createClipper(int flags);
  public Direct3d createD3D();
  public DirectDrawPalette createPalette(int flags, byte[] pe);
  public DirectDrawSurface createSurface(DDSurfaceDesc dd);
  public DirectDrawSurface duplicateSurface(DirectDrawSurface ddIn);
  public void enumDisplayModes(int d, DDSurfaceDesc s,
        IUnknown args, IEnumModesCallback fn);
  public void enumSurfaces(int d, DDSurfaceDesc s, IUnknown args,
        IEnumSurfacesCallback fn);
  public void flipToGDISurface();
  public int getAvailableTotalMem();
  public void getCaps(DDCaps DriverCaps, DDCaps HELcaps);
  public void getDisplayMode(DDSurfaceDesc surface);
  public int getFourCCCodes(int[] size);
  public int getFreeMem();
  public DirectDrawSurface getGDISurface();
  public int getMonitorFrequency();
  public int getNumFourCCCodes();
  public int getScanLine();
  public int getVerticalBlankStatus();
  public DirectDrawPalette loadPaletteFromBitmap(String bName);
  public void restoreDisplayMode();
  public void SetCooperativeLevel(int hdl, int flags);
  public void setDisplayMode(int w, int h, int bpp, int ref,
        int mode);
  public int systemBpp();
  public int tickCount();
  public void waitForVerticalBlank(int flags, int handle);
}

For a description of methods and parameters, see DirectDraw.

IUnknown
  |
  +--IDirectDraw

Methods

Compact

public void Compact();

createClipper

public DirectDrawClipper createClipper(int flags);

createD3D

public Direct3d createD3D();

createPalette

public DirectDrawPalette createPalette(int flags, byte[] pe);

createSurface

public DirectDrawSurface createSurface(DDSurfaceDesc dd);

duplicateSurface

public DirectDrawSurface duplicateSurface(DirectDrawSurface ddIn);

enumDisplayModes

public void enumDisplayModes(int d, DDSurfaceDesc s, IUnknown args,
        IEnumModesCallback fn);

enumSurfaces

public void enumSurfaces(int d, DDSurfaceDesc s, IUnknown args,
        IEnumSurfacesCallback fn);

flipToGDISurface

public void flipToGDISurface();

getAvailableTotalMem

public int getAvailableTotalMem();

getCaps

public void getCaps(DDCaps DriverCaps, DDCaps HELcaps);

getDisplayMode

public void getDisplayMode(DDSurfaceDesc surface);

getFourCCCodes

public int getFourCCCodes(int[] size);

getFreeMem

public int getFreeMem();

getGDISurface

public DirectDrawSurface getGDISurface();

getMonitorFrequency

public int getMonitorFrequency();

getNumFourCCCodes

public int getNumFourCCCodes();

getScanLine

public int getScanLine();

getVerticalBlankStatus

public int getVerticalBlankStatus();

loadPaletteFromBitmap

public DirectDrawPalette loadPaletteFromBitmap(String bName);

restoreDisplayMode

public void restoreDisplayMode();

SetCooperativeLevel

public void SetCooperativeLevel(int hdl, int flags);

setDisplayMode

public void setDisplayMode(int w, int h, int bpp, int ref, int mode);

systemBpp

public int systemBpp();

tickCount

public int tickCount();

waitForVerticalBlank

public void waitForVerticalBlank(int flags, int handle);


Interface IDirectDrawBitmap

public interface IDirectDrawBitmap extends IUnknown
{
  // Methods
  public void filename(String val);
  public int height();
  public void initHeight(int val);
  public void initWidth(int val);
  public int loaded();
  public int width();
}

For a description of methods and parameters, see DirectDrawBitmap.

IUnknown
  |
  +--IDirectDrawBitmap

Methods

filename

public void filename(String val);

height

public int height();

initHeight

public void initHeight(int val);

initWidth

public void initWidth(int val);

loaded

public int loaded();

width

public int width();


Interface IDirectDrawClipper

public interface IDirectDrawClipper extends IUnknown
{
  // Methods
  public void getClipList(Rect rec, int[] rects, int count,
        Rect boundingrec);
  public int getClipListSize(Rect rec);
  public int getHWnd();
  public void initialize(DirectDraw dd, int flags);
  public int isClipListChanged();
  public void setClipList(Rect rec, int[] rects, int count);
  public void setHWnd(int flags, int hdl);
}

For a description of methods and parameters, see DirectDrawClipper.

IUnknown
  |
  +--IDirectDrawClipper

Methods

getClipList

public void getClipList(Rect rec, int[] rects, int count, Rect boundingrec);

getClipListSize

public int getClipListSize(Rect rec);

getHWnd

public int getHWnd();

initialize

public void initialize(DirectDraw dd, int flags);

isClipListChanged

public int isClipListChanged();

setClipList

public void setClipList(Rect rec, int[] rects, int count);

setHWnd

public void setHWnd(int flags, int hdl);


Interface IDirectDrawPalette

public interface IDirectDrawPalette extends IUnknown
{
  // Methods
  public int getCaps();
  public void getEntries(int flags, int start, int count,
        byte[] val);
  public void internalAttachDD(DirectDraw dd);
  public void setEntries(int flags, int start, int count,
        byte[] val);
}

For a description of methods and parameters, see DirectDrawPalette.

IUnknown
  |
  +--IDirectDrawPalette

Methods

getCaps

public int getCaps();

getEntries

public void getEntries(int flags, int start, int count, byte[] val);

internalAttachDD

public void internalAttachDD(DirectDraw dd);

setEntries

public void setEntries(int flags, int start, int count, byte[] val);


Interface IDirectDrawSurface

public interface IDirectDrawSurface extends IUnknown
{
  // Methods
  public void addAttachedSurface(DirectDrawSurface ddS);
  public void addOverlayDirtyRect(Rect r);
  public int blt(Rect dest, DirectDrawSurface ddS, Rect src,
        int flags);
  public int bltColorFill(Rect dest, int fillValue);
  public int bltFast(int dx, int dy, DirectDrawSurface ddS,
        Rect src, int trans);
  public int bltFx(Rect dest, DirectDrawSurface ddS, Rect src,
        int flags, DDBltFx bltFx);
  public void copyBitmap(DirectDrawBitmap val, int cx, int cy,
        int dx, int dy);
  public Direct3dDevice create3DDevice(_Guid g);
  public void deleteAttachedSurface(int flags,
        DirectDrawSurface ddS);
  public void enumAttachedSurfaces(IUnknown args,
        IEnumSurfacesCallback fn);
  public void enumOverlayZOrders(int flags, IUnknown args,
        IEnumZOrdersCallback fn);
  public void flip(DirectDrawSurface ddS, int flags);
  public void flush(Rect r, DDSurfaceDesc d, int flags, int hnd,
        int[] memory);
  public DirectDrawSurface getAttachedSurface(int caps);
  public int getBltStatus(int flags);
  public int getCaps();
  public DirectDrawClipper getClipper();
  public void getColorKey(int flags, DDColorKey val);
  public int getDC();
  public IUnknown getDDInterface();
  public int getFlipStatus(int flags);
  public int getOverlayPositionX();
  public int getOverlayPositionY();
  public DirectDrawPalette getPalette();
  public void getPixelFormat(DDPixelFormat pf);
  public void getSurfaceDesc(DDSurfaceDesc surface);
  public int isLost();
  public void lock(Rect r, DDSurfaceDesc d, int flags, int hnd,
        int[] memory);
  public void releaseDC(int hdc);
  public int restore();
  public void setClipper(DirectDrawClipper val);
  public void setColorKey(int flags, DDColorKey val);
  public void setOverlayPosition(int x, int y);
  public void setPalette(DirectDrawPalette ddp);
  public void unlock(DDSurfaceDesc data);
  public void updateOverlay(Rect r, DirectDrawSurface ddS, Rect d,
        int flags);
  public void updateOverlayDisplay(int flags);
  public void updateOverlayZOrder(int flags, DirectDrawSurface ddS);
}

For a description of methods and parameters, see DirectDrawSurface.

IUnknown
  |
  +--IDirectDrawSurface

Methods

addAttachedSurface

public void addAttachedSurface(DirectDrawSurface ddS);

addOverlayDirtyRect

public void addOverlayDirtyRect(Rect r);

blt

public int blt(Rect dest, DirectDrawSurface ddS, Rect src, int flags);

bltColorFill

public int bltColorFill(Rect dest, int fillValue);

bltFast

public int bltFast(int dx, int dy, DirectDrawSurface ddS, Rect src,
        int trans);

bltFx

public int bltFx(Rect dest, DirectDrawSurface ddS, Rect src, int flags,
        DDBltFx bltFx);

copyBitmap

public void copyBitmap(DirectDrawBitmap val, int cx, int cy, int dx,
        int dy);

create3DDevice

public Direct3dDevice create3DDevice(_Guid g);

deleteAttachedSurface

public void deleteAttachedSurface(int flags, DirectDrawSurface ddS);

enumAttachedSurfaces

public void enumAttachedSurfaces(IUnknown args, IEnumSurfacesCallback fn);

enumOverlayZOrders

public void enumOverlayZOrders(int flags, IUnknown args,
        IEnumZOrdersCallback fn);

flip

public void flip(DirectDrawSurface ddS, int flags);

flush

public void flush(Rect r, DDSurfaceDesc d, int flags, int hnd,
        int[] memory);

getAttachedSurface

public DirectDrawSurface getAttachedSurface(int caps);

getBltStatus

public int getBltStatus(int flags);

getCaps

public int getCaps();

getClipper

public DirectDrawClipper getClipper();

getColorKey

public void getColorKey(int flags, DDColorKey val);

getDC

public int getDC();

getDDInterface

public IUnknown getDDInterface();

getFlipStatus

public int getFlipStatus(int flags);

getOverlayPositionX

public int getOverlayPositionX();

getOverlayPositionY

public int getOverlayPositionY();

getPalette

public DirectDrawPalette getPalette();

getPixelFormat

public void getPixelFormat(DDPixelFormat pf);

getSurfaceDesc

public void getSurfaceDesc(DDSurfaceDesc surface);

isLost

public int isLost();

lock

public void lock(Rect r, DDSurfaceDesc d, int flags, int hnd, int[] memory);

releaseDC

public void releaseDC(int hdc);

restore

public int restore();

setClipper

public void setClipper(DirectDrawClipper val);

setColorKey

public void setColorKey(int flags, DDColorKey val);

setOverlayPosition

public void setOverlayPosition(int x, int y);

setPalette

public void setPalette(DirectDrawPalette ddp);

unlock

public void unlock(DDSurfaceDesc data);

updateOverlay

public void updateOverlay(Rect r, DirectDrawSurface ddS, Rect d, int flags);

updateOverlayDisplay

public void updateOverlayDisplay(int flags);

updateOverlayZOrder

public void updateOverlayZOrder(int flags, DirectDrawSurface ddS);


Interface IDirectInput

public interface IDirectInput extends IUnknown
{
  // Methods
  public void getDevCaps(int joyid, JoyCaps pjc);
  public String getDevCapsOEMVxd(int joyid);
  public String getDevCapsProductName(int joyid);
  public String getDevCapsRegKey(int joyid);
  public int getNumDevs();
  public void getPos(int joyid, JoyInfo info);
}

For a description of methods and parameters, see DirectInput.

IUnknown
  |
  +--IDirectInput

Methods

getDevCaps

public void getDevCaps(int joyid, JoyCaps pjc);

getDevCapsOEMVxd

public String getDevCapsOEMVxd(int joyid);

getDevCapsProductName

public String getDevCapsProductName(int joyid);

getDevCapsRegKey

public String getDevCapsRegKey(int joyid);

getNumDevs

public int getNumDevs();

getPos

public void getPos(int joyid, JoyInfo info);


Interface IDirectPlay2

public interface IDirectPlay2 extends IUnknown
{
  // Methods
  public void addPlayerToGroup(int groupId, int playerId);
  public void close();
  public IDirectPlay2 create(_Guid guid);
  public int createGroup(String friendlyName, String formalName,
        byte[] data, int dataSize);
  public int createPlayer(String friendlyName, String formalName,
        int receiveEvent, byte[] data, int dataSize);
  public void deletePlayerFromGroup(int groupId, int playerId);
  public void destroyGroup(int groupId);
  public void destroyPlayer(int playerId);
  public void enumGroupPlayers(int groupId, _Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumGroups(_Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumPlayers(_Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context,
        int flags);
  public void enumServiceProviders(
        IEnumServiceProvidersCallback callback, IUnknown context);
  public void enumSessions(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password, int timeOut,
        IEnumSessionsCallback2 callback, IUnknown context,
        int flags);
  public void getCaps(DPCaps caps, int flags);
  public void getGroupData(int groupId, byte[] data,
        int[] dataSize, int flags);
  public String getGroupFormalName(int groupId);
  public String getGroupFriendlyName(int groupId);
  public int getMessageCount(int playerId);
  public void getPlayerAddress(int playerId, byte[] addressData,
        int[] addressSize);
  public int getPlayerAddressSize(int playerId);
  public void getPlayerCaps(int playerId, DPCaps caps, int flags);
  public void getPlayerData(int playerId, byte[] data,
        int[] dataSize, int flags);
  public String getPlayerFormalName(int playerId);
  public String getPlayerFriendlyName(int playerId);
  public void getSessionDesc(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String[] sessionName, String[] password);
  public void initialize(_Guid guid);
  public void open(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName,
        String password, int flags);
  public void receive(int[] fromPlayerId, int[] toPlayerId,
        int flags, byte[] data, int[] dataSize);
  public int receiveSize(int flags);
  public void send(int fromPlayerId, int toPlayerId, int flags,
        byte[] data, int dataSize);
  public void setGroupData(int groupId, byte[] data, int dataSize,
        int flags);
  public void setGroupName(int groupId, String friendlyName, String
        formalName, int flags);
  public void setPlayerData(int playerId, byte[] data,
        int dataSize, int flags);
  public void setPlayerName(int playerId, String friendlyName,
        String formalName, int flags);
  public void setSessionDesc(DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password, int flags);
}

For a description of methods and parameters, see DirectPlay2.

IUnknown
  |
  +--IDirectPlay2

Methods

addPlayerToGroup

public void addPlayerToGroup(int groupId, int playerId);

close

public void close();

create

public IDirectPlay2 create(_Guid guid);

createGroup

public int createGroup(String friendlyName, String formalName, byte[] data,
        int dataSize);

createPlayer

public int createPlayer(String friendlyName, String formalName,
        int receiveEvent, byte[] data, int dataSize);

deletePlayerFromGroup

public void deletePlayerFromGroup(int groupId, int playerId);

destroyGroup

public void destroyGroup(int groupId);

destroyPlayer

public void destroyPlayer(int playerId);

enumGroupPlayers

public void enumGroupPlayers(int groupId, _Guid sessionGuid,
        IEnumPlayersCallback2 callback, IUnknown context, int flags);

enumGroups

public void enumGroups(_Guid sessionGuid, IEnumPlayersCallback2 callback,
        IUnknown context, int flags);

enumPlayers

public void enumPlayers(_Guid sessionGuid, IEnumPlayersCallback2 callback,
        IUnknown context, int flags);

enumServiceProviders

public void enumServiceProviders(IEnumServiceProvidersCallback callback,
        IUnknown context);

enumSessions

public void enumSessions(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int timeOut, IEnumSessionsCallback2 callback, IUnknown context, int
        flags);

getCaps

public void getCaps(DPCaps caps, int flags);

getGroupData

public void getGroupData(int groupId, byte[] data, int[] dataSize,
        int flags);

getGroupFormalName

public String getGroupFormalName(int groupId);

getGroupFriendlyName

public String getGroupFriendlyName(int groupId);

getMessageCount

public int getMessageCount(int playerId);

getPlayerAddress

public void getPlayerAddress(int playerId, byte[] addressData,
        int[] addressSize);

getPlayerAddressSize

public int getPlayerAddressSize(int playerId);

getPlayerCaps

public void getPlayerCaps(int playerId, DPCaps caps, int flags);

getPlayerData

public void getPlayerData(int playerId, byte[] data, int[] dataSize,
        int flags);

getPlayerFormalName

public String getPlayerFormalName(int playerId);

getPlayerFriendlyName

public String getPlayerFriendlyName(int playerId);

getSessionDesc

public void getSessionDesc(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String[] sessionName, String[] password);

initialize

public void initialize(_Guid guid);

open

public void open(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int flags);

receive

public void receive(int[] fromPlayerId, int[] toPlayerId, int flags, byte[]
        data, int[] dataSize);

receiveSize

public int receiveSize(int flags);

send

public void send(int fromPlayerId, int toPlayerId, int flags, byte[] data,
        int dataSize);

setGroupData

public void setGroupData(int groupId, byte[] data, int dataSize, int flags);

setGroupName

public void setGroupName(int groupId, String friendlyName,
        String formalName, int flags);

setPlayerData

public void setPlayerData(int playerId, byte[] data, int dataSize,
        int flags);

setPlayerName

public void setPlayerName(int playerId, String friendlyName,
        String formalName, int flags);

setSessionDesc

public void setSessionDesc(DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        int flags);


Interface IDirectPlayLobby

public interface IDirectPlayLobby
{
  // Methods
  public IDirectPlay2 connect();
  public IDirectPlayLobby create(_Guid guid);
  public void createAddress(_Guid spGuid, _Guid addressTypeGuid,
        String addressString, byte[] addressData,
        int[] addressSize);
  public int createAddressSize(_Guid spGuid, _Guid addressTypeGuid,
        String addressString);
  public void enumAddress(IEnumAddressCallback callback,
        byte[] addressData, int addressSize, IUnknown context);
  public void enumAddressTypes(IEnumAddressTypesCallback callback,
        _Guid spGuid, IUnknown context, int flags);
  public void enumLocalApplications(
        IEnumLocalApplicationsCallback callback,
        IUnknown context, int flags);
  public void enumServiceProviders(
        IEnumServiceProvidersCallback callback, IUnknown context);
  public void getConnectionSettings(int applicationId,
        int[] connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String[] sessionName, String[] password,
        String[] playerShortName, String[] playerLongName,
        _Guid guidSP, byte[] addressData, int[] addressSize);
  public int getConnectionSettingsAddressSize(int applicationId);
  public void receiveLobbyMessage(int applicationId, int[] flags,
        byte[] data, int[] dataSize);
  public void receiveLobbyMessageSize(int applicationId,
        int[] flags, int[] dataSize);
  public void runApplication(int[] applicationId,
        int connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password,
        String playerShortName, String playerLongName,
        _Guid spGuid, byte[] addressData, int addressSize,
        int receiveEvent);
  public void sendLobbyMessage(int applicationId, byte[] data,
        int dataSize);
  public void setConnectionSettings(int applicationId,
        int connectionFlags, DPSessionDesc sessionDesc,
        _Guid sessionGuid, _Guid applicationGuid,
        String sessionName, String password,
        String playerShortName, String playerLongName,
        _Guid spGuid, byte[] addressData, int addressSize);
  public void setLobbyMessageEvent(int applicationId,
        int receiveEvent);
}

For a description of methods and parameters, see DirectPlayLobby.

Methods

connect

public IDirectPlay2 connect();

create

public IDirectPlayLobby create(_Guid guid);

createAddress

public void createAddress(_Guid spGuid, _Guid addressTypeGuid,
        String addressString, byte[] addressData, int[] addressSize);

createAddressSize

public int createAddressSize(_Guid spGuid, _Guid addressTypeGuid,
        String addressString);

enumAddress

public void enumAddress(IEnumAddressCallback callback, byte[] addressData,
        int addressSize, IUnknown context);

enumAddressTypes

public void enumAddressTypes(IEnumAddressTypesCallback callback,
        _Guid spGuid, IUnknown context, int flags);

enumLocalApplications

public void enumLocalApplications(IEnumLocalApplicationsCallback callback,
        IUnknown context, int flags);

enumServiceProviders

public void enumServiceProviders(IEnumServiceProvidersCallback callback,
        IUnknown context);

getConnectionSettings

public void getConnectionSettings(int applicationId, int[] connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid, _Guid
        applicationGuid, String[] sessionName, String[] password, String[]
        playerShortName, String[] playerLongName, _Guid guidSP, byte[]
        addressData, int[] addressSize);

getConnectionSettingsAddressSize

public int getConnectionSettingsAddressSize(int applicationId);

receiveLobbyMessage

public void receiveLobbyMessage(int applicationId, int[] flags,
        byte[] data, int[] dataSize);

receiveLobbyMessageSize

public void receiveLobbyMessageSize(int applicationId, int[] flags,
        int[] dataSize);

runApplication

public void runApplication(int[] applicationId, int connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        String playerShortName, String playerLongName, _Guid spGuid, byte[]
        addressData, int addressSize, int receiveEvent);

sendLobbyMessage

public void sendLobbyMessage(int applicationId, byte[] data, int dataSize);

setConnectionSettings

public void setConnectionSettings(int applicationId, int connectionFlags,
        DPSessionDesc sessionDesc, _Guid sessionGuid,
        _Guid applicationGuid, String sessionName, String password,
        String playerShortName, String playerLongName, _Guid spGuid, byte[]
        addressData, int addressSize);

setLobbyMessageEvent

public void setLobbyMessageEvent(int applicationId, int receiveEvent);


Interface IDirectSound

public interface IDirectSound extends IUnknown
{
  // Methods
  public void compact();
  public DirectSoundBuffer createSoundBuffer(
        DSBufferDesc bufferDesc, byte[] format);
  public DirectSoundBuffer duplicateSoundBuffer(
        DirectSoundBuffer original);
  public void enumSoundDrivers(IEnumSoundDriversCallback callback,
        IUnknown context);
  public void getCaps(DSCaps caps);
  public void getSpeakerConfig(int[] speakerConfig);
  public void initialize(_Guid guid);
  public void setCooperativeLevel(int hwnd, int level);
  public void setSpeakerConfig(int speakerConfig);
}

For a description of methods and parameters, see DirectSound.

IUnknown
  |
  +--IDirectSound

Methods

compact

public void compact();

createSoundBuffer

public DirectSoundBuffer createSoundBuffer(DSBufferDesc bufferDesc,
        byte[] format);

duplicateSoundBuffer

public DirectSoundBuffer duplicateSoundBuffer(DirectSoundBuffer original);

enumSoundDrivers

public void enumSoundDrivers(IEnumSoundDriversCallback callback,
        IUnknown context);

getCaps

public void getCaps(DSCaps caps);

getSpeakerConfig

public void getSpeakerConfig(int[] speakerConfig);

initialize

public void initialize(_Guid guid);

setCooperativeLevel

public void setCooperativeLevel(int hwnd, int level);

setSpeakerConfig

public void setSpeakerConfig(int speakerConfig);


Interface IDirectSound3dBuffer

public interface IDirectSound3dBuffer extends IUnknown
{
  // Methods
  public void getAllParameters(DS3dBuffer buffer);
  public void getConeAngles(int[] inCone, int[] outCone);
  public void getConeOrientation(D3dVector orientation);
  public void getConeOutsideVolume(int[] coneOutsideVolume);
  public void getMaxDistance(float[] maxDistance);
  public void getMinDistance(float[] minDistance);
  public void getMode(int[] mode);
  public void getPosition(D3dVector position);
  public void getVelocity(D3dVector velocity);
  public void setAllParameters(DS3dBuffer buffer, int applyFlag);
  public void setConeAngles(int inCone, int outCone, int applyFlag);
  public void setConeOrientation(float x, float y, float z,
        int applyFlag);
  public void setConeOutsideVolume(int coneOutsideVolume,
        int applyFlag);
  public void setMaxDistance(float maxDistance, int applyFlag);
  public void setMinDistance(float minDistance, int applyFlag);
  public void setMode(int mode, int applyFlag);
  public void setPosition(float x, float y, float z, int applyFlag);
  public void setVelocity(float x, float y, float z, int applyFlag);
}

For a description of methods and parameters, see DirectSound3dBuffer.

IUnknown
  |
  +--IDirectSound3dBuffer

Methods

getAllParameters

public void getAllParameters(DS3dBuffer buffer);

getConeAngles

public void getConeAngles(int[] inCone, int[] outCone);

getConeOrientation

public void getConeOrientation(D3dVector orientation);

getConeOutsideVolume

public void getConeOutsideVolume(int[] coneOutsideVolume);

getMaxDistance

public void getMaxDistance(float[] maxDistance);

getMinDistance

public void getMinDistance(float[] minDistance);

getMode

public void getMode(int[] mode);

getPosition

public void getPosition(D3dVector position);

getVelocity

public void getVelocity(D3dVector velocity);

setAllParameters

public void setAllParameters(DS3dBuffer buffer, int applyFlag);

setConeAngles

public void setConeAngles(int inCone, int outCone, int applyFlag);

setConeOrientation

public void setConeOrientation(float x, float y, float z, int applyFlag);

setConeOutsideVolume

public void setConeOutsideVolume(int coneOutsideVolume, int applyFlag);

setMaxDistance

public void setMaxDistance(float maxDistance, int applyFlag);

setMinDistance

public void setMinDistance(float minDistance, int applyFlag);

setMode

public void setMode(int mode, int applyFlag);

setPosition

public void setPosition(float x, float y, float z, int applyFlag);

setVelocity

public void setVelocity(float x, float y, float z, int applyFlag);


Interface IDirectSound3dListener

public interface IDirectSound3dListener extends IUnknown
{
  // Methods
  public void commitDeferredSettings();
  public void getAllParameters(DS3dListener listener);
  public void getDistanceFactor(float[] distanceFactor);
  public void getDopplerFactor(float[] dopplerFactor);
  public void getOrientation(D3dVector orientFront,
        D3dVector orientTop);
  public void getPosition(D3dVector position);
  public void getRolloffFactor(float[] rolloffFactor);
  public void getVelocity(D3dVector velocity);
  public void setAllParameters(DS3dListener listener,
        int applyFlag);
  public void setDistanceFactor(float distanceFactor,
        int applyFlag);
  public void setDopplerFactor(float dopplerFactor, int applyFlag);
  public void setOrientation(float xFront, float yFront,
        float zFront, float xTop, float yTop, float zTop,
        int applyFlag);
  public void setPosition(float x, float y, float z, int applyFlag);
  public void setRolloffFactor(float rolloffFactor, int applyFlag);
  public void setVelocity(float x, float y, float z, int applyFlag);
}

For a description of methods and parameters, see DirectSound3dListener.

IUnknown
  |
  +--IDirectSound3dListener

Methods

commitDeferredSettings

public void commitDeferredSettings();

getAllParameters

public void getAllParameters(DS3dListener listener);

getDistanceFactor

public void getDistanceFactor(float[] distanceFactor);

getDopplerFactor

public void getDopplerFactor(float[] dopplerFactor);

getOrientation

public void getOrientation(D3dVector orientFront, D3dVector orientTop);

getPosition

public void getPosition(D3dVector position);

getRolloffFactor

public void getRolloffFactor(float[] rolloffFactor);

getVelocity

public void getVelocity(D3dVector velocity);

setAllParameters

public void setAllParameters(DS3dListener listener, int applyFlag);

setDistanceFactor

public void setDistanceFactor(float distanceFactor, int applyFlag);

setDopplerFactor

public void setDopplerFactor(float dopplerFactor, int applyFlag);

setOrientation

public void setOrientation(float xFront, float yFront, float zFront,
        float xTop, float yTop, float zTop, int applyFlag);

setPosition

public void setPosition(float x, float y, float z, int applyFlag);

setRolloffFactor

public void setRolloffFactor(float rolloffFactor, int applyFlag);

setVelocity

public void setVelocity(float x, float y, float z, int applyFlag);


Interface IDirectSoundBuffer

public interface IDirectSoundBuffer extends IUnknown
{
  // Methods
  public void getCaps(DSBCaps caps);
  public void getCurrentPosition(DSCursors cursors);
  public void getFormat(byte[] format, int size);
  public int getFormatSize();
  public int getFrequency();
  public int getPan();
  public int getStatus();
  public int getVolume();
  public void play(int flags);
  public void restore();
  public void setCurrentPosition(int newPosition);
  public void setFormat(byte[] format);
  public void setFrequency(int frequency);
  public void setPan(int pan);
  public void setVolume(int volume);
  public void stop();
  public void transferToSoundBuffer(DSResourceDesc resourceDesc,
        int flags);
  public void writeBuffer(int start, int size, byte[] buffer,
        int flags);
}

For a description of methods and parameters, see DirectSoundBuffer.

IUnknown
  |
  +--IDirectSoundBuffer

Methods

getCaps

public void getCaps(DSBCaps caps);

getCurrentPosition

public void getCurrentPosition(DSCursors cursors);

getFormat

public void getFormat(byte[] format, int size);

getFormatSize

public int getFormatSize();

getFrequency

public int getFrequency();

getPan

public int getPan();

getStatus

public int getStatus();

getVolume

public int getVolume();

play

public void play(int flags);

restore

public void restore();

setCurrentPosition

public void setCurrentPosition(int newPosition);

setFormat

public void setFormat(byte[] format);

setFrequency

public void setFrequency(int frequency);

setPan

public void setPan(int pan);

setVolume

public void setVolume(int volume);

stop

public void stop();

transferToSoundBuffer

public void transferToSoundBuffer(DSResourceDesc resourceDesc, int flags);

writeBuffer

public void writeBuffer(int start, int size, byte[] buffer, int flags);


Interface IDirectSoundResource

public interface IDirectSoundResource extends IUnknown
{
  // Methods
  public void loadWaveFile(String name,
        DSResourceDesc resourceDesc, byte[] wave);
  public void loadWaveResource(int handle,
        DSResourceDesc resourceDesc, byte[] wave);
  public void readBuffer(int sourceIndex, int destIndex, int size,
        DSResourceDesc resourceDesc, byte[] buffer, int maxbuf);
}

For a description of methods and parameters, see DirectSoundResource.

IUnknown
  |
  +--IDirectSoundResource

Methods

loadWaveFile

public void loadWaveFile(String name, DSResourceDesc resourceDesc,
        byte[] wave);

loadWaveResource

public void loadWaveResource(int handle, DSResourceDesc resourceDesc,
        byte[] wave);

readBuffer

public void readBuffer(int sourceIndex, int destIndex, int size,
        DSResourceDesc resourceDesc, byte[] buffer, int maxbuf);


Interface IEnumAddressCallback

public interface IEnumAddressCallback extends IUnknown
{
  // Methods
  public void callbackEnumAddress(_Guid typeGuid,
        byte[] addressData, int addressSize, IUnknown context);
}

IUnknown
  |
  +--IEnumAddressCallback

Methods

callbackEnumAddress

public void callbackEnumAddress(_Guid typeGuid, byte[] addressData,
        int addressSize, IUnknown context);

Application-defined callback function for the DirectPlayLobby.enumAddress method.

Return Value:

No return value.

Parameter | Description
typeGuid | A globally unique identifier (GUID) indicating the type of this data chunk.
addressData | The address of the constant data.
addressSize | The size of the address.
context | The context passed to the callback function.


Interface IEnumAddressTypesCallback

public interface IEnumAddressTypesCallback extends IUnknown
{
  // Methods
  public void callbackEnumAddressTypes(_Guid typeGuid,
        IUnknown context);
}

IUnknown
  |
  +--IEnumAddressTypesCallback

Methods

callbackEnumAddressTypes

public void callbackEnumAddressTypes(_Guid typeGuid, IUnknown context);

Application-defined callback function for the DirectPlayLobby.enumAddressTypes method.

Return Value:

No return value.

Parameter | Description
typeGuid | A globally unique identifier (GUID) indicating the address type. Predefined address types are DPAID_Phone, DPAID_Inet, and DPAID_ComPort.
context | The context passed to the callback function.


Interface IEnumerateObjectsCallback

public interface IEnumerateObjectsCallback extends IUnknown
{
  // Methods
  public void callbackEnumerateObjects(IDirect3dRM f,
        IUnknown pArgs);
}

Use with Direct3dRM.enumerateObjects to set the callback function to be called for each active Direct3dRM object.

IUnknown
  |
  +--IEnumerateObjectsCallback

Methods

callbackEnumerateObjects

public void callbackEnumerateObjects(IDirect3dRM f, IUnknown pArgs);

Enumerates objects. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
f | A Direct3dRM object.
pArgs | The application-defined data passed to this callback function.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface IEnumLocalApplicationsCallback

public interface IEnumLocalApplicationsCallback extends IUnknown
{
  // Methods
  public void callbackLocalApplications(_Guid applicationGuid,
        String applicationName, IUnknown context);
}

IUnknown
  |
  +--IEnumLocalApplicationsCallback

Methods

callbackLocalApplications

public void callbackLocalApplications(_Guid applicationGuid,
        String applicationName, IUnknown context);

Application-defined callback function for the DirectPlayLobby.enumLocalApplications method.

Return Value:

No return value.

Parameter | Description
applicationGuid | A globally unique identifier of the application. being enumerated.
applicationName | The name of the application being enumerated.
context | The context passed from the enumLocalApplications call.


Interface IEnumModesCallback

public interface IEnumModesCallback extends IUnknown
{
  // Methods
  public void callbackEnumModes(DDSurfaceDesc desc, IUnknown Ctxt);
}

Use with enumDisplayModes to set the callback function to be called for each display mode exposed by the hardware.

IUnknown
  |
  +--IEnumModesCallback

Methods

callbackEnumModes

public void callbackEnumModes(DDSurfaceDesc desc, IUnknown Ctxt);

Application-defined callback procedure.

Return Value:

No return value.

Parameter | Description
desc | A DDSurfaceDesc object that provides the monitor frequency and the mode that can be created. This data is read-only.
Ctxt | Application-defined data that is passed to the callback function each time the function is called.


Interface IEnumPlayersCallback2

public interface IEnumPlayersCallback2 extends IUnknown
{
  // Methods
  public void callbackEnumPlayers(int playerId, int playerType,
        String playerShortName, String playerLongName, int flags,
        IUnknown context);
}

Use with the DirectPlay2.enumGroupPlayers, DirectPlay2.enumGroups, and DirectPlay2.enumPlayers methods to set the callback function to be called for each group or player.

You can use the DirectPlay2.stopEnumPlayers method to stop a player enumeration.

IUnknown
  |
  +--IEnumPlayersCallback2

Methods

callbackEnumPlayers

public void callbackEnumPlayers(int playerId, int playerType,
        String playerShortName, String playerLongName, int flags,
        IUnknown context);

Application-defined callback procedure.

Return Value:

No return value.

Parameter | Description
playerId | ID of the player or group being enumerated.
playerType | The type of player, either DPPLAYERTYPE_GROUP or DPPLAYERTYPE_PLAYER.
playerShortName | The short name of the player.
playerLongName | The long name of the player.
flags | Specifies the flags that were passed to the enumGroups enumGroupPlayers, or enumPlayers, method.
context | The caller-defined context.


Interface IEnumServiceProvidersCallback

public interface IEnumServiceProvidersCallback extends IUnknown
{
  // Methods
  public void callbackEnumServiceProviders(_Guid spGuid,
        String spName, int majorVer, int minorVer,
        IUnknown context);
}

Use with the DirectPlay2.enumServiceProviders method to enumerate service providers installed on the system.

You can use the DirectPlay2.stopEnumServiceProviders method to stop a service provider enumeration.

IUnknown
  |
  +--IEnumServiceProvidersCallback

Methods

callbackEnumServiceProviders

public void callbackEnumServiceProviders(_Guid spGuid, String spName,
        int majorVer, int minorVer, IUnknown context);

Application-defined callback method used to enumerate DirectPlay service providers installed on a system.

Return Value:

No return value.

Parameter | Description
spGuid | The unique identifier of the Microsoft® DirectPlay® service provider.
spName | A string containing the driver description.
majorVer | The major version number of the driver.
minorVer | The minor version number of the driver.
context | An application-defined context.


Interface IEnumSessionsCallback2

public interface IEnumSessionsCallback2 extends IUnknown
{
  // Methods
  public void callbackEnumSessions(DPSessionDesc sessionDesc, _Guid
        instanceGuid, _Guid applicationGuid, String sessionName,
        String password, int[] timeOut, int flags, IUnknown
        context);
}

Use with DirectPlay2.enumSessions to set the callback function to be called for each active session.

You must use the DirectPlay2.stopEnumSessions to stop a session enumeration, or the enumeration will continue infinitely.

IUnknown
  |
  +--IEnumSessionsCallback2

Methods

callbackEnumSessions

public void callbackEnumSessions(DPSessionDesc sessionDesc,
        _Guid instanceGuid, _Guid applicationGuid, String sessionName,
        String password, int[] timeOut, int flags, IUnknown context);

Enumerates sessions. This is an application-defined callback procedure.

Return Value:

No return value.

Parameter | Description
sessionDesc | A DPSessionDesc object describing the enumerated session. This parameter will be set to null if the enumeration has timed out.
instanceGuid | A globally unique identifier (GUID) of the session instance.
applicationGuid | The GUID for the application running in the session instance. It uniquely identifies the application so that Microsoft® DirectPlay® connects only to other computers running the same application. This member can be set to GUID_NULL to enumerate sessions for any application.
sessionName | The Unicode string containing the name of the session. Use these members only if the IDirectPlay2 interface is in use.
password | The Unicode string containing the password of the session. Use this member only if the IDirectPlay2 interface is in use.
timeOut | The array variable that contains the current time-out value. This can be reset when the DPESC_TIMEDOUT flag is returned if you want to wait longer for sessions to reply.
flags Typically, this flag is set to zero.
DPESC_TIMEDOUT
The enumeration has timed out. Reset timeOut and return 1 to continue, or 0 to stop the enumeration.
context | The caller-defined context.


Interface IEnumSoundDriversCallback

public interface IEnumSoundDriversCallback extends IUnknown
{
  // Methods
  public void callbackEnumSoundDrivers(_Guid guid,
        String description, String moduleName, IUnknown context);
}

IUnknown
  |
  +--IEnumSoundDriversCallback

Methods

callbackEnumSoundDrivers

public void callbackEnumSoundDrivers(_Guid guid, String description, String
        moduleName, IUnknown context);

Enumerates Microsoft® DirectSound® drivers. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
guid | The globally unique identifier (GUID) that identifies the DirectSound driver being enumerated. This value can be passed to the DirectSound.initialize function to create a DirectSound object for that driver.
description | A null-terminated string that provides a textual description of the DirectSound device.
moduleName | A null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.
context | Application-defined data that is passed to each callback function.


Interface IEnumSurfacesCallback

public interface IEnumSurfacesCallback extends IUnknown
{
  // Methods
  public void callbackEnumSurfaces(DirectDrawSurface f,
        DDSurfaceDesc surfDesc, IUnknown ctxt);
}

Use with DirectDraw.enumSurfaces and DirectDrawSurface.enumAttachedSurfaces to set the callback function to be called for each specified surface.

Also see com.ms.directX.DirectDraw, com.ms.directX.DirectDrawSurface

IUnknown
  |
  +--IEnumSurfacesCallback

Methods

callbackEnumSurfaces

public void callbackEnumSurfaces(DirectDrawSurface f,
        DDSurfaceDesc surfDesc, IUnknown ctxt);

Enumerates surfaces.

Return Value:

No return value.

Parameter | Description
f | The DirectDrawSurface object.
surfDesc | A DDSurfaceDesc object that describes the surface.
ctxt | An application-defined structure that will be passed to the callback function each time the function is called.


Interface IEnumTextureFormatsCallback

public interface IEnumTextureFormatsCallback extends IUnknown
{
  // Methods
  public void callbackEnumTextureFormats(DDSurfaceDesc surfDesc,
        IUnknown userArg);
}

Use with Direct3dDevice.enumTextureFormats to set the callback function to be called for each texture format for a device.

IUnknown
  |
  +--IEnumTextureFormatsCallback

Methods

callbackEnumTextureFormats

public void callbackEnumTextureFormats(DDSurfaceDesc surfDesc,
        IUnknown userArg);

Prototype definition for the callback function to enumerate texture formats.

Return Value:

No return value.

Parameter | Description
surfDesc | A DDSurfaceDesc object containing the texture information.
userArg | An application-defined data passed to this callback function.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface IEnumZOrdersCallback

public interface IEnumZOrdersCallback extends IUnknown
{
  // Methods
  public void callbackEnumOverlayZOrders(DirectDrawSurface f,
        IUnknown context);
}

Use with DirectDrawSurface.enumOverlayZOrders to set the callback function to be called for each overlay on the given surface.

IUnknown
  |
  +--IEnumZOrdersCallback

Methods

callbackEnumOverlayZOrders

public void callbackEnumOverlayZOrders(DirectDrawSurface f,
        IUnknown context);

Enumerates overlays for the surface.

Return Value:

No return value.

Parameter | Description
f | The surface being overlaid on this surface.
context | An application-defined structure that will be passed to the callback function each time the function is called.


Interface IFrameMoveCallback

public interface IFrameMoveCallback extends IUnknown
{
  // Methods
  public void callbackFrameMove(Direct3dRMFrame f, IUnknown pArgs,
        float delta);
}

Use with Direct3dRMFrame.addMoveCallback and Direct3dRMFrame.deleteMoveCallback to set or remove the callback function to be called when a frame is moved.

IUnknown
  |
  +--IFrameMoveCallback

Methods

callbackFrameMove

public void callbackFrameMove(Direct3dRMFrame f, IUnknown pArgs,
        float delta);

Enables an application to apply customized algorithms when a frame is moved or updated. You can use this callback function to compensate for changing frame rates. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
f | The Direct3dRMFrame object that is being moved.
pArgs | Application-defined data passed to this callback function.
delta | The amount of change to apply to the movement. There are two components to the change in position of a frame: linear and rotational. The change in each component is equal to velocity_of_component x delta. Although either or both of these velocities can be set relative to any frame, the system automatically converts them to velocities relative to the parent frame for the purpose of applying time deltas.

Remarks:

Your application can synthesize the acceleration of a frame relative to its parent frame. To do so, on each tick, your application should set the velocity of the child frame, relative to itself to (a units per tick) x 1 tick, where a is the required acceleration. This is equal to a x delta units per tick. Internally, a x delta units per tick relative to the child frame is converted to (v + (a x delta )) units per tick relative to the parent frame, where v is the current velocity of the child relative to the parent.

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first and then calls their callback functions in the order in which they were created.


Interface ILoadCallback

public interface ILoadCallback extends IUnknown
{
  // Methods
  public void callbackLoad(Direct3dRM obj, _Guid id, IUnknown args);
}

Use with Direct3dRM.loadFromFileByPos to set the callback function to be called when an object is loaded.

IUnknown
  |
  +--ILoadCallback

Methods

callbackLoad

public void callbackLoad(Direct3dRM obj, _Guid id, IUnknown args);

Loads objects. This callback function is application-defined.

Return Value:

No return value.

Parameter | Description
obj | The Direct3dRM object being loaded.
id | The globally unique identifier (GUID) of the object being loaded.
args | Application-defined data passed to this callback function.

Remarks:

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface ILoadTextureCallback

public interface ILoadTextureCallback extends IUnknown
{
  // Methods
  public Direct3dRMTexture callbackLoadTexture(String text_name,
        IUnknown pArgs);
}

Use with methods, such as Direct3dRM.loadFromFileByPos to set the callback function to be called when loading a texture.

Also see com.ms.directX.Direct3dRM, com.ms.directX.Direct3dRMAnimation, com.ms.directX.Direct3dRMFrame, com.ms.directX.Direct3dRMMeshBuilder

IUnknown
  |
  +--ILoadTextureCallback

Methods

callbackLoadTexture

public Direct3dRMTexture callbackLoadTexture(String text_name,
        IUnknown pArgs);

Loads texture maps from a file. This callback function is application-defined.

Return Value:

Returns the Direct3dRMTexture object if successful; otherwise, returns null.

Parameter | Description
text_name | The name of the texture.
pArgs | The application-specific data.

Remarks:

Applications can use this callback function to implement support for textures that are not in the Microsoft® Windows® bitmap (.bmp) or Portable Pixmap (.ppm) P6 format.

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


Interface IUserVisualCallback

public interface IUserVisualCallback extends IUnknown
{
  // Methods
  public void callbackUserVisual(Direct3dRMUserVisual uv,
        IUnknown arg, int[] r, Direct3dRMDevice d,
        Direct3dRMViewport v);
}

Use with Direct3dRM.createUserVisual and Direct3dRMUserVisual.init to set the callback function to be called to render an application-defined visual.

IUnknown
  |
  +--IUserVisualCallback

Methods

callbackUserVisual

public void callbackUserVisual(Direct3dRMUserVisual uv, IUnknown arg, int[]
        r, Direct3dRMDevice d, Direct3dRMViewport v);

Alerts an application that supplies user-visual objects that it should execute the execute buffer. This function is application-defined.

Return Value:

No return value.

Parameter | Description
uv | The Direct3dRMUserVisual object.
Arg | Application-defined data passed to this callback function.
r An array variable that contains a value of user visual reason type:
D3DRMUSERVISUAL_CANSEE
The application should set this parameter to TRUE if the user-visual object is visible in the viewport. In this case, the application uses the device specified in the v parameter.
D3DRMUSERVISUAL_RENDER
The application should render the user-visual element. In this case, the application uses the device specified in the d parameter.
d | A Direct3dRMDevice object used to render the Direct3dRMUserVisual object.
v | A Direct3dRMViewport object used to determine whether the Direct3dRMUserVisual object is visible.

Remarks:

When determining the order in which to call callback functions, the system searches the objects that are highest in the hierarchy first, and then calls their callback functions in the order in which they were created.


About com.ms.dll

The com.ms.dll package helps you link your Java code with dynamic-link libraries (DLLs). You can use the methods in the com.ms.dll package along with Microsoft® J/Direct™ technology to call functions located in Win32 DLLs, OLE API functions, and third-party DLLs. For more information on J/Direct technology and on how to use the @dll.import compiler directive that J/Direct provides, see About J/Direct.

Overview

The DllLib class offers a variety of methods that are used in conjunction with the @dll.import directive. The ptrToXXX methods can be used to treat a parameter as a LPTSTR. Several copy methods, as well as read and write methods, allow your Java code to read and write data from raw pointers. The ptrToStruct method provides another way to read and write data through a raw pointer by wrapping the raw pointer in an instance of a class that was declared with the @dll.struct directive. For more information on how and when to declare a Java class with the @dll.struct directive, see the Structures section of the About J/Direct article. DllLib also contains methods that copy strings to native memory blocks, convert native strings to Java String objects, and free and allocate native memory blocks.

You can extend the Callback class to create Callback objects in Java. Your derived Callback class must contain one non-static method whose name is callback (all lowercase). The callback method has limited return types, and all the parameters must be of type int. After the Callback class has been created, you can use the @dll.import compiler directive to call a Win32 function that takes a Callback as a parameter.

The Root class provides a way for you to protect a Java object from garbage collection by creating a 32-bit root handle for the object. This is helpful when you have created a Callback object that will be used across function calls. By wrapping the Callback inside a root handle, you can keep the Callback from being reclaimed by garbage collection. When you no longer need the Callback, you should explicitly free its root handle using the dll.Root.free method.

You can use the Win32Exception class to create objects that contain error descriptions for error codes set by Win32 functions. When you call Win32 functions using the @dll.import compiler directive, you can use the setLastError modifier to tell the VM to capture the error code immediately after the function is called. You can then use the dll.dllLib.getLastWin32Error method to obtain the error code, and you can wrap it in a Java Win32Exception object that describes the error.

The following class in com.ms.dll is used by internal operations and must be installed on your host system for the com.ms.dll package to work correctly. However, the Java applications you create never need to call this class directly.

StringMarshaler
Converts a LPCSTR to a java.lang.String object.

Classes

Class Callback
This class creates a native callback for Win32 APIs such as EnumWindows.
Class DllLib
This class contains methods for linking to dynamic-link libraries (DLLs).
Class ParameterCountMismatchError
This class represents objects that contain the number of parameters expected and the number of objects actually passed to a method.
Class Root
This class allows you to create an opaque 32-bit root handle to any Java object.
Class Win32Exception
This class provides access to objects that contain error codes and error descriptions for errors set by Microsoft® Win32® functions.

Hierarchy

Object
  |
  +--Callback
  |
  +--DllLib
  |
  +--Root

RuntimeException
  |
  +--ParameterCountMismatchError
  |
  +--Win32Exception


Class Callback

public class Callback
{
  // Constructors
  protected Callback();

  // Methods
  protected void finalize();
}

This class creates a native callback for Win32 APIs such as EnumWindows. The Callback class can only be instantiated by a subclass constructor. Therefore, you must extend this class to use it. Each subclass must include a non-static method named callback, whose parameters are all integers and whose return type is either int or void. If a method that meets these requirements cannot be found anywhere in the inheritance hierarchy, construction will fail.

The callback method that is declared in a subclass creates a native callback that accepts as many 4-byte parameters as there are integer parameters to the callback method. The native callback returns a single 4-byte value, and that is the value returned by the callback method. If the callback method throws an uncaught Java exception, a zero is returned to the callback method's native caller.

To implement callbacks that take non-integer arguments such as strings or structures, you need to convert the integer argument (which typically corresponds to a native pointer) to a convenient Java type.

The Callback class is generally used for callbacks that exist only during the call of a single API. However, this class can also be used for persistent callbacks as long as you ensure that there is at least one Java reference to the Callback object for as long as the native code needs the callback.

For examples that show how you can declare and invoke DLL functions that take callbacks, see the Callbacks section of the Microsoft® J/Direct™ article.

Constructors

Callback

protected Callback();

Creates a Callback object. Since you must extend the Callback class to instantiate it, this constructor is used only by subclass constructors.

Methods

finalize

protected void finalize();

Performs cleanup before garbage collection.

Return Value:

No return value.


Class DllLib

public class DllLib
{
  // Fields
  public static final int systemDefaultCharSize;

  // Methods
  public static int addrOf(int root);
  public static int allocCoTaskMem(int cb);
  public static int allocHGlobal(int cb);
  public static void copy(byte jasrc[], int elemidx, int pdst,
        int nelems);
  public static void copy(char jasrc[], int elemidx, int pdst,
        int nelems);
  public static void copy(short jasrc[], int elemidx, int pdst, int
        nelems);
  public static void copy(int jasrc[], int elemidx, int pdst,
        int nelems);
  public static void copy(long jasrc[], int elemidx, int pdst,
        int nelems);
  public static void copy(float jasrc[], int elemidx, int pdst, int
        nelems);
  public static void copy(double jasrc[], int elemidx, int pdst,
        int nelems);
  public static void copy(Object jasrc, int ofs, int pdst, int cb);
  public static void copy(int psrc, byte jadst[], int elemidx,
        int nelems);
  public static void copy(int psrc, char jadst[], int elemidx,
        int nelems);
  public static void copy(int psrc, short jadst[], int elemidx, int
        nelems);
  public static void copy(int psrc, int jadst[], int elemidx,
        int nelems);
  public static void copy(int psrc, long jadst[], int elemidx,
        int nelems);
  public static void copy(int psrc, float jadst[], int elemidx, int
        nelems);
  public static void copy(int psrc, double jadst[], int elemidx,
        int nelems);
  public static void copy(int psrc, Object jadst, int ofs, int cb);
  public static void freeCoTaskMem(int ptr);
  public static void freeHGlobal(int hglobal);
  public static final int getLastWin32Error();
  public static boolean isStruct(Class structCls);
  public native static boolean isStruct(Field structField);
  public static int numParamBytes(Method m);
  public native static int offsetOf(Field structField);
  public static int offsetOf(Class structCls,
        String fieldName) throws SecurityException;
  public static native void prelink(Method method);
  public static void prelinkAll(Class cls);
  public static String ptrToString(int ptr);
  public static String ptrToStringAnsi(int ptr);
  public static String ptrToStringUni(int ptr);
  public static Object ptrToStruct(Class structClass, int ptr);
  public static native byte read1(Object ptr, int ofs);
  public static native byte read1(int ptr, int ofs);
  public static byte read1(int ptr);
  public static native short read2(Object ptr, int ofs);
  public static native short read2(int ptr, int ofs);
  public static short read2(int ptr);
  public static native int read4(Object ptr, int ofs);
  public static native int read4(int ptr, int ofs);
  public static int read4(int ptr);
  public static native long read8(Object ptr, int ofs);
  public static native long read8(int ptr, int ofs);
  public static long read8(int ptr);
  public static native void release(Object o);
  public native static void resize(Object structObj, int newsize);
  public static int sizeOf(Class structCls);
  public native static int sizeOf(Object structObj);
  public static int stringToCoTaskMem(String s);
  public static int stringToCoTaskMemAnsi(String s);
  public static int stringToCoTaskMemUni(String s);
  public static int stringToHGlobal(String s);
  public static int stringToHGlobalAnsi(String s);
  public static int stringToHGlobalUni(String s);
  public static final void throwWin32Exception();
  public static native void write1(Object ptr, int ofs, byte val);
  public static native void write1(int ptr, int ofs, byte val);
  public static void write1(int ptr, byte val);
  public static native void write2(Object ptr, int ofs, short val);
  public static native void write2(int ptr, int ofs, short val);
  public static void write2(int ptr, short val);
  public static native void write2(Object ptr, int ofs, char val);
  public static native void write2(int ptr, int ofs, char val);
  public static void write2(int ptr, char val);
  public static native void write4(Object ptr, int ofs, int val);
  public static native void write4(int ptr, int ofs, int val);
  public static void write4(int ptr, int val);
  public static native void write8(Object ptr, int ofs, long val);
  public static native void write8(int ptr, int ofs, long val);
  public static void write8(int ptr, long val);
}

This class contains methods for linking to dynamic-link libraries (DLLs). All methods in the DllLib class are static; therefore, you do not need to instantiate this class to use its methods. The methods and fields of the DllLib class provide support for Microsoft® J/Direct™ technology.

J/Direct allows you to specify the auto modifier with the @dll.import directive to call the optimal version of a DLL function, depending on the platform you are using. To find out what version is optimal for your platform, you can examine the systemDefaultCharSize field. This field is set to 1 for ANSI system, and 2 for Unicode systems.

There are several DllLib methods that help you read and write from raw pointers returned by DLL functions. You can use the ptrToStruct method, which casts a raw pointer to a structure, to cast the raw pointer to a reference to a class declared with @dll.struct. For an example that illustrates this technique, see the Raw Pointers section of the J/Direct article.

There are other situations where the ptrToStruct method can be helpful. Since there is no direct support for pointers inside structures, you could represent a structure with an embedded pointer by declaring the pointer field as type int and calling DLL functions to allocate the memory. Then you can call ptrToStruct to map the memory blocks onto @dll.struct classes so that you can initialize the blocks.

The DllLib methods, ptrToStringAnsi, ptrToStringUni, and ptrToString, are used to convert a string to a java.lang.String object when you want to treat a raw pointer as a pointer to a string. The following example shows how you can interpret a raw pointer as a pointer to a Unicode string.

import com.ms.dll.*;

int rawPtr = ...;  // value of rawPtr is returned by a DLL function
String s = DllLib.ptrToStringUni(rawPtr);

The addrOf method can be used to get the address of a callback. For instance, when you want to embed a callback inside a structure, you would call the com.ms.dll.Root.alloc method to wrap the Callback in a root handle. Next, you would pass the root handle to the addrOf method to obtain native address of the callback. Then, you can store the address as an integer.

The getLastWin32Error method helps you obtain the error code set by a DLL function. For an example that shows how to do this, see the Error Code section of the J/Direct article.

The copy methods in DllLib allow you to copy data between various types of Java arrays and raw pointers. You could use these methods to read or write data from raw pointers returned by DLL functions.

Methods

addrOf

public static int addrOf(int root);

Returns the address of a native structure wrapped by an @dll.struct object.

Note To use this method, you must first call the Root.alloc method to wrap the object in a root handle. Then, pass the root handle to the addrOf method. This extra step is required because of the garbage-collected nature of Java. (If the addrOf method took an object directly, there would be nothing to prevent the object from being reclaimed by garbage collection before the returned address could be used.)

Return Value:

Returns the address of the native structure.

Parameter | Description
root | A root handle obtained by calling Root.alloc.

Exceptions:

SecurityException if called by an untrusted applet.

allocCoTaskMem

public static int allocCoTaskMem(int cb);

Allocates a native memory block by invoking the Win32 function CoTaskMemAlloc.

Return Value:

Returns a pointer to the allocated block.

Parameter | Description
cb | The required size of the memory block (in bytes).

Exceptions:

OutOfMemoryError if allocation fails.

allocHGlobal

public static int allocHGlobal(int cb);

Allocates a native memory block using GlobalAlloc (GMEM_FIXED).

Return Value:

Returns a pointer to the allocated block.

Parameter | Description
cb | The required size of the memory block (in bytes).

Exceptions:

OutOfMemoryError if allocation fails.

copy

public static void copy(byte jasrc[], int elemidx, int pdst, int nelems);

Copies a number of bytes from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy bytes from.
elemidx | The offset that indicates the location in the Java array where the first byte to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of bytes to copy.

copy

public static void copy(char jasrc[], int elemidx, int pdst, int nelems);

Copies a number of characters from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the characters from.
elemidx | The offset that indicates the location in the Java array where the first character to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of characters to copy.

copy

public static void copy(short jasrc[], int elemidx, int pdst, int nelems);

Copies a number of short integers from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the short integers from.
elemidx | The offset that indicates the location in the Java array where the first short integer to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of short integers to copy.

copy

public static void copy(int jasrc[], int elemidx, int pdst, int nelems);

Copies a number of integers from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the integers from.
elemidx | The offset that indicates the location in the Java array where the first integer to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of integers to copy.

copy

public static void copy(long jasrc[], int elemidx, int pdst, int nelems);

Copies a number of long integers from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the long integers from.
elemidx | The offset that indicates the location in the Java array where the first long integer to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of long integers to copy.

copy

public static void copy(float jasrc[], int elemidx, int pdst, int nelems);

Copies 32-bit floating-point numbers from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the floating-point numbers from.
elemidx | The offset that indicates the location in the Java array where the first floating-point number to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of floating-point numbers to copy.

copy

public static void copy(double jasrc[], int elemidx, int pdst, int nelems);

Copies 64-bit floating-point numbers (doubles) from a Java array to the destination indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
jasrc | The Java array to copy the doubles from.
elemidx | The offset that indicates the location in the Java array where the first double to be copied is located.
pdst | A raw pointer to the destination of the copy.
nelems | The number of doubles to copy.

copy

public static void copy(Object jasrc, int ofs, int pdst, int cb);

Copies a native structure to the destination indicated by a raw native pointer. The Java object that represents the native structure must have been declared using the @dll.struct compiler directive.

Return Value:

No return value.

Parameter | Description
jasrc | The native structure to copy from.
ofs | The offset that indicates where in the object the first byte to copy is located.
pdst | A raw pointer to the destination of the copy.
cb | The number of bytes to copy.

copy

public static void copy(int psrc, byte jadst[], int elemidx, int nelems);

Copies a number of bytes to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the bytes to.
elemidx | The offset that indicates the location in the Java array where the first byte is copied to.
nelems | The number of bytes to copy.

copy

public static void copy(int psrc, char jadst[], int elemidx, int nelems);

Copies a number of characters to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the characters to.
elemidx | The offset that indicates the location in the Java array where the first character is copied to.
nelems | The number of characters to copy.

copy

public static void copy(int psrc, short jadst[], int elemidx, int nelems);

Copies a number of short integers to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the short integers to.
elemidx | The offset that indicates the location in the Java array where the first short integer is copied to.
nelems | The number of short integers to copy.

copy

public static void copy(int psrc, int jadst[], int elemidx, int nelems);

Copies a number of integers to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the integers to.
elemidx | The offset that indicates the location in the Java array where the first integer is copied to.
nelems | The number of integers to copy.

copy

public static void copy(int psrc, long jadst[], int elemidx, int nelems);

Copies a number of long integers to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the long integers to.
elemidx | The offset that indicates the location in the Java array where the first long integer is copied to.
nelems | The number of long integers to copy.

copy

public static void copy(int psrc, float jadst[], int elemidx, int nelems);

Copies 32-bit floating-point numbers to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the floats to.
elemidx | The offset that indicates the location in the Java array where the first floating-point number is copied to.
nelems | The number of floats to copy.

copy

public static void copy(int psrc, double jadst[], int elemidx, int nelems);

Copies 64-bit floating-point numbers (doubles) to a Java array from the source indicated by a raw native pointer. This copy method is range-checked.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The Java array to copy the doubles to.
elemidx | The offset that indicates the location in the Java array where the first double is copied to.
nelems | The number of doubles to copy.

copy

public static void copy(int psrc, Object jadst, int ofs, int cb);

Copies a number of bytes to a native structure from the source indicated by a raw native pointer. The Java object that represents the native structure must be declared using the @dll.struct compiler directive.

Return Value:

No return value.

Parameter | Description
psrc | A raw pointer to the source of the copy.
jadst | The native structure to copy to.
ofs | The offset that indicates the location in the object where the first byte is copied to.
cb | The number of bytes to copy.

freeCoTaskMem

public static void freeCoTaskMem(int ptr);

Frees a native memory block by invoking the Win32 function CoTaskMemFree. Any global memory handle that has a zero high-order word is safely ignored.

Return Value:

No return value.

Parameter | Description
ptr | The memory block to free.

freeHGlobal

public static void freeHGlobal(int hglobal);

Frees a native memory block by invoking the Win32 function GlobalFree. Any global memory handle that has a zero high-order word is safely ignored.

Return Value:

No return value.

Parameter | Description
hglobal | The global memory handle to free.

getLastWin32Error

public static final int getLastWin32Error();

Returns the Microsoft® Win32® error code set by the last DLL-imported method (declared with the setLastError modifier) invoked on the current thread.

Note Only DLL methods declared with the setLastError modifier can set error codes.

Return Value:

Returns the last saved Win32 error code.

isStruct

public static boolean isStruct(Class structCls);

Determines whether a class represents a native structure.

Return Value:

Returns true if the class represents a native structure; otherwise, returns false.

Parameter | Description
structCls | The class to examine.

isStruct

public native static boolean isStruct(Field structField);

Determines whether a field represents a field in a native structure.

Return Value:

Returns true if the field represents a field in a native structure; otherwise, returns false.

Parameter | Description
structField | The field to examine.

numParamBytes

public static int numParamBytes(Method m);

Prelinks the specified method and returns the number of bytes of memory required to store the method's parameters.

Return Value:

Returns the number of bytes of memory required to store the method's parameters.

Parameter | Description
m | The method to be prelinked.

offsetOf

public native static int offsetOf(Field structField);

Returns the offset (measured in bytes) of a member of a native structure. The class, which is represented by structField.getClass, must have been declared using the @dll.struct compiler directive (or @com.struct).

Note The getClass method is from the java.lang.Object class.

Return Value:

Returns the size of the native structure (in bytes).

Parameter | Description
structField | The field to obtain the offset of.

offsetOf

public static int offsetOf(Class structCls, String fieldName)
        throws SecurityException;

Returns the offset (measured in bytes) of a member of a native structure. The class, which is represented by structCls, must have been declared using the @dll.struct compiler directive (or @com.struct).

Return Value:

Returns the size of the native structure in bytes.

Parameter | Description
structCls | The class declared by using @dll.struct.
fieldName | The name of the field to examine.

Exceptions:

SecurityException if the caller lacks permissions to use the java.lang.reflect API.

prelink

public static native void prelink(Method method);

Preloads the native library and performs a type analysis on an @dll.import method to ensure that the types are compatible with DLL calling. If this method is called multiple times on the same method (or on a method that does not link to a DLL), the call is safely ignored.

Return Value:

No return value.

Parameter | Description
method | The method to prelink.

Remarks:

This work is normally performed on the first call to the @dll.import method. The prelink method can be used to force the type analysis to be done before the first call to the @dll.import method. This can help with performance tuning, debugging, or both.

prelinkAll

public static void prelinkAll(Class cls);

Calls the prelink method on all methods of a class. This method is provided primarily for debugging purposes because it can expose errors in DLL-linked methods.

Return Value:

No return value.

Parameter | Description
cls | The class to prelink.

ptrToString

public static String ptrToString(int ptr);

Converts a native string to a java.lang.String object. The native string is assumed to be in ANSI format if the auto mode is ANSI; otherwise, Unicode format is assumed. A string that has the high-order word set to zero is allowed and is converted to null.

Return Value:

Returns the Java string that represents the native string.

Parameter | Description
ptr | The native string to convert.

ptrToStringAnsi

public static String ptrToStringAnsi(int ptr);

Converts a native string in ANSI format to a java.lang.String object. A string that has the high-order word set to zero is legal and is converted to null.

Return Value:

Returns the Java string that represents the native string.

Parameter | Description
ptr | The string pointer to convert.

ptrToStringUni

public static String ptrToStringUni(int ptr);

Converts a native string in Unicode format to a java.lang.String object. A string that has the high-order word set to zero is legal and is converted to null.

Return Value:

Returns the Java string that represents the native string.

Parameter | Description
ptr | The string pointer to convert.

ptrToStruct

public static Object ptrToStruct(Class structClass, int ptr);

Maps a raw pointer onto a structure. This method simulates a C-style cast of an arbitrary pointer to a structure.

Return Value:

Returns an instance of structClass.

Parameter | Description
structClass | The structure to map the raw pointer to. This class must have been declared using @dll.struct.
ptr | The raw pointer to be mapped.

read1

public static native byte read1(Object ptr, int ofs);

Reads one byte of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the byte that is read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read1

public static native byte read1(int ptr, int ofs);

Reads one byte of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the byte that is read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read1

public static byte read1(int ptr);

Reads a byte from a specified memory location.

Return Value:

Returns the byte that is read.

Parameter | Description
ptr | The address in memory where the byte to be read is located.

read2

public static native short read2(Object ptr, int ofs);

Reads two bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read2

public static native short read2(int ptr, int ofs);

Reads two bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read2

public static short read2(int ptr);

Reads a short integer from a specified memory location.

Return Value:

Returns the short integer that is read.

Parameter | Description
ptr | The address in memory where the short integer to be read is located.

read4

public static native int read4(Object ptr, int ofs);

Reads four bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read4

public static native int read4(int ptr, int ofs);

Reads four bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read4

public static int read4(int ptr);

Reads an integer from a specified memory location.

Return Value:

Returns the integer that is read.

Parameter | Description
ptr | The address in memory where the integer to be read is located.

read8

public static native long read8(Object ptr, int ofs);

Reads eight bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read8

public static native long read8(int ptr, int ofs);

Reads eight bytes of data from the memory location that is specified by a base address and an offset.

Return Value:

Returns the bytes that are read.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.

read8

public static long read8(int ptr);

Reads a long integer from a specified memory location.

Return Value:

Returns the long integer that is read.

Parameter | Description
ptr | The address in memory where the long integer to be read is located.

release

public static native void release(Object o);

This method frees the native memory associated with an object declared using the @dll.struct compiler directive, if that memory would normally have been released by garbage collection. If the object is not declared using @dll.struct, or if the native memory associated with the object is not owned by the garbage-collector, this method does nothing.

Return Value:

No return value.

Parameter | Description
o | The object to be freed.

resize

public native static void resize(Object structObj, int newsize);

Reallocates the native memory block represented by an object declared using the @dll.struct directive. The object must have been created by executing "new" from Java (as opposed to being created to wrap an external pointer). The new block will preserve the contents of the old block as much as possible. If the new block is larger than the old block, the remaining portion will be zero-initialized.

This method is normally invoked from a constructor and can be used to implement structures that vary in size.

Return Value:

No return value.

Parameter | Description
structObj | The structure to resize.
newsize | The new size (in bytes).

sizeOf

public static int sizeOf(Class structCls);

Returns the size in bytes of the native structure represented by the specified class. The class must have been declared using the @dll.struct compiler directive (or @com.struct).

Return Value:

Returns the size of the native structure (in bytes).

Parameter | Description
structCls | The class to examine.

sizeOf

public native static int sizeOf(Object structObj);

Returns the size in bytes of an instance of a J/Direct structure. You can use this method to declare a self-describing structure that will be used in a DLL call, as in the following example.

/** @dll.struct() */
class STARTUPINFO
{
  public int cb = DllLib.sizeOf(this);
  public int lpReserved;
  public int lpDesktop;
  ...
}

// now you can use an instance of STARTUPINFO in a DLL call

Return Value:

Returns the size of the object.

Parameter | Description
structObj | The object whose size is being determined.

stringToCoTaskMem

public static int stringToCoTaskMem(String s);

Copies a string into a native memory block by using either ANSI or Unicode format depending on the auto mode setting. The memory block is allocated by using the Win32 function CoTaskMemAlloc.

Return Value:

Returns a pointer to the block that contains the string in the specified format.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeCoTaskMem method to release the block from Java.

Important Note:

On Windows NT, if you use the stringToCoTaskMem method with the Comctl32.ListView_InsertColumn function, you may not get the results you expect. Instead, you should use the stringToCoTaskMemAnsi method as shown in the following example.

lvc1.pszText = DllLib.stringToCoTaskMemAnsi("C Column"); // Notice the Ansi suffix
int1 = Comctl32.ListView_InsertColumn(hWindLV1, 1, lvc1);

stringToCoTaskMemAnsi

public static int stringToCoTaskMemAnsi(String s);

Copies a string into a native memory block in ANSI format. The memory block is allocated by using the Win32 function CoTaskMemAlloc.

Return Value:

Returns a pointer to the block that contains the specified string in ANSI format.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeCoTaskMem method to release the block from Java.

stringToCoTaskMemUni

public static int stringToCoTaskMemUni(String s);

Copies a string into a native memory block in Unicode format. The memory block is allocated by using the Win32 function CoTaskMemAlloc.

Return Value:

Returns a pointer to the block that contains the specified string in Unicode format.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeCoTaskMem method to release the block from Java.

stringToHGlobal

public static int stringToHGlobal(String s);

Copies a string into a native memory block, using either ANSI or Unicode format, depending on the auto mode setting. The memory block is allocated by using GlobalAlloc (GMEM_FIXED).

Return Value:

Returns a pointer to the block that contains the specified string.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeHGlobal method to release the block from Java.

stringToHGlobalAnsi

public static int stringToHGlobalAnsi(String s);

Copies a string into a native memory block in ANSI format. The memory block is allocated by using GlobalAlloc (GMEM_FIXED).

Return Value:

Returns a pointer to the block that contains the specified string in ANSI format.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeHGlobal method to release the block from Java.

stringToHGlobalUni

public static int stringToHGlobalUni(String s);

Copies a string into a native memory block in Unicode format. The memory block is allocated by using GlobalAlloc (GMEM_FIXED).

Return Value:

Returns a pointer to the block that contains the specified string in Unicode format.

Parameter | Description
s | The string to copy.

Remarks:

You can use the freeHGlobal method to release the block from Java.

throwWin32Exception

public static final void throwWin32Exception();

Throws a Win32Exception using the error code set by the last DLL-imported method (declared with the setLastError modifier) that is invoked on the current thread.

Note Only DLL methods declared with the setLastError modifier can set error codes.

Return Value:

No return value.

write1

public static native void write1(Object ptr, int ofs, byte val);

Writes one byte of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write1

public static native void write1(int ptr, int ofs, byte val);

Writes one byte of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write1

public static void write1(int ptr, byte val);

Writes a byte to the specified memory location.

Return Value:

No return value.

Parameter | Description
ptr | The address in memory where the byte will be written.
val | The value to write.

write2

public static native void write2(Object ptr, int ofs, short val);

Writes two bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write2

public static native void write2(int ptr, int ofs, short val);

Writes two bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write2

public static void write2(int ptr, short val);

Writes a short integer to the specified memory location.

Return Value:

No return value.

Parameter | Description
ptr | The address in memory where the short integer will be written.
val | The value to write.

write2

public static native void write2(Object ptr, int ofs, char val);

Writes two bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write2

public static native void write2(int ptr, int ofs, char val);

Writes two bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write2

public static void write2(int ptr, char val);

Writes a character to the specified memory location.

Return Value:

No return value.

Parameter | Description
ptr | The address in memory where the character will be written.
val | The value to write.

write4

public static native void write4(Object ptr, int ofs, int val);

Writes four bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write4

public static native void write4(int ptr, int ofs, int val);

Writes four bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write4

public static void write4(int ptr, int val);

Writes an integer to the specified memory location.

Return Value:

No return value.

Parameter | Description
ptr | The address in memory where the integer will be written.
val | The value to write.

write8

public static native void write8(Object ptr, int ofs, long val);

Writes eight bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write8

public static native void write8(int ptr, int ofs, long val);

Writes eight bytes of data to the memory location that is specified by a base address and an offset.

Return Value:

No return value.

Parameter | Description
ptr | The base address to write to.
ofs | The offset from the base address.
val | The value to write.

write8

public static void write8(int ptr, long val);

Writes a long integer to the specified memory location.

Return Value:

No return value.

Parameter | Description
ptr | The address in memory where the long integer will be written.
val | The value to write.

Fields

systemDefaultCharSize
Contains the preferred character size of the host system (1 for ANSI, 2 for Unicode). The value of this class variable indicates the mode that a DLL-imported method will link in when the auto modifier is used with the @dll.import compiler directive.


Class ParameterCountMismatchError

public class ParameterCountMismatchError extends RuntimeException
{
  // Constructors
  public ParameterCountMismatchError();
  public ParameterCountMismatchError(int expected, int passed);
}

This class represents objects that contain the number of parameters expected and the number of objects actually passed to a method. ParameterCountMismatchError objects are thrown by the Microsoft VM under debugging mode if a function called with Microsoft® J/Direct™ accepts fewer or more parameters than was passed in. For more information on using J/Direct, see the About J/Direct article.

RuntimeException
  |
  +--ParameterCountMismatchError

Constructors

ParameterCountMismatchError

public ParameterCountMismatchError();

Constructs a ParameterCountMismatchError object.

ParameterCountMismatchError

public ParameterCountMismatchError(int expected, int passed);

Constructs a ParameterCountMismatchError object from the number of parameters passed and the number of parameters expected.

Parameter | Description
expected | The number of parameters expected.
passed | The number of parameters actually passed.


Class Root

public class Root
{
  // Methods
  public static int alloc(Object object);
  public static void free(int root);
  public static Object get(int root);
}

This class allows you to create an opaque 32-bit root handle to any Java object. A root handle prevents the contained Java object from being reclaimed by garbage collection, so that the Java object can be safely stored in native data structures. This technique is valuable when using DLL functions that take callback parameters.

For example, when a callback will be used across function calls, you need to protect the Callback object from being reclaimed. You should wrap the Callback inside a root handle and then explicitly free the root handle when you no longer need the Callback.

Suppose you have declared a class called EnumWindowsProc that extends Callback and that will be used across function calls. To protect an instance of this class from garbage collection, you could write the following code.

EnumWindowsProc MyCallback = new EnumWindowsProc;
int rootHandle = Root.alloc(MyCallback);
// use the Callback across function calls
// until you're done
Root.free(rootHandle);

For more information about declaring and invoking DLL functions that take callbacks, see the Callbacks section of the Microsoft® J/Direct™ article.

Methods

alloc

public static int alloc(Object object);

Creates a new root handle.

Note Root handles require explicit deallocation using the free method. The object will not be reclaimed by the garbage collector until the free method is called.

Return Value:

Returns a new root handle that protects the object from garbage collection.

Parameter | Description
object | The object that the root handle is created for.

free

public static void free(int root);

Releases a root handle.

Return Value:

No return value.

Parameter | Description
root | The handle to release.

get

public static Object get(int root);

Extracts the Java object protected by a root handle.

Return Value:

Returns the Java object protected by the root handle.

Parameter | Description
root | The handle to dereference.


Class Win32Exception

public class Win32Exception extends RuntimeException
{
  // Constructors
  public Win32Exception(int errorcode);
  public Win32Exception(int errorcode, String message);

  // Methods
  public int getErrorCode();
  public static String getErrorDescription(int errorcode);
}

This class provides access to objects that contain error codes and error descriptions for errors set by Microsoft® Win32® functions. To set an error code, a Win32 function must be imported using the @dll.import directive with the setLastError modifier. This modifier tells the Microsoft Win32 VM for Java to capture the error code immediately after invoking the method. To retrieve the error code, you can invoke the com.ms.dll.dllLib.getLastWin32Error method.

Suppose you have imported the Win32 function FindClose, which returns status information through the error code. You can call the FindClose method, retrieve the error code, and wrap the error code in a Win32Exception object as shown by the following example.

import com.ms.dll.*;

boolean successful = FindClose(hFindFile);
if (!successful) {
      Win32Exception e =
        new Win32Exception(DllLib.getLastWin32Error());
}

Note You cannot reliably retrieve error codes by using the Win32 function GetLastError. This is because the Microsoft VM, while executing function calls of its own, might overwrite the error code before you retrieve it.

To learn how to import DLL functions such as FindClose, see the Syntax for @dll.import section of the Microsoft® J/Direct™ article.

RuntimeException
  |
  +--Win32Exception

Constructors

Win32Exception

public Win32Exception(int errorcode);

Creates a Win32Exception object initialized with an error code.

Parameter | Description
errorcode | The error code.

Win32Exception

public Win32Exception(int errorcode, String message);

Creates a Win32Exception object initialized with an error code and an error description.

Parameter | Description
errorcode | The error code.
message | The error description.

Methods

getErrorCode

public int getErrorCode();

Retrieves the error code associated with the Win32Exception object.

Return Value:

Returns the error code associated with the Win32Exception object.

getErrorDescription

public static String getErrorDescription(int errorcode);

Retrieves the error description associated with a Win32 error code.

Return Value:

Returns the error description.

Parameter | Description
errorcode | The error code.


About com.ms.io

The com.ms.io package contains a variety of classes that provide access to specialized input and output operations. You can use the classes in the com.ms.io package to manipulate path strings (Path), create file dialog boxes (UserFileDialog), resolve a class with a non-system class loader (ObjectInputStreamWithLoader), and read and write from specialized input streams.

The following table lists the classes in com.ms.io that represent input and output streams:
Class | Basic Functionality
IntArrayOutputStream | An output stream for primitive integers.
SystemInputStream | An input stream that can be handed to untrusted code.
SystemOutputStream | An output stream that can be handed to untrusted code.
OffsetInputStreamFilter | A filter input stream that keeps track of the byte offset into the stream.

Example

The following code sample opens a file using a file dialog box and then writes an array of bytes to the file.

import com.ms.io.UserFileDialog;
import java.io.FileOutputStream;
import java.awt.Frame;

public class MySample
{
  // parent represents the container of the dialog box
  public void dbOpen(Frame parent, byte[] buffer){
    UserFileDialog db = new UserFileDialog(parent,"Open a File");
    FileOutputStream stream = db.openFileForWriting();
    try{
      stream.write(buffer);
    }
    catch(IOException e) {
      System.out.println("I/O error occurred.");
    }
  }
}

Classes

Class IntArrayOutputStream
This class provides methods that create and manipulate output streams for primitive integers.
Class ObjectInputStreamWithLoader
This class provides methods that allow a class to be resolved by using an existing ClassLoader instance instead of the system class loader.
Class OffsetInputStreamFilter
This class represents a filter input stream that keeps track of the byte offset into the stream.
Class Path
This class provides methods for checking and manipulating strings that represent paths.
Class SystemInputStream
This class provides methods that allow an application to hand an input stream to untrusted code and prevent the untrusted code from closing it.
Class SystemOutputStream
This class provides methods that allow an application to hand an output stream to untrusted code and prevent the untrusted code from closing it.
Class UserFileDialog
This class provides methods for creating and displaying dialog boxes that can open files for reading, writing, and random access.

Hierarchy

Object
  |
  +--Path
  |
  +--UserFileDialog

OutputStream
  |
  +--IntArrayOutputStream (Cloneable)

ObjectInputStream
  |
  +--ObjectInputStreamWithLoader

FilterInputStream
  |
  +--OffsetInputStreamFilter
  |
  +--SystemInputStream

FilterOutputStream
  |
  +--SystemOutputStream


Class IntArrayOutputStream

public class IntArrayOutputStream extends java.io.OutputStream
             implements Cloneable
{
  // Constructors
  public IntArrayOutputStream ();
  public IntArrayOutputStream (int size);
  public IntArrayOutputStream (int[] stuff);

  // Methods
  public synchronized void append (int n);
  public synchronized void appendTo (IntArrayOutputStream out);
  public synchronized void appendTo (IntArrayOutputStream out,
        int s, int len);
  public synchronized int capacity ();
  public IntArrayOutputStream copy ();
  public synchronized int copyInto (int[] dest);
  public synchronized int elementAt (int ofs);
  public synchronized int elementFromEnd (int ofs);
  public synchronized int ensureCapacity (int capacity);
  public int[] getIntArray ();
  public synchronized void getInts (int[] dest, int s, int len);
  public synchronized void insertElements (int ofs, int n);
  public boolean isEmpty ();
  public synchronized void putElement (int ofs, int value);
  public synchronized int reduceCapacity (int capacity);
  public synchronized void removeElements (int ofs, int n);
  public void reset ();
  public synchronized void setIntArray (int[] array);
  public synchronized void shrinkToFit ();
  public int size ();
  public synchronized int[] toIntArray ();
  public String toString ();
  public synchronized void truncate (int newsize);
  public void write (int[] src);
  public void write (int b) throws IOException;
  public synchronized void write (int[] src, int s, int len);
}

This class provides methods that create and manipulate output streams for primitive integers.

OutputStream
  |
  +--IntArrayOutputStream

Constructors

IntArrayOutputStream

public IntArrayOutputStream ();

Creates an IntArrayOutputStream object that can hold 16 integers.

IntArrayOutputStream

public IntArrayOutputStream (int size);

Creates an IntArrayOutputStream object that can hold the specified number of integers.

Parameter | Description
size | The number of integers that the output stream can hold.

IntArrayOutputStream

public IntArrayOutputStream (int[] stuff);

Creates an IntArrayOutputStream object initialized with integer values.

Parameter | Description
stuff | The initial values for the output stream.

Methods

append

public synchronized void append (int n);

Appends an integer to the output stream.

Return Value:

No return value.

Parameter | Description
n | The value to append to the output stream.

appendTo

public synchronized void appendTo (IntArrayOutputStream out);

Appends the contents of the output stream onto another IntArrayOutputStream.

Return Value:

No return value.

Parameter | Description
out | The output stream to append the stream to.

appendTo

public synchronized void appendTo (IntArrayOutputStream out, int s,
        int len);

Appends integers from this output stream onto another IntArrayOutputStream, beginning at a specified offset in this output stream.

Return Value:

No return value.

Parameter | Description
out | The output stream to append the integers to.
s | The offset in this output stream where the first integer to append is located.
len | The number of integers in this output stream to append.

Exceptions:

ArrayIndexOutOfBoundsException if the offset is negative, or if the specified number of integers to append exceeds the amount available from the specified offset.

capacity

public synchronized int capacity ();

Retrieves the maximum number of integers that the IntArrayOutputStream object can hold.

Return Value:

Returns the maximum capacity of the output stream.

copy

public IntArrayOutputStream copy ();

Creates a deep copy of the output stream.

Return Value:

Returns the copy of the output stream.

copyInto

public synchronized int copyInto (int[] dest);

Copies the contents of the output stream into an array of integers.

Return Value:

Returns the number of elements copied.

Parameter | Description
dest | The destination array that the output stream is copied into.

elementAt

public synchronized int elementAt (int ofs);

Retrieves an element from the output stream at a specified offset.

Return Value:

Returns the value of the retrieved element.

Parameter | Description
ofs | The offset in the output stream where the element to retrieve is located.

elementFromEnd

public synchronized int elementFromEnd (int ofs);

Retrieves an element from the output stream at a specified offset, relative to the end of the stream.

Return Value:

Returns the value of the retrieved element.

Parameter | Description
ofs | The offset from the end of the output stream where the element to retrieve is located.

ensureCapacity

public synchronized int ensureCapacity (int capacity);

Ensures that the IntArrayOutputStream object has enough storage capacity for the specified number of integers. If current capacity exceeds the specified capacity, the current capacity remains unchanged.

Return Value:

Returns the actual capacity of the output stream.

Parameter | Description
capacity | The minimum required capacity of the output stream.

getIntArray

public int[] getIntArray ();

Retrieves the array of integers represented by the IntArrayOutputStream object.

Return Value:

Returns the array of integers represented by the output stream.

getInts

public synchronized void getInts (int[] dest, int s, int len);

Copies integers from the output stream to an array. The first integer copied is located at the beginning of the stream; it is copied to the specified offset in the array.

Return Value:

No return value.

Parameter | Description
dest | The array that receives the integers.
s | The offset in the array where the first integer is copied to.
len | The number of integers in the output stream to copy.

Exceptions:

ArrayIndexoutOfBoundsException if the offset is negative, if copying the integers will exceed the capacity of the array, or if the specified number of integers to append exceeds the amount available from the specified offset.

insertElements

public synchronized void insertElements (int ofs, int n);

Inserts zero-initialized elements into the IntArrayOutputStream object.

Return Value:

No return value.

Parameter | Description
ofs | The offset in the output stream where the elements are inserted.
n | The number of zero-initialized elements to insert.

isEmpty

public boolean isEmpty ();

Determines whether the IntArrayOutputStream object is empty.

Return Value:

Returns true if the output stream is empty; otherwise, returns false.

putElement

public synchronized void putElement (int ofs, int value);

Replaces an element in the output stream at a specified offset.

Return Value:

No return value.

Parameter | Description
ofs | The offset in the output stream of the element to be replaced.
value | The value for the new element.

Exceptions:

ArrayIndexOutOfBoundsException if the offset exceeds or equals the number of elements currently in the stream.

reduceCapacity

public synchronized int reduceCapacity (int capacity);

Shrinks the storage of the IntArrayOutputStream object to the requested capacity. If the requested capacity is greater than or equal to the capacity of the output stream, the capacity of the output stream remains unchanged.

Return Value:

Returns the actual capacity of the output stream.

Parameter | Description
capacity | The maximum required capacity of the output stream.

Exceptions:

ArrayIndexOutOfBoundsException if the number of integers currently in the output stream exceeds the requested capacity.

removeElements

public synchronized void removeElements (int ofs, int n);

Removes elements from the IntArrayOutputStream object.

Return Value:

No return value.

Parameter | Description
ofs | The offset in the output stream where the first element to remove is located.
n | The number of elements to remove.

reset

public void reset ();

Sets the number of integers in the IntArrayOutputStream object to zero.

Return Value:

No return value.

setIntArray

public synchronized void setIntArray (int[] array);

Sets the values of the IntArrayOutputStream object.

Return Value:

No return value.

Parameter | Description
array | The array that contains the new values.

shrinkToFit

public synchronized void shrinkToFit ();

Reduces the capacity of the IntArrayOutputStream object to the number of integers currently in the output stream.

Return Value:

No return value.

size

public int size ();

Retrieves the number of integers in the IntArrayOutputStream object.

Return Value:

Returns the number of integers in the output stream.

toIntArray

public synchronized int[] toIntArray ();

Makes a copy of the array of integers represented by the IntArrayOutputStream object.

Return Value:

Returns a copy of the integers represented by the output stream.

toString

public String toString ();

Converts the output stream to string form.

Return Value:

Returns the output stream in string form.

truncate

public synchronized void truncate (int newsize);

Decreases the number of integers in the IntArrayOutputStream object to the specified number.

Return Value:

No return value.

Parameter | Description
newsize | The number of integers that the truncated output stream will hold.

Exceptions:

ArrayIndexOutOfBoundsException if the specified number exceeds or equals the number of integers currently in the output stream.

write

public void write (int[] src);

Appends an array of integers to the output stream.

Return Value:

No return value.

Parameter | Description
src | The array of integers to append to the output stream.

write

public void write (int b) throws IOException;

Appends a byte to the output stream. This method blocks until the byte is actually written.

Return Value:

No return value.

Parameter | Description
b | The byte to append.

Exceptions:

IOException if the byte cannot be appended to the output stream.

write

public synchronized void write (int[] src, int s, int len);

Appends a number of integers from the specified array to the output stream, starting with the integer at offset s in the array.

Return Value:

No return value.

Parameter | Description
src | The array of integers to append to the output stream.
s | The offset in the array, where the first integer to append is located.
len | The number of integers to append.


Class ObjectInputStreamWithLoader

public class ObjectInputStreamWithLoader extends ObjectInputStream
{
  // Constructors
  public ObjectInputStreamWithLoader(InputStream in,
        ClassLoader loader) throws IOException,
        StreamCorruptedException;

  // Methods
  protected Class resolveClass(ObjectStreamClass classDesc)
        throws IOException, ClassNotFoundException;
}

This class provides methods that allow a class to be resolved by using an existing ClassLoader instance instead of the system class loader. It extends the java.io.ObjectInputStream class, which delegates class resolution to the java.lang.ClassLoader supplied at construction time.

ObjectInputStream
  |
  +--ObjectInputStreamWithLoader

Constructors

ObjectInputStreamWithLoader

public ObjectInputStreamWithLoader(InputStream in,
        ClassLoader loader) throws IOException, StreamCorruptedException;

Creates an ObjectInputStreamWithLoader object, using the specified input stream and class loader.

Parameter | Description
in | The input stream that is used to create the object.
loader | The existing ClassLoader instance.

Exceptions:

IllegalArgumentException if loader is null.

IOException if an error is encountered while using the underlying stream.

StreamCorruptedException if the version or magic number is incorrect.

Methods

resolveClass

protected Class resolveClass(ObjectStreamClass classDesc)
        throws IOException, ClassNotFoundException;

Instructs the class loader that is associated with the ObjectInputStreamWithLoader object to load the class indicated by the specified ObjectStreamClass object.

Return Value:

Returns the loaded class.

Parameter | Description
classDesc | The ObjectStreamClass object that indicates the class to load.

Exceptions:

ClassNotFoundException if the class to load cannot be found.

IOException if the loader encounters an error while reading the class.


Class OffsetInputStreamFilter

public class OffsetInputStreamFilter extends FilterInputStream
{
  // Constructors
  public OffsetInputStreamFilter (InputStream i);

  // Methods
  public long getOffset ();
  public void mark(int readlimit);
  public synchronized int read() throws IOException;
  public synchronized int read (byte b[], int off, int len)
        throws IOException;
  public void reset() throws IOException;
  public synchronized long skip (long n) throws IOException;
  public synchronized long skipToAlignment (int align)
        throws IOException;
}

This class represents a filter input stream that keeps track of the byte offset into the stream.

FilterInputStream
  |
  +--OffsetInputStreamFilter

Constructors

OffsetInputStreamFilter

public OffsetInputStreamFilter (InputStream i);

Creates an OffsetInputStreamFilter object from the specified input stream.

Parameter | Description
i | The input stream.

Methods

getOffset

public long getOffset ();

Retrieves the current byte offset into the input stream.

Return Value:

Returns the current byte offset into the input stream.

mark

public void mark(int readlimit);

Marks the current position in the input stream.

Return Value:

No return value.

Parameter | Description
readlimit | The number of bytes that can be read without invalidating the mark.

read

public synchronized int read() throws IOException;

Reads a single byte from the input stream.

Return Value:

Returns the byte that was read from the input stream.

Exceptions:

IOException if an error occurs while attempting to read.

read

public synchronized int read (byte b[], int off, int len)
        throws IOException;

Reads a sequence of bytes from the input stream into the buffer.

Return Value:

Returns the number of bytes read.

Parameter | Description
b | The buffer to store the bytes in.
off | The offset in the buffer where the first byte read is stored.
len | The number of bytes to read.

Exceptions:

IOException if an error occurs while attempting to read.

reset

public void reset() throws IOException;

Resets the byte offset of the input stream to the last marked position.

Return Value:

No return value.

Exceptions:

IOException if the mark is invalid or has not been set.

skip

public synchronized long skip (long n) throws IOException;

Skips a number of bytes in the input stream and updates the byte offset to reflect the new position in the stream.

Return Value:

Returns the actual number of bytes skipped.

Parameter | Description
n | The number of bytes to skip.

Exceptions:

IOException if an I/O error occurs.

skipToAlignment

public synchronized long skipToAlignment (int align) throws IOException;

Skips bytes in the input stream until the byte offset is a multiple of the alignment.

Return Value:

Returns the actual number of bytes skipped.

Parameter | Description
align | The alignment.

Exceptions:

IOException if an I/O error occurs.


Class Path

public class Path
{
  // Methods
  public static String append(String stPath1, String stPath2);
  public static String getExtension(String stPath);
  public static boolean hasExecExtensionType(String stPath);
  public static boolean isRoot(String stPath);
  public static boolean isValidFileChar (char ch);
  public static String removeBeginEndQuotes(String stPath);
  public static String removeTrailingSlash(String stPath);
  public static String validateFilename (String origfilename,
        char replch) throws IOException;
}

This class provides methods for checking and manipulating strings that represent paths.

Methods

append

public static String append(String stPath1, String stPath2);

Appends one path string to another. If necessary, a separator is inserted between the path strings.

Return Value:

Returns the string that consists of the second path appended to the first.

Parameter | Description
stPath1 | The first path.
stPath2 | The second path, which will be appended to the first path.

getExtension

public static String getExtension(String stPath);

Retrieves the extension of the filename. If there is no extension, this method returns null.

Return Value:

Returns the extension of the filename.

Parameter | Description
stPath | The path string.

hasExecExtensionType

public static boolean hasExecExtensionType(String stPath);

Determines whether the path string ends in .exe, .com, .bat, .pif, or .cmd.

Return Value:

Returns true if the path string ends in .exe, .com, .bat, .pif, or .cmd; otherwise, returns false.

Parameter | Description
stPath | The path string.

isRoot

public static boolean isRoot(String stPath);

Determines whether the path string is a root path. For example, the following strings are root paths: "\", "c:\", "\\server\", and "\\server\share".

Return Value:

Returns true if the path string is a root path; otherwise, returns false.

Parameter | Description
stPath | The path string.

isValidFileChar

public static boolean isValidFileChar (char ch);

Determines whether a character can be used in a filename.

Return Value:

Returns true if the character can be used in a filename; otherwise, returns false.

Parameter | Description
ch | The character that is checked to see if it is valid in a filename.

removeBeginEndQuotes

public static String removeBeginEndQuotes(String stPath);

Removes leading and trailing quotes from the path string, if there are any.

Return Value:

Returns the path string with quotes removed.

Parameter | Description
stPath | The path string to remove quotes from.

removeTrailingSlash

public static String removeTrailingSlash(String stPath);

Removes a trailing backslash unless the path is a root path.

Return Value:

Returns the path string without the trailing backslash. If the path is a root path, it remains unchanged.

Parameter | Description
stPath | The path string.

validateFilename

public static String validateFilename (String origfilename,
        char replch) throws IOException;

Checks a filename, and if it is not valid, attempts to correct it.

Return Value:

Returns a valid filename or the original filename, if it is already valid.

Parameter | Description
origfilename | The filename to check and correct.
replch | The character to replace invalid characters with.

Exceptions:

IOException if the filename cannot be corrected.


Class SystemInputStream

public class SystemInputStream extends FilterInputStream
{
  // Constructors
  public SystemInputStream (InputStream out, int id);

  // Methods
  public void close () throws IOException;
}

This class provides methods that allow an application to hand an input stream to untrusted code and prevent the untrusted code from closing it. System.in objects are wrapped with this class, which extends the FilterInputStream class.

FilterInputStream
  |
  +--SystemInputStream

Constructors

SystemInputStream

public SystemInputStream (InputStream out, int id);

Creates a SystemInputStream object by using the specified input stream and an identifier. The identifier will be used for security checks.

Parameter | Description
out | The input stream.
id | The identifier for the new SystemInputStream object.

Methods

close

public void close () throws IOException;

Closes the system input stream.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurs while attempting to close the output stream.


Class SystemOutputStream

public class SystemOutputStream extends FilterOutputStream
{
  // Constructors
  public SystemOutputStream (OutputStream out, int id);

  // Methods
  public void close () throws IOException;
  public void write(byte b[], int off, int len) throws IOException;
}

This class provides methods that allow an application to hand an output stream to untrusted code and prevent the untrusted code from closing it. System.out and System.err objects are wrapped with this class, which extends the FilterOutputStream class.

FilterOutputStream
  |
  +--SystemOutputStream

Constructors

SystemOutputStream

public SystemOutputStream (OutputStream out, int id);

Creates a SystemOutputStream object by using the specified output stream and an identifier. The identifier will be used for security checks.

Parameter | Description
out | The output stream.
id | The identifier for the new SystemOutputStream object.

Methods

close

public void close () throws IOException;

Closes the system output stream.

Return Value:

No return value.

Exceptions:

IOException if an error occurs while attempting to close the output stream.

write

public void write(byte b[], int off, int len) throws IOException;

Writes bytes to the output stream from an array, starting at a specified offset in the array.

Return Value:

No return value.

Parameter | Description
b | The array to write from.
off | The offset in the array, where the first byte to write is located.
len | The number of bytes to write.

Exceptions:

IOException if an error occurs while attempting to write to the output stream.


Class UserFileDialog

public final class UserFileDialog
{
  // Constructors
  public UserFileDialog(Frame parent,String title);

  // Methods
  public String getFileName();
  public synchronized FileInputStream openFileForReading()
        throws IOException;
  public synchronized FileOutputStream openFileForWriting()
        throws IOException;
  public synchronized RandomAccessFile openRandomAccessFile(
        String mode) throws IOException;
}

This class provides methods for creating and displaying dialog boxes that can open files for reading, writing, and random access.

Constructors

UserFileDialog

public UserFileDialog(Frame parent,String title);

Creates a UserFileDialog object that represents a file dialog box. After creating the UserFileDialog object, you can use one of the following methods to display the dialog box and open a file:

  • openFileForReading
  • openFileForWriting
  • openRandomAccessFile.

Parameter | Description
parent | The owner of the file dialog box.
title | The title of the file dialog box.

Methods

getFileName

public String getFileName();

Retrieves the name of the last file opened with a dialog box if a successful file open operation has been performed with the dialog box. This method returns null if the dialog box has never been used to open a file or if the last attempt to open a file with the dialog box failed for any reason.

Return Value:

Returns the name of the last file successfully opened with this dialog box; returns null if the last attempt failed or if the dialog box has never been used to open a file.

openFileForReading

public synchronized FileInputStream openFileForReading() throws IOException;

Displays a dialog box that allows the user to open a file for reading. If the user selects a file, then a FileInputStream object for that file is returned. If the user cancels the dialog box, null is returned. To determine the name of the file that was opened, you can use the getFileName method.

Return Value:

Returns a FileInputStream object if the user selects a file or returns null if the user cancels the dialog box.

Exceptions:

SecurityException if the caller does not have permission to initiate user-directed file I/O.

IOException if an I/O error occurs while attempting to open the file.

openFileForWriting

public synchronized FileOutputStream openFileForWriting()
        throws IOException;

Displays a dialog box that allows the user to open a file for writing. If the user selects a file, then a FileOutputStream object for that file is returned. If the user cancels the dialog box, null is returned. To determine the name of the file that was opened, you can use the getFileName method.

Return Value:

Returns a FileOutputStream object if the user selects a file or returns null if the user cancels the dialog box.

Exceptions:

SecurityException if the caller does not have permission to initiate user-directed file I/O.

IOException if an I/O error occurs while attempting to open the file.

openRandomAccessFile

public synchronized RandomAccessFile openRandomAccessFile(
        String mode) throws IOException;

Displays a dialog box that allows the user to open a file for random access. If the user selects a file, then a FileInputStream object for that file is returned. If the user cancels the dialog box, null is returned. To determine the name of the file that was opened, you can use the getFileName method.

Return Value:

Returns a RandomAccessFile object if the user selects a file or returns null if the user cancels the dialog box.

Parameter | Description
mode | The mode to open the file in. If mode is "r", the file is opened in read-only mode. If mode is "rw", the file is opened in read-write mode.

Exceptions:

IllegalArgumentException if the mode argument is not equal to "r" or to "rw".

SecurityException if the caller does not have permission to initiate user-directed file I/O.

IOException if an I/O error occurs while attempting to open the file.


About com.ms.io.clientstorage

The com.ms.io.clientstorage package contains classes that manage and enforce storage limitations for principals. The three classes in this package work together to keep track of the available storage, allocate storage, and allow information about the files to be retrieved. These classes can be used to allocate scratch space for an applet on the client's computer.

Scratch space is unshared persistent storage that is available only to the signer of the applet that created the storage. If an applet is unsigned, it can obtain and use scratch space if it runs from the class path or from a fully trusted zone. The amount of scratch space and its location on the client computer is managed by the Microsoft Win32 VM for Java so that it cannot be used maliciously. Scratch space is sometimes used to store configuration information for applets that are re-used.

Overview of Classes

The ClientStorageManager class keeps track of all client stores. You can use the ClientStorageManager class to obtain the store for a specified principal, open a shared store, or get the store for the currently executing principal. You can open a file for reading or writing with a specified type of accessibility. This is the class that you use to obtain scratch space for your applet.

The ClientStore class provides access to individual client stores and enforces storage limitations. This class includes methods that allow you to delete a file, create directories, rename a file, get the length of a file, list the files in a directory, and determine whether a file exists. You can also use the ClientStore class to open a file for reading or writing (as you can with the ClientStorageManager class). The methods in this class allow you to create files and directories and obtain other information about files within your applet's scratch space.

The ClientStoreFile class manages individual files within client stores. Using the methods in this class, you can delete a file, rename it, make a directory for it, determine whether you can read from the file, get the absolute or canonical path for the file, and retrieve other information about a file. This class provides methods for manipulating an individual file within your applet's scratch space.

The following table describes the accessibility flags used to open files in the com.ms.io.clientstorage package.

Flag Name | Accessibility Type
STORE_FL_ROAMING | The file is accessible to the user from any computer.
STORE_FL_LOCAL | The file is found in a computer-specific local storage area.
OPEN_FL_SHARED | The file is accessible to the user and to other authorized principals.
OPEN_FL_APPEND | When writing to a file, append to the file if it exists; otherwise, open a new file for writing.
OPEN_FL_EXPENDABLE | When the storage area is full, the file is automatically deleted if the deletion will help satisfy a new request.
OPEN_FL_WRITABLE | The file is opened with write access.

Example

The following example uses the com.ms.io.clientstorage package to create a client store (scratch space) for an applet, write to a file called myFile.txt, and print a list of files in the current directory.

import com.ms.io.clientstorage.*;
import java.io.OutputStream;
import java.io.IOException;
import java.applet.*;

public class MySample extends Applet{

  public void outputToScratch() throws IOException {

    ClientStore s = ClientStorageManager.getStore();

    s.createDirectory("myDirectory");

    ClientStoreFile oneFile =
       new ClientStoreFile(s,"MyFile.txt");

    long x = oneFile.length();

    OutputStream stream1 = oneFile.openOutputStream();

    byte buffer1[] = {1,2,3,4,5};
    stream1.write(buffer1);
    stream1.close();

    OutputStream appendStream = s.openWritable("myFile.txt",true);
    byte buffer2[] = {11,12,13,14,15};
    appendStream.write(buffer2);
    appendStream.close();

    String fileList[] = s.listFiles(".", ClientStore.LIST_FL_RECURSE);
    for (int i = 0; i < fileList.length; i++)  {
       System.out.println(fileList[i]);
    }

    s.deleteFile("secondFile.txt");
  }
}

After compiling the MySample applet, you would place the compiled file into a cabinet file. You would then sign the file using the signcode tool, specifying a level of security that permits access to client storage.

Classes

Class ClientStorageManager
This class manages the allocation of client stores.
Class ClientStore
This class helps manage client storage by enforcing storage limitations and providing access to client stores.
Class ClientStoreFile
This class manages and provides access to individual files within client stores.

Hierarchy

Object
  |
  +--ClientStorageManager
  |
  +--ClientStore

File
  |
  +--ClientStoreFile


Class ClientStorageManager

public class ClientStorageManager
{
  // Methods
  public static ClientStorageManager getStorageManager ();
  public static ClientStore getStore () throws IOException;
  public ClientStore getStoreForPrincipal (Principal principal,
        ClientStoragePermission data) throws IOException;
  public ClientStore getStoreFromContext () throws IOException;
  public static RandomAccessFile openRandom (String stgfilename,
        boolean writable) throws IOException;
  public static RandomAccessFile openRandom (
        String stgfilename) throws IOException;
  public static RandomAccessFile openRandom (String stgfilename,
        int flags) throws IOException;
  public static InputStream openReadable (String stgfilename,
        int flags) throws IOException;
  public static InputStream openReadable (
        String stgfilename) throws IOException;
  public static OutputStream openWritable (String stgfilename,
        int flags) throws IOException;
  public static OutputStream openWritable (
        String stgfilename) throws IOException;
  public static OutputStream openWritable (String stgfilename,
        boolean append) throws IOException;
}

This class manages the allocation of client stores. The methods of the ClientStorageManager class enable you to obtain the store for a specified principal, get the shared store, or obtain the store for the currently executing principal. You can also open a file for reading or writing, and specify flags that determine the accessibility type. Enforcement of storage limitations for each principal is performed by the ClientStore class.

Methods

getStorageManager

public static ClientStorageManager getStorageManager ();

Obtains the global storage manager.

Return Value:

Returns the global storage manager.

getStore

public static ClientStore getStore () throws IOException;

Obtains the store for the currently executing principal.

Return Value:

Returns the store for the currently executing principal.

Exceptions:

IOException if the context cannot be determined, if no caller has a principal, or if the store for the context does not exist and an error occurs while allocating space for the store.

getStoreForPrincipal

public ClientStore getStoreForPrincipal (Principal principal,
        ClientStoragePermission data) throws IOException;

Retrieves a principal's store.

Return Value:

Returns a store for the specified principal.

Parameter | Description
principal | The principal to obtain the store for.
data | The default data to give to the principal if the principal does not have a store.

Exceptions:

IOException if an error occurs while allocating space for the store.

getStoreFromContext

public ClientStore getStoreFromContext () throws IOException;

Obtains the store for the currently executing principal. This method scans the current call stack to find the store for the last non-system principal.

Return Value:

Returns the store for the currently executing principal.

Exceptions:

IOException if the context cannot be determined, if no caller has a principal, or if the store for the context does not exist and an error occurs while allocating space for the store.

SecurityException if the caller does not have permission to access the store.

openRandom

public static RandomAccessFile openRandom (String stgfilename,
        boolean writable) throws IOException;

Opens a RandomAccessFile from the store for read or write operations.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.
writable | Set this value to true if the file should be opened as OPEN_FL_WRITABLE; otherwise, set this value to false.

Exceptions:

IOException if the method fails to open the specified file.

openRandom

public static RandomAccessFile openRandom (String stgfilename)
        throws IOException;

Opens a RandomAccessFile from the store for read operations, with no specified flags.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.

Exceptions:

IOException if the method fails to open the specified file.

openRandom

public static RandomAccessFile openRandom (String stgfilename,
        int flags) throws IOException;

Opens a RandomAccessFile from the store for read or write operations.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.
flags A value that indicates the requested type of file accessibility. It can be any combination of the following accessibilities:
  • OPEN_FL_SHARED
  • OPEN_FL_EXPENDABLE
  • OPEN_FL_WRITABLE
  • STORE_FL_ROAMING
  • STORE_FL_LOCAL

Exceptions:

IOException if the method fails to create or open the specified file.

openReadable

public static InputStream openReadable (String stgfilename,
        int flags) throws IOException;

Opens a file for reading from the store for the current principal.

Return Value:

Returns the file that is open for reading.

Parameter | Description
stgfilename | The name of the file to open.
flags | A value that indicates the requested type of file accessibility. It can be any combination of the flags OPEN_FL_SHARED, STORE_FL_ROAMING, or STORE_FL_LOCAL from the ClientStore class.

Exceptions:

IOException if the file does not exist or cannot be opened.

openReadable

public static InputStream openReadable (String stgfilename)
        throws IOException;

Opens a file for reading from the store for the current principal.

Return Value:

Returns the file that is open for reading.

Parameter | Description
stgfilename | The name of the file to open.

Exceptions:

IOException if the file does not exist or cannot be opened.

openWritable

public static OutputStream openWritable (String stgfilename,
        int flags) throws IOException;

Opens a file for writing from the store for the current principal. If the file already exists, it is truncated unless the ClientStore.OPEN_FL_APPEND flag is provided.

Return Value:

Returns the output stream that is open for writing.

Parameter | Description
stgfilename | The name of the file to open for writing.
flags | A value that indicates the requested type of file accessibility. This value can be any combination of the flags OPEN_FL_APPEND, OPEN_FL_SHARED, STORE_FL_ROAMING, or STORE_FL_LOCAL from the ClientStore class.

Exceptions:

IOException if the file could not be created or truncated.

openWritable

public static OutputStream openWritable (String stgfilename)
        throws IOException;

Opens a file for writing from the store for the current principal. If the file already exists, it is truncated.

Return Value:

Returns the file that is open for writing.

Parameter | Description
stgfilename | The name of the storage file to open.

Exceptions:

IOException if the file could not be created or truncated.

openWritable

public static OutputStream openWritable (String stgfilename,
        boolean append) throws IOException;

Opens a file for writing from the store for the current principal. If the file already exists, it is truncated or appended.

Return Value:

Returns the file that is open for writing.

Parameter | Description
stgfilename | The name of the storage file to open.
append | The value that indicates whether to append to an existing file. If the value is true, append to the existing file; otherwise, do not append.

Exceptions:

IOException if the file could not be created or truncated.


Class ClientStore

public class ClientStore
{
  // Fields
  public static final int LIST_FL_NO_DIRECTORIES;
  public static final int LIST_FL_NO_FILES;
  public static final int LIST_FL_RECURSE;
  public static final int OPEN_FL_APPEND;
  public static final int OPEN_FL_EXPENDABLE;
  public static final int OPEN_FL_SHARED;
  public static final int OPEN_FL_WRITABLE;
  public static final int STORE_FL_LOCAL;
  public static final int STORE_FL_ROAMING;

  // Methods
  public boolean canAccessRoamingFiles ();
  public void copyFile (String curstgfilename,
        String newstgfilename) throws IOException;
  public void copyFile (String curstgfilename, int curflags, String
        newstgfilename, int newflags) throws IOException;
  public void createDirectories (String stgdirpath)
        throws IOException;
  public void createDirectories (String stgdirpath,
        int flags) throws IOException;
  public void createDirectory (String stgdirname)
        throws IOException;
  public void createDirectory (String stgdirname, int flags) throws
        IOException;
  public void deleteDirectory (String stgfilename)
        throws IOException;
  public void deleteDirectory (String stgfilename,
        int flags) throws IOException;
  public void deleteFile (String stgfilename) throws IOException;
  public void deleteFile (String stgfilename, int flags)
        throws IOException;
  public boolean equals (Object o);
  public boolean fileExists (String stgfilename) throws IOException;
  public boolean fileExists (String stgfilename, int flags)
        throws IOException;
  protected void finalize ();
  public String getCurrentDirectory ();
  public long getFileSize (String stgfilename) throws IOException;
  public long getFileSize (String stgfilename, int flags)
        throws IOException;
  public long getLastModificationTime (String stgfilename)
        throws IOException;
  public long getLastModificationTime (String stgfilename,
        int flags) throws IOException;
  public long getStorageLimit ();
  public long getStorageRemaining ();
  public long getStorageUsed ();
  public long getStorageUsed (int flags);
  public boolean isDirectory (String stgfilename)
        throws IOException;
  public boolean isDirectory (String stgfilename, int flags) throws
        IOException;
  public boolean isExpendable (String stgfilename)
        throws IOException;
  public boolean isExpendable (String stgfilename,
        int flags) throws IOException;
  public boolean isFile (String stgfilename) throws IOException;
  public boolean isFile (String stgfilename, int flags)
        throws IOException;
  public String[] listFiles (String stgdir) throws IOException;
  public String[] listFiles (String stgdir,
        FilenameFilter filter) throws IOException;
  public String[] listFiles (String stgdir, int flags)
        throws IOException;
  public String[] listFiles (String stgdir, FilenameFilter filter,
        int flags) throws IOException;
  public void markFileAsExpendable (String stgfilename,
        boolean deletewhenfull) throws IOException;
  public void markFileAsExpendable (String stgfilename, int flags,
        boolean deletewhenfull) throws IOException;
  public RandomAccessFile openRandom (String stgfilename,
        boolean writable) throws IOException;
  public RandomAccessFile openRandom (String stgfilename,
        int flags) throws IOException;
  public RandomAccessFile openRandom (String stgfilename)
        throws IOException;
  public InputStream openReadable (String stgfilename,
        int flags) throws IOException;
  public InputStream openReadable (String stgfilename)
        throws IOException;
  public OutputStream openWritable (String stgfilename,
        int flags) throws IOException;
  public OutputStream openWritable (String stgfilename)
        throws IOException;
  public OutputStream openWritable (String stgfilename,
        boolean append) throws IOException;
  public boolean purgeExpendableFiles (long spacerequired,
        int flags) throws IOException;
  public boolean purgeExpendableFiles (long spacerequired)
        throws IOException;
  public boolean purgeExpendableFiles () throws IOException;
  public void renameFile (String curstgfilename,
        String newstgfilename) throws IOException;
  public void renameFile (String curstgfilename, int curflags,
        String newstgfilename, int newflags) throws IOException;
  public void setCurrentDirectory (String newcurdir)
        throws IOException;
  public void setStorageLimit (long newlimit) throws IOException;
}

This class helps manage client storage by enforcing storage limitations and providing access to client stores. It includes methods for creating directories, renaming files, getting a list of files in a directory, deleting files, and reading or writing to a file.

Methods

canAccessRoamingFiles

public boolean canAccessRoamingFiles ();

Determines whether the principal can access roaming files.

Return Value:

Returns true if the principal can access roaming files; otherwise, returns false.

copyFile

public void copyFile (String curstgfilename, String newstgfilename)
        throws IOException;

Copies the contents of an existing file to a new file, with the same flags set.

Return Value:

No return value.

Parameter | Description
curstgfilename | The name of the file to copy from.
newstgfilename | The name of the newly created file.

Exceptions:

IOException if either one or the other filename is not valid, if curstgfilename cannot be found, or if either filename is a directory.

copyFile

public void copyFile (String curstgfilename, int curflags,
        String newstgfilename, int newflags) throws IOException;

Copies the contents of an existing file to a new file, with the same flags set.

Return Value:

No return value.

Parameter | Description
curstgfilename | The name of the file to copy from.
curflags | A value that indicates the storage area in which to find curstgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.
newstgfilename | The name of the newly created file.
newflags The new flags that are set for the file. This value should be some combination of the following:
  • STORE_FL_LOCAL
  • STORE_FL_ROAMING
  • OPEN_FL_EXPENDABLE

Exceptions:

IOException if either one or the other filename is not valid, if curstgfilename cannot be found, or if either filename is a directory.

createDirectories

public void createDirectories (String stgdirpath) throws IOException;

Ensures that the specified directory path exists. Missing path components are created if they do not exist.

Return Value:

No return value.

Parameter | Description
stgdirpath | The path of the directory to create.

Exceptions:

IOException if the directory already exists or if the directory name already exists as a file.

createDirectories

public void createDirectories (String stgdirpath, int flags)
        throws IOException;

Ensures that the specified directory path exists. Missing path components are created if they do not exist.

Return Value:

No return value.

Parameter | Description
stgdirpath | The name of the directory to create.
flags | A value that indicates the storage area in which to create the components of stgdirpath. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the directory already exists or the directory name already exists as a file.

createDirectory

public void createDirectory (String stgdirname) throws IOException;

Creates a new directory.

Return Value:

No return value.

Parameter | Description
stgdirname | The name of the directory to create.

Exceptions:

IOException if the directory already exists or if the directory name already exists as a file.

createDirectory

public void createDirectory (String stgdirname, int flags)
        throws IOException;

Creates a new directory.

Return Value:

No return value.

Parameter | Description
stgdirname | The name of the directory to create.
flags | A value that indicates the storage area in which to create stgdirname. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the directory already exists or the directory name already exists as a file.

deleteDirectory

public void deleteDirectory (String stgfilename) throws IOException;

Deletes the specified directory.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the directory to delete.

Exceptions:

IOException if the directory name is not valid.

deleteDirectory

public void deleteDirectory (String stgfilename, int flags)
        throws IOException;

Deletes a specified directory.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the directory to delete.
flags | A value that indicates the storage area from which to delete stgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the directory name is not valid.

deleteFile

public void deleteFile (String stgfilename) throws IOException;

Deletes the specified file.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the file to delete.

Exceptions:

IOException if there is an error while attempting to delete the file.

deleteFile

public void deleteFile (String stgfilename, int flags) throws IOException;

Deletes the specified file.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the file to delete.
flags | A value that indicates the storage area in which to delete stgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if there is an error while attempting to delete the file.

equals

public boolean equals (Object o);

Determines whether the current object is equal to the specified object.

Return Value:

Returns true if the objects are equal; otherwise, returns false.

Parameter | Description
o | The object that the current object is being compared against.

fileExists

public boolean fileExists (String stgfilename) throws IOException;

Determines whether the specified file exists.

Return Value:

Returns true if the file exists; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file whose existence is being determined.

Exceptions:

IOException if the specified file is a directory.

fileExists

public boolean fileExists (String stgfilename, int flags)
        throws IOException;

Determines whether the specified file exists.

Return Value:

Returns true if the file exists; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file whose existence is being determined.
flags | A value that indicates the storage area in which to search for stgfilename. This value should be one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

finalize

protected void finalize ();

Performs any necessary cleanup before garbage collection.

Return Value:

No return value.

getCurrentDirectory

public String getCurrentDirectory ();

Gets the current directory in the store.

Return Value:

Returns the name of the current directory.

getFileSize

public long getFileSize (String stgfilename) throws IOException;

Retrieves the size of the specified file, measured in bytes.

Return Value:

Returns the size of the file, in bytes.

Parameter | Description
stgfilename | The name of the file whose size is being measured.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

getFileSize

public long getFileSize (String stgfilename, int flags) throws IOException;

Retrieves the size of the specified file, in bytes.

Return Value:

Returns the size of the file, in bytes.

Parameter | Description
stgfilename | The name of the file whose size is being measured.
flags | A value that indicates the storage area in which to search for stgfilename. It can one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the filename is not valid or the file cannot be found.

getLastModificationTime

public long getLastModificationTime (String stgfilename) throws IOException;

Retrieves the time that the specified file was last modified.

Caution The return value is system-dependent and should only be used to compare with values returned by lastModified. It should not be interpreted as an absolute time.

Return Value:

Returns the time that the file specified by this object was last modified.

Parameter | Description
stgfilename | The name of the file whose last modification time is being retrieved.

Exceptions:

IOException if the filename is invalid or if the file does not exist.

getLastModificationTime

public long getLastModificationTime (String stgfilename, int flags)
        throws IOException;

Retrieves the time that the specified file was last modified.

Caution The return value is system-dependent and should only be used to compare with values returned by lastModified. It should not be interpreted as an absolute time.

Return Value:

Returns the time that the file specified by this object was last modified,

Parameter | Description
stgfilename | The name of the file whose last modification time is being retrieved.
flags | A value that indicates the storage area in which to search for stgfilename. It can be one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the filename is invalid or if the file does not exist.

getStorageLimit

public long getStorageLimit ();

Retrieves the amount of storage space allocated to the principal.

Return Value:

Returns the amount of storage space allocated to the principal, in bytes.

getStorageRemaining

public long getStorageRemaining ();

Retrieves the principal's remaining storage.

Return Value:

Returns the principal's remaining storage, in bytes.

getStorageUsed

public long getStorageUsed ();

Retrieves the amount of storage space the principal has used.

Return Value:

Returns the amount of space used, in bytes.

getStorageUsed

public long getStorageUsed (int flags);

Retrieves the amount of storage space the principal has used.

Return Value:

Returns the amount of space used, in bytes.

Parameter | Description
flags | A value that indicates the storage area in which to find the space used for. It can be one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

isDirectory

public boolean isDirectory (String stgfilename) throws IOException;

Determines whether the specified file is a directory.

Return Value:

Returns true if the file is a directory; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

isDirectory

public boolean isDirectory (String stgfilename, int flags)
        throws IOException;

Determines whether the specified file is a directory.

Return Value:

Returns true if the file is a directory; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file.
flags | A value that indicates the storage area in which to search for stgfilename. It can be one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

isExpendable

public boolean isExpendable (String stgfilename) throws IOException;

Determines whether the specified file can be deleted when the client storage becomes full.

Return Value:

Returns true if the file was opened with the OPEN_FL_EXPENDABLE flag.

Parameter | Description
stgfilename | The name of the file to check.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

See Also: OPEN_FL_EXPENDABLE, markFileAsExpendable, purgeExpendableFiles

isExpendable

public boolean isExpendable (String stgfilename, int flags)
        throws IOException;

Determines whether the specified file can be deleted when the client storage becomes full.

Return Value:

Returns true if the file was opened with the OPEN_FL_EXPENDABLE flag.

Parameter | Description
stgfilename | The name of the file to check.
flags | A value that indicates the storage area in which to search for stgfilename. It can be any combination of STORE_FL_LOCAL and STORE_FL_ROAMING.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

isFile

public boolean isFile (String stgfilename) throws IOException;

Determines whether the specified file is a "normal" file. A file is normal if it is not a directory and if it satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

Return Value:

Returns true if the file is normal; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file.

isFile

public boolean isFile (String stgfilename, int flags) throws IOException;

Determines whether the specified file is a "normal" file. A file is normal if it is not a directory and if it satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

Return Value:

Returns true if the file is normal; otherwise, returns false.

Parameter | Description
stgfilename | The name of the file.
flags | A value that indicates the storage area in which to search for stgfilename. It can be one or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if the filename is not valid or if the file cannot be found.

listFiles

public String[] listFiles (String stgdir) throws IOException;

Lists files in the specified directory.

Return Value:

Returns the names of the files in the specified directory.

Parameter | Description
stgdir | The directory to list files in. If null, the current directory is used.

Exceptions:

IOException if the specified directory is not valid.

listFiles

public String[] listFiles (String stgdir, FilenameFilter filter)
        throws IOException;

Lists files in the specified directory.

Parameter | Description
stgdir | The directory to list files in. If null, the current directory is used.
filter | The filter that determines which files to list. File patterns, such as "*.txt", can be specified by using the com.ms.util.WildcardExpression class.

Exceptions:

IOException if the specified directory is not valid.

listFiles

public String[] listFiles (String stgdir, int flags) throws IOException;

Lists files in the specified directory.

Return Value:

Returns a String list of the files in the directory.

Parameter | Description
stgdir | The directory to list files in. If null, the current directory is used.
flags | The listing modifiers for this method. This value should be one or more of LIST_FL_RECURSE and LIST_FL_NO_DIRECTORIES to control the listing behavior, and one or more of STORE_FL_LOCAL and STORE_FL_ROAMING to select the storage area to list files in.

Exceptions:

IOException if the specified directory is invalid.

listFiles

public String[] listFiles (String stgdir, FilenameFilter filter, int flags)
        throws IOException;

Lists files in the specified directory.

Return Value:

Returns a String list of the files in the directory.

Parameter | Description
stgdir | The directory to list files in. If null, the current directory is used.
filter | The filter that determines which files to list. File patterns, such as "*.txt," can be specified by using the com.ms.util.WildcardExpression class.
flags | The listing modifiers for this method. This value should be one or more of LIST_FL_RECURSE and LIST_FL_NO_DIRECTORIES to control the listing behavior, and one or more of STORE_FL_LOCAL and STORE_FL_ROAMING to select the storage area to list files in.

Exceptions:

IOException if the directory is invalid.

markFileAsExpendable

public void markFileAsExpendable (String stgfilename,
        boolean deletewhenfull) throws IOException;

Marks the specified file so that it is automatically deleted when the storage area is full.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the file to mark.
deletewhenfull | Set this value to true if the the file is to be deleted when the client storage area is full; otherwise, set this value to false.

Exceptions:

IOException if the filename is not valid, if the file cannot be found, or if the filename specifies a directory.

See Also: OPEN_FL_EXPENDABLE

markFileAsExpendable

public void markFileAsExpendable (String stgfilename, int flags,
        boolean deletewhenfull) throws IOException;

Marks the specified file so that it is automatically deleted when the storage area is full.

Return Value:

No return value.

Parameter | Description
stgfilename | The name of the file to mark.
flags | A value that indicates the storage area from which to delete stgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.
deletewhenfull | Set this value to true if the file is to be deleted when the client storage area is full; otherwise, set this value to false.

Exceptions:

IOException if the filename is not valid, if the file cannot be found, or if the filename specifies a directory.

See Also: OPEN_FL_EXPENDABLE

openRandom

public RandomAccessFile openRandom (String stgfilename,
        boolean writable) throws IOException;

Opens a RandomAccessFile from the store for read or write operations.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.
writable | Set this value to true if the file is to be opened as OPEN_FL_WRITABLE; otherwise, set this value to false.

Exceptions:

IOException if the method fails to create or open the specified file.

openRandom

public RandomAccessFile openRandom (String stgfilename, int flags)
        throws IOException;

Opens a RandomAccessFile from the store for read or write operations.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.
flags A value that indicates the requested type of file accessibility. It can be any combination of the following accessibilities:
  • STORE_FL_LOCAL
  • STORE_FL_ROAMING
  • OPEN_FL_EXPENDABLE
  • OPEN_FL_WRITABLE
  • OPEN_FL_SHARED

Exceptions:

IOException if the method fails to create or open the specified file.

openRandom

public RandomAccessFile openRandom (String stgfilename) throws IOException;

Opens a RandomAccessFile from the store for read operations, with no specified flags.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
stgfilename | The name of the file to open.

Exceptions:

IOException if the method fails to open the specified file.

openReadable

public InputStream openReadable (String stgfilename, int flags)
        throws IOException;

Opens an existing file for reading.

Return Value:

Returns the input stream that is open for reading.

Parameter | Description
stgfilename | The name of the file to open for reading.
flags | A value that indicates the requested type of file accessibility. It can be one or both of STORE_FL_ROAMING and STORE_FL_LOCAL.

Exceptions:

IOException if the method fails to create the file or if there is an error while attempting to truncate an existing file.

openReadable

public InputStream openReadable (String stgfilename) throws IOException;

Opens an existing file for reading.

Return Value:

Returns the input stream that is open for reading.

Parameter | Description
stgfilename | The name of the file to open for reading.

Exceptions:

IOException if the method fails to create the file or if there is an error while attempting to truncate an existing file.

openWritable

public OutputStream openWritable (String stgfilename, int flags)
        throws IOException;

Opens a file for writing. If the file already exists, it is truncated unless the OPEN_FL_APPEND flag is provided.

Return Value:

Returns the output stream that is open for writing.

Parameter | Description
stgfilename | The name of the file to open for writing.
flags A value that indicates the requested type of file accessibility. It can be any combination of the following accessibilities.
  • OPEN_FL_SHARED
  • STORE_FL_ROAMING
  • OPEN_FL_APPEND
  • OPEN_FL_EXPENDABLE
  • OPEN_FL_WRITABLE
  • STORE_FL_LOCAL

Exceptions:

IOException if the method fails to create the file or if there is an error while attempting to truncate an existing file.

openWritable

public OutputStream openWritable (String stgfilename) throws IOException;

Opens a file for writing. If the file already exists, it is truncated.

Return Value:

Returns the output stream that is open for writing.

Parameter | Description
stgfilename | The name of the file to open for writing.

Exceptions:

IOException if the method fails to create the file or if there is an error while attempting to truncate an existing file.

openWritable

public OutputStream openWritable (String stgfilename,
        boolean append) throws IOException;

Opens a file for writing. If the file already exists, it is truncated or appended, depending on the value of append.

Return Value:

Returns the output stream that is open for writing.

Parameter | Description
stgfilename | The storage file to open.
append | The value that determines whether to append to an existing file. If true, appends to an existing file; otherwise, truncates an existing file.

Exceptions:

IOException if the file could not be created or truncated.

purgeExpendableFiles

public boolean purgeExpendableFiles (long spacerequired, int flags)
        throws IOException;

Searches for files that are marked as expendable. If files are found and the total space used by the found files exceeds spacerequired, the found files are deleted. A file can be marked expendable by using the markFileAsExpendable method or by creating the file with the OPEN_FL_EXPENDABLE flag.

Return Value:

Returns true if files were deleted; otherwise, returns false.

Parameter | Description
spacerequired | The number of bytes needed. If spacerequired is set to 0, all the files marked as expendable are deleted.
flags | A value that indicates the storage area from which to delete stgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.

Exceptions:

IOException if an error occurs while deleting the files.

purgeExpendableFiles

public boolean purgeExpendableFiles (long spacerequired) throws IOException;

Searches for files that are marked as expendable. If files are found and the total space used by the found files exceeds spacerequired, the found files are deleted. A file can be marked expendable by using the markFileAsExpendable method or by creating the file with the OPEN_FL_EXPENDABLE flag.

Return Value:

Returns true if files were deleted; otherwise, returns false.

Parameter | Description
spacerequired | The number of bytes needed. If spacerequired is set to 0, all the files found are deleted.

Exceptions:

IOException if an error occurs while deleting the files.

purgeExpendableFiles

public boolean purgeExpendableFiles () throws IOException;

Deletes all files that are marked as expendable. Files are marked expendable by using the markFileAsExpendable method or by creating them with the OPEN_FL_EXPENDABLE flag.

Return Value:

Returns true if files were deleted; otherwise, returns false.

Exceptions:

IOException if an error occurs while deleting the files.

renameFile

public void renameFile (String curstgfilename,
        String newstgfilename) throws IOException;

Gives an existing file a new name, possibly moving it to a new directory.

Return Value:

No return value.

Parameter | Description
curstgfilename | The file to rename.
newstgfilename | The new name of the file.

Exceptions:

IOException if one of the following is true:

  • Either one or the other filename is not valid.
  • The source file cannot be found.
  • The source filename is a directory and the destination is a file.
  • The source filename is a file and the destination is a directory.

renameFile

public void renameFile (String curstgfilename, int curflags,
        String newstgfilename, int newflags) throws IOException;

Renames and assigns new flags to an existing file.

Return Value:

No return value.

Parameter | Description
curstgfilename | The file to rename.
curflags | A value that indicates the storage area in which to find curstgfilename. It can be either or both of the STORE_FL_LOCAL and STORE_FL_ROAMING flags.
newstgfilename | The new name of the file.
newflags The new flags that are set for the file. This value can be any combination of the following:
  • STORE_FL_LOCAL
  • STORE_FL_ROAMING
  • OPEN_FL_EXPENDABLE

Exceptions:

IOException if any one of the following is true:

  • Either one or the other filename is not valid.
  • The source file cannot be found.
  • The source filename is a directory.
  • The destination is a file.
  • The source filename is a file and the destination is a directory.

setCurrentDirectory

public void setCurrentDirectory (String newcurdir) throws IOException;

Sets the current directory in the store.

Return Value:

No return value.

Parameter | Description
newcurdir | The new current directory.

Exceptions:

IOException if the specified directory is not valid.

setStorageLimit

public void setStorageLimit (long newlimit) throws IOException;

Sets the amount of storage space allocated to the principal. All callers of this method must be fully trusted.

Return Value:

No return value.

Parameter | Description
newlimit | The amount of space allocated, in bytes.

Exceptions:

IOException if the new limit could not be set.

SecurityException if any caller is not fully trusted.

Fields

LIST_FL_NO_DIRECTORIES
Indicates that list operations do not include directories.
LIST_FL_NO_FILES
Indicates that list operations do not include files.
LIST_FL_RECURSE
Indicates that list operations find files recursively. When used in conjunction with a filter, the directory will be recursed only if the filter returns true.
OPEN_FL_APPEND
Indicates a type of accessibility for a file that is opened with the openWritable method. If the file already exists, it will be appended. If the file does not exist, a new file is opened for writing.
OPEN_FL_EXPENDABLE
Indicates a type of accessibility for a file that is automatically deleted when the storage area is full, if deleting the file will help satisfy a request for opening a new file.
OPEN_FL_SHARED
Indicates a type of accessibility for a file that is opened with the openWritable or the openReadable method. Opening the file with this accessibility type makes the file accessible to other principals co-signed or otherwise authorized by the owning principal.
OPEN_FL_WRITABLE
Indicates a type of accessibility for a file that is opened with the openRandom method. The file is opened with write access.
STORE_FL_LOCAL
Indicates a type of accessibility for a file that is manipulated by various other methods. If this type of accessibility is specified, the file must be found in a computer-specific local storage area.
STORE_FL_ROAMING
Indicates a type of accessibility for a file that is opened with the openWritable or openReadable method. Opening a file with this accessibility type makes the file accessible to the user from any computer that the user logs on to. The file that is opened will be added to the user's profile.


Class ClientStoreFile

public class ClientStoreFile extends File
{
  // Constructors
  public ClientStoreFile (String stgfilename) throws IOException;
  public ClientStoreFile (ClientStore store,
        String stgfilename) throws IOException;
  public ClientStoreFile (String stgfilename, int flags)
        throws IOException;
  public ClientStoreFile (ClientStore store, String stgfilename,
        int flags) throws IOException;

  // Methods
  public boolean canRead ();
  public boolean canWrite ();
  public boolean delete ();
  public boolean equals (Object obj);
  public boolean exists ();
  public String getAbsolutePath();
  public String getCanonicalPath() throws IOException;
  public boolean isAbsolute ();
  public boolean isDirectory ();
  public boolean isFile ();
  public long lastModified ();
  public long length ();
  public String[] list ();
  public String[] list (FilenameFilter filter);
  public boolean mkdir ();
  public boolean mkdirs ();
  public InputStream openInputStream () throws IOException;
  public OutputStream openOutputStream () throws IOException;
  public OutputStream openOutputStream (boolean append)
        throws IOException;
  public RandomAccessFile openRandom () throws IOException;
  public RandomAccessFile openRandom (boolean writable)
        throws IOException;
  public boolean renameTo (File dest);
}

This class manages and provides access to individual files within client stores. Using the methods in this class, you can delete a file, rename it, make a directory for it, determine whether you can read from the file, get the absolute or canonical path for the file, and retrieve other file characteristics.

This class extends the java.io.File class and uses the java.io.File.getPath method to retrieve the pathfor the ClientStoreFile object.

File
  |
  +--ClientStoreFile

Constructors

ClientStoreFile

public ClientStoreFile (String stgfilename) throws IOException;

Creates a ClientStoreFile object from the specified filename.

Return Value:

Returns the ClientStoreFile object that represents the specified file.

Parameter | Description
stgfilename | The name of the file.

Exceptions:

IOException if there is an I/O error.

ClientStoreFile

public ClientStoreFile (ClientStore store, String stgfilename)
        throws IOException;

Creates a ClientStoreFile object from the filename and the ClientStore object that the file is located in.

Return Value:

Returns the ClientStoreFile object representing the file that is located in the client store.

Parameter | Description
store | The client store that contains the specified file.
stgfilename | The name of the file.

Exceptions:

IOException if there is an I/O error.

ClientStoreFile

public ClientStoreFile (String stgfilename, int flags) throws IOException;

Creates a ClientStoreFile object from the filename and any specified file flags.

Return Value:

Returns the ClientStoreFile object representing the file that is located in the client store.

Parameter | Description
stgfilename | The name of the file.
flags The flags that can be used with any of the file operations in this class. They can be any combination of the following:
  • OPEN_FL_SHARED
  • STORE_FL_ROAMING
  • OPEN_FL_APPEND
  • OPEN_FL_EXPENDABLE
  • OPEN_FL_WRITABLE
  • STORE_FL_LOCAL

Exceptions:

IOException if there is an I/O error.

ClientStoreFile

public ClientStoreFile (ClientStore store, String stgfilename,
        int flags) throws IOException;

Creates a ClientStoreFile object from the filename, the ClientStore object that the file is located in, and any specified file flags.

Return Value:

Returns the ClientStoreFile object representing the file that is located in the client store.

Parameter | Description
store | The client store that contains the specified file.
stgfilename | The name of the file.
flags The flags that can be used with any of the file operations in this class. They can be any combination of the following:
  • OPEN_FL_SHARED
  • STORE_FL_ROAMING
  • OPEN_FL_APPEND
  • OPEN_FL_EXPENDABLE
  • OPEN_FL_WRITABLE
  • STORE_FL_LOCAL

Exceptions:

IOException if there is an I/O error.

Methods

canRead

public boolean canRead ();

Determines whether the application can read from the specified file.

Return Value:

Returns true if the file specified by this object exists and the application can read the file; otherwise, returns false.

canWrite

public boolean canWrite ();

Determines whether the application can write to this file.

Return Value:

Returns true if the application is allowed to write to the file whose name is specified by this object; otherwise, returns false.

delete

public boolean delete ();

Deletes the file specified by the ClientStoreFile object.

Return Value:

Returns true if the file is successfully deleted; otherwise, returns false.

equals

public boolean equals (Object obj);

Determines whether this ClientStoreFile instance is equal to another object.

Return Value:

Returns false if obj is not an instance of ClientStoreFile or if the file specified by this instance is not identical to the object specified by obj; otherwise, returns true.

Parameter | Description
obj | The object that the ClientStoreFile instance is being compared with.

exists

public boolean exists ();

Determines whether this ClientStoreFile object exists.

Return Value:

Returns true if the file specified by this object exists; otherwise, returns false.

getAbsolutePath

public String getAbsolutePath();

Retrieves the absolute path of the file represented by this object.

Return Value:

Returns an absolute path for this ClientStoreFile object.

Remarks:

If the ClientStoreFile object represents an absolute path, this method returns the path. Otherwise, it returns a path that is a concatenation of the current storage directory, the separator character, and the path of this file object.

getCanonicalPath

public String getCanonicalPath() throws IOException;

Retrieves the canonical form of this ClientStoreFile object's path. The precise definition of the canonical form is system-dependent, but it usually specifies an absolute path in which all relative references and references to the current user directory have been completely resolved. The canonical form of a path of a nonexistent file cannot be defined.

Return Value:

Returns the canonical form of the object's path.

Exceptions:

IOException if an I/O error occurs. Errors are possible because the construction of the canonical path may require file system queries.

isAbsolute

public boolean isAbsolute ();

Determines whether the file represented by this ClientStoreFile object is an absolute path.

Return Value:

Returns true if the path indicated by the ClientStoreFile object is an absolute path; otherwise, returns false.

Remarks:

The definition of an absolute pathname is system dependent. For example, on UNIX, a pathname is absolute if its first character is the separator character. On Microsoft® Windows® platforms, a pathname is absolute if its first character is an ASCII '\' or '/', or if it begins with a letter followed by a colon. This method uses the java.io.File.separator field to retrieve the separator for the file system.

isDirectory

public boolean isDirectory ();

Determines whether the file represented by this ClientStoreFile object is a directory.

Return Value:

Returns true if this ClientStoreFile object exists and is a directory; otherwise, returns false.

isFile

public boolean isFile ();

Determines whether the file represented by this ClientStoreFile object is a "normal" file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

Return Value:

Returns true if the file specified by this object exists and is a normal file; otherwise, returns false.

lastModified

public long lastModified ();

Retrieves the time that the file represented by this ClientStoreFile object was last modified.

Caution The return value is system dependent and should only be used to compare with other values returned by lastModified. It should not be interpreted as an absolute time.

Return Value:

Returns the time the file specified by this object was last modified, or 0L if the specified file does not exist.

length

public long length ();

Retrieves the length of the file represented by this ClientStoreFile object.

Return Value:

Returns the length, in bytes, of the file specified by this object, or 0L if the specified file does not exist.

list

public String[] list ();

Returns a list of the files in the directory specified by the ClientStoreFile object.

Return Value:

Returns an array that contains the names of files in the specified directory. This list does not include the current directory or the parent directory ("." and ".." on Unix systems).

list

public String[] list (FilenameFilter filter);

Retrieves a list of files that satisfy the specified filter and that are located in the directory specified by the ClientStoreFile object. The filter parameter, which is an instance of a class that implements the java.io.FilenameFilter interface, indicates the properties that the file must have to be included in the returned list of files.

Return Value:

Returns an array that contains the names of files in the specified directory. This list does not include the current directory or the parent directory ("." and ".." on Unix systems).

Parameter | Description
filter | A filename filter.

mkdir

public boolean mkdir ();

Creates a directory whose path is specified by the ClientStoreFile object.

Return Value:

Returns true if the directory could be created; otherwise, returns false.

mkdirs

public boolean mkdirs ();

Creates a directory whose path is specified by the ClientStoreFile object, including any necessary parent directories.

Return Value:

Returns true if the directory (or directories) could be created; otherwise, returns false.

openInputStream

public InputStream openInputStream () throws IOException;

Opens an input stream to the file.

Return Value:

Returns the InputStream that is open for reading.

Exceptions:

IOException if the file could not be created or truncated.

openOutputStream

public OutputStream openOutputStream () throws IOException;

Opens an output stream to the file.

Return Value:

Returns the OutputStream that is open for writing.

Exceptions:

IOException if the file could not be created or truncated.

openOutputStream

public OutputStream openOutputStream (boolean append) throws IOException;

Opens an output stream to the file, optionally appending to an existing file.

Return Value:

Returns the output stream that is open for writing.

Parameter | Description
append | The value that determines whether to append to an existing file. If true, this method appends to an existing file; otherwise, it truncates an existing file.

Exceptions:

IOException if the file could not be created or truncated.

openRandom

public RandomAccessFile openRandom () throws IOException;

Opens a RandomAccessFile from the store for read operations, with no specified flags.

Return Value:

Returns the RandomAccessFile that is opened.

Exceptions:

IOException if the method fails to open the specified file.

openRandom

public RandomAccessFile openRandom (boolean writable) throws IOException;

Opens a RandomAccessFile from the store for read or write operations, with no specified flags.

Return Value:

Returns the RandomAccessFile that is opened.

Parameter | Description
writable | Set this value to true if the file should be opened as OPEN_FL_WRITABLE; otherwise, set writable to false.

Exceptions:

IOException if the method fails to open the specified file.

renameTo

public boolean renameTo (File dest);

Renames the file specified by this ClientStoreFile object to have the path given by the File argument.

Return Value:

Returns true if the renaming succeeds; otherwise, returns false.

Parameter | Description
dest | The new filename.


About com.ms.lang

This package provides access to Microsoft® Win32® system-level support that is not available through the standard package language. The com.ms.lang package extends java.lang and supplies Java system enhancement, keyboard switching, and registry manipulation classes. The Microsoft® Windows® registry plays a key role in Windows® 95 and Windows NT® operations. It is an access-restricted database that stores many critical application and operating system values. Although many of the common registry functions, such as RegCreateKeyEx and RegOpenKeyEx, are not implemented, the Java class RegKey handles many of the same operations.

Classes

Class RegKey
The RegKey class produces Windows registry access objects.
Class RegKeyEnumValue
This class is created and returned by the RegKey.enumValue method.
Class RegKeyEnumValueByteArray
This class is created when RegKey.enumValue returns a byte array.
Class RegKeyEnumValueInt
This class is created when RegKey.enumValue returns a integer.
Class RegKeyEnumValueString
This class is created as a result of returning a string from RegKey.enumValue.
Class RegKeyException
This class signals that an I/O exception has occurred.
Class RegQueryInfo
This class queries registry access objects.
Class SystemThread
An object of the SystemThread class represents a thread that is always created in the system thread group (the highest level thread group, which has no parent).
Class SystemX
This class provides system enhancements that implement extended functionality.

Hierarchy

Object
  |
  +--RegKey
  |
  +--RegKeyEnumValue
  |  |
  |  +--RegKeyEnumValueByteArray
  |  |
  |  +--RegKeyEnumValueInt
  |  |
  |  +--RegKeyEnumValueString
  |
  +--RegQueryInfo
  |
  +--SystemX

IOException
  |
  +--RegKeyException

Thread
  |
  +--SystemThread


Class RegKey

public class RegKey
{
  // Fields
  public final static int CLASSES_ROOT;
  public final static int KEYOPEN_ALL;
  public final static int KEYOPEN_CREATE;
  public final static int KEYOPEN_READ;
  public final static int KEYOPEN_WRITE;
  public final static int LOCALMACHINE_ROOT;
  public final static int USER_ROOT;
  public final static int USERS_ROOT;

  // Constructors
  public RegKey(RegKey rkParent, String subKey, int access)
        throws RegKeyException;
  public RegKey(int rootID, String subKey, int access)
        throws RegKeyException;
  public RegKey(int rootID,String subKey) throws RegKeyException;

  // Methods
  public void close();
  public void deleteSubKey(String sub);
  public void deleteValue(String val);
  public String enumKey(int idx);
  public RegKeyEnumValue enumValue(int idx);
  public void finalize();
  public void flush();
  public byte[] getBinaryValue(String name);
  public int getIntValue(String name);
  public int getIntValue(String name, int defval);
  public final static RegKey getRootKey(int id);
  public String getStringValue(String name);
  public String getStringValue(String name,String defval);
  public void loadKey(String subKey, String fileName);
  public RegQueryInfo queryInfo();
  public void replace(String subKey, String newFile,
        String oldFile);
  public void restore( String filename, boolean vol );
  public void setValue(String subKey, String val);
  public void setValue(String subKey, byte val[]);
  public void setValue(String subKey, int val);
  public String toString();
  public void unload(String subKey);
  public RegKeyValueEnumerator values();
}

The RegKey class produces Windows registry access objects.

Constructors

RegKey

public RegKey(RegKey rkParent, String subKey, int access)
        throws RegKeyException;

Creates the specified key. If the key already exists in the Windows registry, the method opens it.

Parameter | Description
rkParent The currently open key or any of the following predefined reserved identifiers:
  • null
  • HKEY_CLASSES_ROOT,
  • HKEY_CURRENT_USER,
  • HKEY_LOCAL_MACHINE
  • HKEY_USERS

The key created is a subkey of the key identified by the rkParent parameter. If the applet is running in a browser or another protected environment, this parameter must be null.

subKey | The string specifying the name of a subkey that this method opens or creates. must be a subkey of the key identified by the rkParent parameter. This subkey must not begin with the backslash character (\). The rkParent parameter cannot be null.
access | The read-write access privileges for the key.

Exceptions:

com.ms.lang.RegKeyException if the key cannot be created.

RegKey

public RegKey(int rootID, String subKey, int access) throws RegKeyException;

A convenience constructor that performs Regkey.getRootKey automatically.

Parameter | Description
rootID | The rootID of the key.
subKey | A string specifying the name of a subkey that this method opens or creates. The subkey must not begin with the backslash character (\). The rkParent parameter cannot be null.
access | The read-write access for the key.

RegKey

public RegKey(int rootID,String subKey) throws RegKeyException;

Opens a key for reading.

Parameter | Description
rootID | The root identifier of the key.
subKey | A string specifying the name of a subkey that this method opens or creates. The subkey must not begin with the backslash character (\). This parameter cannot be null.

Methods

close

public void close();

Closes a key when it is no longer needed.

Return Value:

No return value.

Remarks:

As the system registry keys must be written out to disk, the keys must be closed when no longer needed. After this, the keys must not be used again.

deleteSubKey

public void deleteSubKey(String sub);

Removes a subkey from the key.

Return Value:

No return value.

Parameter | Description
sub | The subkey removed from the key.

Exceptions:

IOException if the subkey removal is unsuccessful.

deleteValue

public void deleteValue(String val);

Deletes a value from the key.

Parameter | Description
val | The name of the value that is deleted.

enumKey

public String enumKey(int idx);

Enumerates a key's subkeys.

Return Value:

Returns the enumeration value of the subkey by index (see RegKeyEnumValue).

Parameter | Description
idx | The enumeration index.

enumValue

public RegKeyEnumValue enumValue(int idx);

Enumerates values of the key.

Return Value:

Returns the subkey name of the subkey.

Parameter | Description
idx | The enumeration index.

finalize

public void finalize();

Frees the resources associated with a RegKey object.

Return Value:

No return value.

flush

public void flush();

Flushes the key to the registry on disk.

Return Value:

No return value.

getBinaryValue

public byte[] getBinaryValue(String name);

Queries a byte array from the registry.

Return Value:

Returns the byte array contained in the subKey.

Parameter | Description
name | The subKey containing the value requested. The name must be a subkey of the current key.

getIntValue

public int getIntValue(String name);

Queries an integer value from the registry.

Return Value:

Returns the integer value contained in the subKey.

Parameter | Description
name | The subKey containing the value wanted. The name must be a subkey of the current key.

getIntValue

public int getIntValue(String name, int defval);

Queries an integer value from the registry. The name is a subkey of the current key. If the named value does not exist in the registry, the default value is returned.

Return Value:

Returns the integer value contained in the subKey or the default value if the named value does not exist in the registry.

Parameter | Description
name | The subkey containing the value wanted.
defval | The default value.

getRootKey

public final static RegKey getRootKey(int id);

Retrieves a top-level key.

Parameter | Description
id | The identifier of the top-level key.

getStringValue

public String getStringValue(String name);

Queries a string value from the registry. The name is a subkey of the current key.

Return Value:

Returns the String value contained in the subKey.

Parameter | Description
name | The subKey containing the requested value.

getStringValue

public String getStringValue(String name,String defval);

Queries a string value from the registry. The name is a subkey of the current key. If the named value does not exist in the registry, the specified default value is returned.

Return Value:

Returns the default value if the named value does not exist in the registry. Otherwise, the method returns the string value contained in the subkey.

Parameter | Description
name | The subkey containing the requested string.
defval | The default value to return.

loadKey

public void loadKey(String subKey, String fileName);

Loads a new hive into the registry.

Return Value:

No return value.

Parameter | Description
subKey | The name of the subkey created to contain the new hive.
fileName | The name of a file that contains the registry information.

queryInfo

public RegQueryInfo queryInfo();

Retrieves information about the key.

Return Value:

Returns a RegQueryInfo object containing the information.

replace

public void replace(String subKey, String newFile, String oldFile);

Replaces the file supporting a key and all its subkeys with another file. The next time the system is started, the key and subkey values are stored in the new file.

Return Value:

No return value.

Parameter | Description
subKey | The subkey, whose values are stored in the new file.
newFile | The name of the new file.
oldFile | The name of the old file.

restore

public void restore( String filename, boolean vol );

Restores a subkey from a file.

Return Value:

No return value.

Parameter | Description
filename | The filename.
vol | The value returned is true if the hive is volatile; otherwise, the value is false.

setValue

public void setValue(String subKey, String val);

Sets a string value into a subkey.

Return Value:

No return value.

Parameter | Description
subKey | The subkey that holds the value.
val | The string that is written out.

setValue

public void setValue(String subKey, byte val[]);

Sets a byte array into a subkey.

Return Value:

No return value.

Parameter | Description
subKey | The subkey that holds the value.
val | The array that is written out.

setValue

public void setValue(String subKey, int val);

Sets an integer value into a subkey.

Return Value:

No return value.

Parameter | Description
subKey | The subkey that holds the value.
val | The integer that is written out.

toString

public String toString();

Returns a string representation of the key.

Return Value:

Returns a string containing the path information in the form: "[RegKey: <path>]".

unload

public void unload(String subKey);

Unloads a hive from the registry.

Return Value:

No return value.

Parameter | Description
subKey | The subkey that is unloaded.

values

public RegKeyValueEnumerator values();

Returns an enumeration of the subkey values of this registry key.

Return Value:

Returns a RegKeyValueEnumerator object, used to enumerate the list of subkeys.

See Also: RegKeyValueEnumerator

Fields

CLASSES_ROOT
An identifier that signifies that the HKEY_CLASSES_ROOT key must be returned.
KEYOPEN_ALL
An identifier that signifies a key must be opened for read-write access.
KEYOPEN_CREATE
An identifier that signifies a key must be created, not opened.
KEYOPEN_READ
An identifier that signifies a key must be opened for read-only access.
KEYOPEN_WRITE
An identifier that signifies a key must be opened for write access.
LOCALMACHINE_ROOT
An identifier that signifies that the HKEY_LOCAL_MACHINE key must be returned.
USER_ROOT
An identifier that signifies that the HKEY_CURRENT_USER key must be returned.
USERS_ROOT
An identifier that signifies that the HKEY_USERS key must be returned.


Class RegKeyEnumValue

public abstract class RegKeyEnumValue
{
  // Fields
  public String name;
  public final int REGTYPE_BINARY;
  public final int REGTYPE_DWORD;
  public final int REGTYPE_DWORD_BIG_ENDIAN;
  public final int REGTYPE_DWORD_LITTLE_ENDIAN;
  public final int REGTYPE_EXPAND_SZ;
  public final int REGTYPE_LINK;
  public final int REGTYPE_MULTI_SZ;
  public final int REGTYPE_NONE;
  public final int REGTYPE_RESOURCE_LIST;
  public final int REGTYPE_SZ;
  public int theType;
  public static final int TYPE_BINARY;
  public static final int TYPE_DWORD;
  public static final int TYPE_EXPAND_STRING;
  public static final int TYPE_NONE;
  public static final int TYPE_STRING;

  // Methods
  public String getName();
  public int getType();
  public boolean isBinary();
  public boolean isDword();
  public boolean isString();
}

This class is created and returned by the RegKey.enumValue method.

Methods

getName

public String getName();

Retrieves the registry name.

Return Value:

Returns the registry value name.

getType

public int getType();

Retrieves the registry type.

Return Value:

Returns the registry value type.

isBinary

public boolean isBinary();

Determines if the registry value is binary.

Return Value:

Returns true if the registry value is binary, in which case the object is the RegKeyEnumValueByteArray type; otherwise, returns false.

See Also: RegEnumValueByteArray

isDword

public boolean isDword();

Determines if the registry value is a double word value.

Return Value:

Returns true if the registry value is a double word value, in which case the object is the RegEnumValueInt type; otherwise, returns false.

See Also: RegEnumValueInt

isString

public boolean isString();

Determines if the registry value is a string.

Return Value:

Returns true if the registry value is a string, in which case the object is the RegKeyEnumValueString type; otherwise, returns false.

See Also: RegEnumValueString

Fields

name
The registry name.
REGTYPE_BINARY
Indicates that the registry type is a binary value.
REGTYPE_DWORD
Indicates that the registry type is a double word value.
REGTYPE_DWORD_BIG_ENDIAN
Indicates that the registry type is a 32-bit number in big endian format.
REGTYPE_DWORD_LITTLE_ENDIAN
Indicates that the registry type is a 32-bit number in little endian format.
REGTYPE_EXPAND_SZ
Indicates that the registry type is a string that contains unexpanded references to environment variables (for example "%PATH%").
REGTYPE_LINK
Indicates that the registry type is a link.
REGTYPE_MULTI_SZ
Indicates that the registry type is an array of null-terminated strings, terminated by two null characters.
REGTYPE_NONE
Indicates no defined value type.
REGTYPE_RESOURCE_LIST
Indicates that the registry type is a device-driver resource list.
REGTYPE_SZ
Indicates that the registry type is a string.
theType
The registry type.
TYPE_BINARY
Static alias for REGTYPE_BINARY.
TYPE_DWORD
Static alias for REGTYPE_DWORD.
TYPE_EXPAND_STRING
Static alias for REGTYPE_EXPAND_SZ.
TYPE_NONE
Static alias for REGTYPE_NONE.
TYPE_STRING
Static alias for REGTYPE_SZ.


Class RegKeyEnumValueByteArray

public class RegKeyEnumValueByteArray extends RegKeyEnumValue
{
  // Fields
  public byte value[];

  // Methods
  public byte[] getValue();
  public String toString();
}

This class is created when RegKey.enumValue returns a byte array.

RegKeyEnumValue
  |
  +--RegKeyEnumValueByteArray

Methods

getValue

public byte[] getValue();

Retrieves the binary contents of the registry value.

Return Value:

Returns the byte array.

toString

public String toString();

Retrieves a string representation of the object.

Return Value:

Returns a string with the form, "com.ms.lang.RegKeyEnumValueByteArray: name = value (type = type)"

Fields

value[]
The byte array value.


Class RegKeyEnumValueInt

public class RegKeyEnumValueInt extends RegKeyEnumValue
{
  // Fields
  public int value;

  // Methods
  public int getValue();
  public String toString();
}

This class is created when RegKey.enumValue returns a integer.

RegKeyEnumValue
  |
  +--RegKeyEnumValueInt

Methods

getValue

public int getValue();

Retrieves the double-word contents of the registry value.

Return Value:

Returns the registry value.

toString

public String toString();

Retrieves a string representation of the object.

Return Value:

Returns a string of the form, "com.ms.lang.RegKeyEnumValueInt: name = value (type = type)"

Fields

value
The integer value.


Class RegKeyEnumValueString

public class RegKeyEnumValueString extends RegKeyEnumValue
{
  // Fields
  public String value;

  // Methods
  public String getValue();
  public String toString();
}

This class is created as a result of returning a string from RegKey.enumValue.

RegKeyEnumValue
  |
  +--RegKeyEnumValueString

Methods

getValue

public String getValue();

Retrieves the string contents of this registry value.

Return Value:

Returns the registry value.

toString

public String toString();

Retrieves a string representation of the object.

Return Value:

Returns a string of the form, "com.ms.lang.RegKeyEnumValueString: name = value (type = type)"

Fields

value
The string value.


Class RegKeyException

public class RegKeyException extends IOException
{
  // Constructors
  public RegKeyException();
  public RegKeyException(String s);
}

This class signals that an I/O exception has occurred.

IOException
  |
  +--RegKeyException

Constructors

RegKeyException

public RegKeyException();

Constructs a RegKeyException with no detail message.

RegKeyException

public RegKeyException(String s);

Constructs a RegKeyException object with a detail message.

Parameter | Description
s | the detail message, which is a string that describes the specified exception.


Class RegQueryInfo

public class RegQueryInfo
{
  // Fields
  public Date lastWriteTime;
  public int maxClassLen;
  public int maxSubKeyLen;
  public int maxValueLen;
  public int maxValueNameLen;
  public int securityDescriptor;
  public int subKeys;
  public String theClass;
  public int values;
}

This class queries registry access objects.

Fields

lastWriteTime
The most recent write time. If you are querying the registry on a computer running Windows NT, this method returns the last time that the key or any of its value entries was modified. If you are querying the registry on a computer running Microsoft® Windows® 95, this method returns null. This is because the Windows 95 operating system does not keep track of registry key last write time information.
maxClassLen
The length, in characters, of the longest string specifying a subkey class.
maxSubKeyLen
The length, in characters, of the key's subkey with the longest name.
maxValueLen
The length, in bytes, of the longest data component among the key's values.
maxValueNameLen
The length, in characters, of the key's subkey with the longest name. The count returned does not include the terminating null character.
securityDescriptor
The length, in bytes, of the security descriptor.
subKeys
The number of subkeys contained by the key.
theClass
The String class buffer address.
values
The number of value entries associated with the key.


Class SystemThread

public class SystemThread extends Thread
{
  // Constructors
  public SystemThread();
  public SystemThread(String name);
  public SystemThread(Runnable target);
  public SystemThread(Runnable target,String name);

  // Methods
  public static ThreadGroup getSystemThreadGroup();
}

An object of the SystemThread class represents a thread that is always created in the system thread group (the highest level thread group, which has no parent). Untrusted code cannot create threads in the system thread group.

Also see Thread, ThreadGroup

Thread
  |
  +--SystemThread

Constructors

SystemThread

public SystemThread();

Creates a new SystemThread object. This constructor has the same effect as making the following call when group is the system thread group:

Thread(group, null , null)

See Also: java.lang.ThreadGroup, java.lang.Runnable, java.lang.String

SystemThread

public SystemThread(String name);

Creates a new SystemThread object. When group is the system thread group, this constructor has the same effect as making the following call:

Thread(group, null , name)

Parameter | Description
name | The name of the new thread.

See Also: java.lang.ThreadGroup, java.lang.Runnable, java.lang.String

SystemThread

public SystemThread(Runnable target);

Creates a new SystemThread object. When group is the system thread group, this constructor has the same effect as making the following call:

Thread(group, target, null)

Parameter | Description
target | The object, whose run method is called.

See Also: java.lang.ThreadGroup, java.lang.Runnable, java.lang.String

SystemThread

public SystemThread(Runnable target,String name);

Creates a new SystemThread object. When group is the system thread group, this constructor has the same effect as making the following call:

Thread(group, target , name)

Parameter | Description
target | The object, whose run method is called.
name | The name of the new thread.

See Also: java.lang.ThreadGroup, java.lang.Runnable, java.lang.String

Methods

getSystemThreadGroup

public static ThreadGroup getSystemThreadGroup();

Retrieves the system thread group.

Return Value:

Returns the ThreadGroup object of the system thread group.


Class SystemX

public final class SystemX
{
  // Fields
  public static final int LANG_AFRIKAANS;
  public static final int LANG_ALBANIAN;
  public static final int LANG_ARABIC;
  public static final int LANG_BASQUE;
  public static final int LANG_BULGARIAN;
  public static final int LANG_BYELORUSSIAN;
  public static final int LANG_CATALAN;
  public static final int LANG_CHINESE;
  public static final int LANG_CROATIAN;
  public static final int LANG_CZECH;
  public static final int LANG_DANISH;
  public static final int LANG_DUTCH;
  public static final int LANG_ENGLISH;
  public static final int LANG_ESTONIAN;
  public static final int LANG_FINNISH;
  public static final int LANG_FRENCH;
  public static final int LANG_GERMAN;
  public static final int LANG_GREEK;
  public static final int LANG_HEBREW;
  public static final int LANG_HUNGARIAN;
  public static final int LANG_ICELANDIC;
  public static final int LANG_INDONESIAN;
  public static final int LANG_ITALIAN;
  public static final int LANG_JAPANESE;
  public static final int LANG_KOREAN;
  public static final int LANG_LATVIAN;
  public static final int LANG_LITHUANIAN;
  public static final int LANG_NORWEGIAN;
  public static final int LANG_POLISH;
  public static final int LANG_PORTUGUESE;
  public static final int LANG_ROMANIAN;
  public static final int LANG_RUSSIAN;
  public static final int LANG_SLOVAK;
  public static final int LANG_SLOVENIAN;
  public static final int LANG_SORBIAN;
  public static final int LANG_SPANISH;
  public static final int LANG_SWEDISH;
  public static final int LANG_THAI;
  public static final int LANG_TURKISH;
  public static final int LANG_UKRAINIAN;
  public static final int SUBLANG_CHINESE_HONGKONG;
  public static final int SUBLANG_CHINESE_SIMPLIFIED;
  public static final int SUBLANG_CHINESE_SINGAPORE;
  public static final int SUBLANG_CHINESE_TRADITIONAL;
  public static final int SUBLANG_DUTCH_BELGIAN;
  public static final int SUBLANG_ENGLISH_AUS;
  public static final int SUBLANG_ENGLISH_CAN;
  public static final int SUBLANG_ENGLISH_EIRE;
  public static final int SUBLANG_ENGLISH_NZ;
  public static final int SUBLANG_ENGLISH_UK;
  public static final int SUBLANG_ENGLISH_US;
  public static final int SUBLANG_FRENCH;
  public static final int SUBLANG_FRENCH_BELGIAN;
  public static final int SUBLANG_FRENCH_CANADIAN;
  public static final int SUBLANG_FRENCH_SWISS;
  public static final int SUBLANG_GERMAN;
  public static final int SUBLANG_GERMAN_AUSTRIAN;
  public static final int SUBLANG_GERMAN_SWISS;
  public static final int SUBLANG_ITALIAN;
  public static final int SUBLANG_ITALIAN_SWISS;
  public static final int SUBLANG_NORWEGIAN_BOKMAL;
  public static final int SUBLANG_NORWEGIAN_NYNORSK;
  public static final int SUBLANG_PORTUGUESE;
  public static final int SUBLANG_PORTUGUESE_BRAZILIAN;
  public static final int SUBLANG_SPANISH;
  public static final int SUBLANG_SPANISH_MEXICAN;
  public static final int SUBLANG_SPANISH_MODERN;

  // Methods
  public native static boolean arrayCompare(Object P[], int pStart,
        Object Q[], int qStart, int count);
  public static native void gc();
  public static InputManagerListener getDefaultInputManager();
  public static InputManagerListener getInputManager();
  public static int getKeyboardLanguage();
  public static String getKeyboardLanguageName(int id);
  public static int getKeyboardLanguages(int array[]);
  public static int [] getKeyboardLanguages();
  public static int getNumKeyboardLanguages();
  public native static boolean isLocalCharDBCSLeadByte(byte local);
  public static byte JavaStringToLocalString( char Uni );
  public static byte[] JavaStringToLocalString( char C[] );
  public static byte[] JavaStringToLocalString( char C[], int off,
        int len );
  public static String LocalStringToJavaString( String local );
  public static char[] LocalStringToJavaString( byte B[] );
  public static char[] LocalStringToJavaString( char B[] );
  public static char[] LocalStringToJavaString( byte B[], int off,
        int len );
  public static char[] LocalStringToJavaString( char B[], int off,
        int len );
  public static char LocalStringToJavaString( byte local );
  public static void setInputManager(InputManagerListener imm,
        boolean retainCurrentList);
  public static boolean setKeyboardLanguage( Applet App,
        int idLanguage );
}

This class provides system enhancements that implement extended functionality. The SystemX class cannot be instantiated or subclassed because all of the methods and variables are static.

Methods

arrayCompare

public native static boolean arrayCompare(Object P[], int pStart,
        Object Q[], int qStart, int count);

Compares two arrays.

Return Value:

Returns true if the two arrays are equal; otherwise, the method returns false.

Parameter | Description
P | The first array.
pStart | The first element of the first array.
Q | The second array.
pStart | The first element of the second array.
count | The number of elements compared.

Exceptions:

nullPointerArray occurs if there are not enough items in the arrays.

gc

public static native void gc();

Runs the garbage collector.

Return Value:

No return value.

Remarks:

Calling the gc method causes the virtual machine to perform garbage collection. When control returns from the method call, the virtual machine has made a best effort to reclaim space from all unused objects.

See Also: java.lang.Runtime.gc, java.lang.System.gc

getDefaultInputManager

public static InputManagerListener getDefaultInputManager();

Finds the default system input manager.

Return Value:

Returns the default system input manager.

getInputManager

public static InputManagerListener getInputManager();

Retrieves the current input method manager.

Return Value:

Returns null if an input method manager is not running.

getKeyboardLanguage

public static int getKeyboardLanguage();

Retrieves the currently active keyboard language.

Return Value:

Returns the currently active keyboard language.

getKeyboardLanguageName

public static String getKeyboardLanguageName(int id);

Retrieves the keyboard language name.

Return Value:

Returns the name of the language.

Parameter | Description
id | Specifies the identifier of the keyboard language.

getKeyboardLanguages

public static int getKeyboardLanguages(int array[]);

Retrieves a list of the keyboard languages currently active in the system.

Return Value:

Returns the number of active languages.

Parameter | Description
array | The list of keyboard language identifiers.

getKeyboardLanguages

public static int [] getKeyboardLanguages();

Retrieves a list of the keyboard languages currently active in the system.

Return Value:

Returns an array containing the active languages.

getNumKeyboardLanguages

public static int getNumKeyboardLanguages();

Finds the number of active keyboard languages in the system.

Return Value:

Returns the number of active keyboard languages in the system.

isLocalCharDBCSLeadByte

public native static boolean isLocalCharDBCSLeadByte(byte local);

Checks if a local code page character is a lead byte for DBCS systems.

Return Value:

Returns true if the local code page is DBCS; otherwise, returns false.

Parameter | Description
local | The local code page character.

JavaStringToLocalString

public static byte JavaStringToLocalString( char Uni );

Converts a Java character to a character in the local code page.

Return Value:

Returns the local code page string.

Parameter | Description
Uni | The Java character.

JavaStringToLocalString

public static byte[] JavaStringToLocalString( char C[] );

Converts a character array to a byte array in the local code page.

Return Value:

Returns the local representation of the array.

Parameter | Description
C | The Java character array.

JavaStringToLocalString

public static byte[] JavaStringToLocalString( char C[], int off, int len );

Converts a character array to a byte array in the local code page.

Return Value:

Returns the local representation of the array.

Parameter | Description
C | The Java character array.
off | The starting point within the array.
len | The number of characters to convert.

See Also: LocalStringToJavaString

LocalStringToJavaString

public static String LocalStringToJavaString( String local );

Converts a string from a local code page to Unicode.

Return Value:

Returns the Unicode representation of the string.

Parameter | Description
local | The local code page string.

Remarks:

Java internally uses the Unicode encoding system. Unfortunately, this means more than just using 16-bits per character in the local code page. For example, character 149 in the Microsoft® Windows® code page used in America (code page 1252) is a bullet. This is not true for the Macintosh or for many UNIX systems. So, if you make this a hard-coded value, the bullet does not appear correctly on other platforms.

LocalStringToJavaString

public static char[] LocalStringToJavaString( byte B[] );

Converts a byte array from a local code page to an Unicode-filled character array.

Return Value:

Returns the Unicode representation of the array.

Parameter | Description
B | The local code page string.

See Also: LocalStringToJavaString

LocalStringToJavaString

public static char[] LocalStringToJavaString( char B[] );

Converts a char array from a local code page to an Unicode-filled character array.

Return Value:

Returns the Unicode representation of the array.

Parameter | Description
B | The local code page array.

See Also: LocalStringToJavaString

LocalStringToJavaString

public static char[] LocalStringToJavaString( byte B[], int off, int len );

Converts a part of a byte array from a local code page to a Unicode-filled character array.

Return Value:

Returns the Unicode representation of the array.

Parameter | Description
B | The local code page array.
off | The starting point within the array.
len | The length of the segment to convert.

See Also: LocalStringToJavaString

LocalStringToJavaString

public static char[] LocalStringToJavaString( char B[], int off, int len );

Converts a part of a character array from a local code page to an Unicode-filled character array.

Return Value:

Returns the Unicode representation of the array.

Parameter | Description
B | The local code page array.
off | The starting point within the array.
len | The number of characters to convert.

See Also: LocalStringToJavaString

LocalStringToJavaString

public static char LocalStringToJavaString( byte local );

Converts a byte from a local code page to a Unicode character.

Return Value:

Returns the Unicode representation of the array.

Parameter | Description
local | The local code page string.

See Also: LocalStringToJavaString

setInputManager

public static void setInputManager(InputManagerListener imm,
        boolean retainCurrentList);

Sets a new input method manager.

Return Value:

No return value.

Parameter | Description
imm | The new input method manager. Set to null to disable input method manager services. If the new manager inherits the IME list from the previous one, set retainCurrentList to true.
retainCurrentList | The parameter returns true if the new input method manager inherits the list of IMEs. Otherwise, returns false.

setKeyboardLanguage

public static boolean setKeyboardLanguage( Applet App, int idLanguage );

Sets a new active keyboard language.

Return Value:

Returns true if the action was successful. Otherwise, false is returned.

Parameter | Description
App | The applet to set the language.
idLanguage | The language to activate.

Fields

LANG_AFRIKAANS
The Afrikaans language constant.
LANG_ALBANIAN
The Albanian language constant.
LANG_ARABIC
The Arabic language constant.
LANG_BASQUE
The Basque language constant.
LANG_BULGARIAN
The Bulgarian language constant.
LANG_BYELORUSSIAN
The Byelorussian language constant.
LANG_CATALAN
The Catalan language constant.
LANG_CHINESE
The generic Chinese language constant.
LANG_CROATIAN
The Croatian language constant.
LANG_CZECH
The Czech language constant.
LANG_DANISH
The Danish language constant.
LANG_DUTCH
The Dutch language constant.
LANG_ENGLISH
The English language constant.
LANG_ESTONIAN
The Estonian language constant.
LANG_FINNISH
The Finnish language constant.
LANG_FRENCH
The French language constant.
LANG_GERMAN
The German language constant.
LANG_GREEK
The Greek language constant.
LANG_HEBREW
The Hebrew language constant.
LANG_HUNGARIAN
The Hungarian language constant.
LANG_ICELANDIC
The Icelandic language constant.
LANG_INDONESIAN
The Indonesian language constant.
LANG_ITALIAN
The Italian language constant.
LANG_JAPANESE
The Japanese language constant.
LANG_KOREAN
The Korean language constant.
LANG_LATVIAN
The Latvian language constant.
LANG_LITHUANIAN
The Lithuanian language constant.
LANG_NORWEGIAN
The Norwegian language constant.
LANG_POLISH
The Polish language constant.
LANG_PORTUGUESE
The Portuguese language constant.
LANG_ROMANIAN
The Romanian language constant.
LANG_RUSSIAN
The Russian language constant.
LANG_SLOVAK
The Slovakian language constant.
LANG_SLOVENIAN
The Slovenian language constant.
LANG_SORBIAN
The Sorbian language constant.
LANG_SPANISH
The Spanish language constant.
LANG_SWEDISH
The Swedish language constant.
LANG_THAI
The Thai language constant.
LANG_TURKISH
The Turkish language constant.
LANG_UKRAINIAN
The Ukrainian language constant.
SUBLANG_CHINESE_HONGKONG
The Hong Kong Chinese language constant.
SUBLANG_CHINESE_SIMPLIFIED
The Simplified Chinese language constant.
SUBLANG_CHINESE_SINGAPORE
The Singapore Chinese language constant.
SUBLANG_CHINESE_TRADITIONAL
The Traditional Chinese language constant.
SUBLANG_DUTCH_BELGIAN
The Belgian Dutch language constant.
SUBLANG_ENGLISH_AUS
The Australian English language constant.
SUBLANG_ENGLISH_CAN
The Canadian English language constant.
SUBLANG_ENGLISH_EIRE
The Erie (Irish) English language constant.
SUBLANG_ENGLISH_NZ
The New Zealand English language constant.
SUBLANG_ENGLISH_UK
The United Kingdom English language constant.
SUBLANG_ENGLISH_US
The United States English language constant.
SUBLANG_FRENCH
The French language constant.
SUBLANG_FRENCH_BELGIAN
The Belgian French language constant.
SUBLANG_FRENCH_CANADIAN
The French Canadian language constant.
SUBLANG_FRENCH_SWISS
The Swiss French language constant.
SUBLANG_GERMAN
The German language constant.
SUBLANG_GERMAN_AUSTRIAN
The Austrian German language constant.
SUBLANG_GERMAN_SWISS
The Swiss German language constant.
SUBLANG_ITALIAN
The Italian language constant.
SUBLANG_ITALIAN_SWISS
The Italian Swiss language constant.
SUBLANG_NORWEGIAN_BOKMAL
The Bokmal Norwegian language constant.
SUBLANG_NORWEGIAN_NYNORSK
The Nynorsk Norwegian language constant.
SUBLANG_PORTUGUESE
The Portuguese language constant.
SUBLANG_PORTUGUESE_BRAZILIAN
The Portuguese Brazilian language constant.
SUBLANG_SPANISH
The Spanish language constant.
SUBLANG_SPANISH_MEXICAN
The Spanish Mexican language constant.
SUBLANG_SPANISH_MODERN
The modern Spanish language constant.


About com.ms.license

This package includes classes that support Java object licensing files. Licensing files are used to license a java class, package, or archive to a particular user or for a trial period (or both). Java object license files are stored in an encrypted Extended Markup Language (.xml) file with the following format:

<license>

    <licensedescriptor>
        <name>name</name>
        <type>CLASS|PACKAGE|ARCHIVE</type>
        <style>DESIGN|RUNTIME</style>
        <server>URL</server>
        <user>username</user>
        <date>date</date>
        <key>key-string</key>
    </licensedescriptor>

</license>

The .xml file must be named license.xml, and either be located in the same directory as the files that it licenses, or at an URL specified in License.validate. License.xml may have only one <license> tag pair, but as many <licensedescriptor> pairs as needed to license the contents of the current directory.

Licenses may be either RUNTIME or DESIGN. If the style is DESIGN, the license is checked when the container is in design mode. If the style is RUNTIME, the license manager will fail and throw a LicenseException (this prevents developers from incorporating a runtime component into an application).

Classes

Class License
This class supports the validate method, which is used to validate a license for a Java object.
Class LicenseException
This class represents an exception that is thrown when a Java object tries to access a license that either does not exist or is not valid.

Interfaces

Interface LicenseDescriptor
This interface describes the signature of a license object.
Interface LicenseManager
This interface serves as a specification for how to implement a license manager.

Hierarchy

Object
  |
  +--License

Exception
  |
  +--LicenseException

LicenseDescriptor
LicenseManager


Class License

public class License
{
  // Methods
  public static void validate(Object obj, String server,
        String lic, boolean runtime) throws LicenseException;
}

This class supports the validate method, which is used to validate a license for a Java object.

Methods

validate

public static void validate(Object obj, String server, String lic,
        boolean runtime) throws LicenseException;

Validates a license for a Java object. An object can call the License. validate method and specify if the license file is necessary at runtime. If runtime is false, the license manager will not check the license.xml file at runtime. If runtime is true, the license.xml file is required and needs to be packaged with the component.

Return Value:

No return value.

Parameter | Description
obj | The object to find the license for.
server | The server URL to get the license.xml file from if the license is server-side. Set this parameter to null if the license is client-side (the license.xml file is located in the same directory as the class, package, or archive).
lic | The string to use for license comparison.
runtime | The license is runtime only.

Exceptions:

com.ms.license.LicenseException if the validation fails.


Class LicenseException

public class LicenseException extends Exception
{
  // Fields
  public static final int EXPIRED;
  public static final int INVALID;
  public static final int INVALID_USER;
  public static final int KEY_DOES_NOT_MATCH;
  public static final int NO_DESCRIPTORS;
  public static final int NOT_FOUND;
  public static final int READ_ERROR;
  public static final int RUNTIME_ONLY;
  public static final int WRITE_ERROR;

  // Constructors
  public LicenseException();
  public LicenseException(String s);
  public LicenseException(int id, String s);

  // Methods
  public int getID();
}

This class represents an exception that is thrown when a Java object tries to access a license that either does not exist or is not valid.

Exception
  |
  +--LicenseException

Constructors

LicenseException

public LicenseException();

Creates a LicenseException without a detailed message.

LicenseException

public LicenseException(String s);

Creates a LicenseException with a detailed message.

Parameter | Description
s | The detailed message.

LicenseException

public LicenseException(int id, String s);

Creates a new LicenseException with an identifier and a detailed message.

Parameter | Description
id The exception identifier. This may be one of the following identifiers.
INVALID NOT_FOUND NO_DESCRIPTORS
WRITE_ERROR KEY_DOES_NOT_MATCH READ_ERROR
EXPIRED RUNTIME_ONLY INVALID_USER
s | The detailed message.

Methods

getID

public int getID();

Retrieves the exception identifier.

Return Value:

Returns the exception identifier. This may be one of the following identifiers.
INVALID NOT_FOUND NO_DESCRIPTORS
READ_ERROR WRITE_ERROR KEY_DOES_NOT_MATCH

Fields

EXPIRED
An exception identifier that indicates the license is expired.
INVALID
An exception identifier that indicates that the license is invalid.
INVALID_USER
An exception identifier that indicates an invalid user argument.
KEY_DOES_NOT_MATCH
An exception identifier that indicates the key does not match.
NO_DESCRIPTORS
An exception identifier that indicates there are no descriptors for the license.
NOT_FOUND
An exception identifier that indicates that the license cannot be found.
READ_ERROR
An exception identifier that indicates there was a read error while reading the license.
RUNTIME_ONLY
An exception identifier that indicates the license has a RUNTIME style.
WRITE_ERROR
An exception identifier that indicates there was a write error.


Interface LicenseDescriptor

public interface LicenseDescriptor
{
  // Fields
  public static final int ARCHIVE;
  public static final int CLASS;
  public static final int DESIGN;
  public static final int PACKAGE;
  public static final int RUNTIME;

  // Methods
  public java.util.Date getDate();
  public String getKey();
  public String getName();
  public java.net.URL getServer();
  public int getStyle();
  public int getType();
  public String getUser();
  public void setDate(java.util.Date date);
  public void setKey(String key);
  public void setName(String name);
  public void setServer(java.net.URL server);
  public void setStyle(int style) throws Exception;
  public void setType(int type) throws Exception;
  public void setUser(String user);
}

This interface describes the signature of a license object. The descriptor allows access to the different fields of a license.

Methods

getDate

public java.util.Date getDate();

Retrieves the expiration date of the license.

Return Value:

Returns the expiration date. If the returned date is null, the license does not have an expiration.

See Also: setDate

getKey

public String getKey();

Retrieves the license string that is used for validation of the license.

Return Value:

Returns the license string to validate.

See Also: setKey

getName

public String getName();

Retrieves the name of the class, package, or archive licensed by the license file.

Return Value:

Returns the name of the class, package, or archive.

See Also: setName

getServer

public java.net.URL getServer();

Retrieves the server where the true license file is stored for this object.

Return Value:

Returns the URL location of the server.

See Also: setServer

getStyle

public int getStyle();

Retrieves the license style. By default, all licenses are design time licenses. However, a user can have a run-time only license.

Return Value:

Returns the style of license, either DESIGN or RUNTIME.

See Also: setStyle

getType

public int getType();

Retrieves the type of license from the descriptor object.

Return Value:

Returns the type of license. This may be one of the following:

  • CLASS
  • ARCHIVE
  • PACKAGE

See Also: setType

getUser

public String getUser();

Retrieves the user that is able to use the license.

Return Value:

Returns the username.

See Also: setUser

setDate

public void setDate(java.util.Date date);

Sets the expiration date in the license descriptor.

Return Value:

No return value.

Parameter | Description
date | The expiration date.

See Also: getDate

setKey

public void setKey(String key);

Sets the license string that is used to validate the license.

Return Value:

No return value.

Parameter | Description
key | The license string.

See Also: getKey

setName

public void setName(String name);

Sets the name of the class, package, or archive that is licensed by the license descriptor.

Return Value:

No return value.

Parameter | Description
name | The name of the class, package, or archive (CAB, JAR, and CCF formats are currently supported).

See Also: getName

setServer

public void setServer(java.net.URL server);

Sets the server attribute for the license descriptor.

Return Value:

No return value.

Parameter | Description
server | The URL location of the server to get a remote license from.

See Also: getServer

setStyle

public void setStyle(int style) throws Exception;

Sets the license style. If style is zero, the method defaults to a design time license.

Return Value:

No return value.

Parameter | Description
style | The style of license. This may be either DESIGN or RUNTIME.

Exceptions:

Exception if the style is invalid.

See Also: getStyle

setType

public void setType(int type) throws Exception;

Sets the type of license.

Return Value:

No return value.

Parameter Description
type Sets the type of license. The type can be one of the following:
  • CLASS
  • ARCHIVE
  • PACKAGE

Exceptions:

Exception if the license type is not valid.

See Also: getType

setUser

public void setUser(String user);

Sets the valid user for the license.

Return Value:

No return value.

Parameter | Description
user | The username.

See Also: getUser

Fields

ARCHIVE
The archive license type.
CLASS
The class license type. The CLASS type is the default type if none is specified in the license.xml file.
DESIGN
The design license style.
PACKAGE
The package license type.
RUNTIME
The run-time license style.


Interface LicenseManager

public interface LicenseManager
{
  // Methods
  public void decrypt() throws LicenseException;
  public void encrypt() throws LicenseException;
  public LicenseDescriptor[] getLicenseDescriptors();
  public void readLicense(Object obj) throws java.io.IOException;
  public void readLicense(String server) throws java.io.IOException;
  public void writeLicense(PrintStream stream,
        LicenseDescriptor desc[]) throws java.io.IOException;
}

This interface serves as a specification for how to implement a license manager. It describes all of the facilities needed to perform the licensing function.

Methods

decrypt

public void decrypt() throws LicenseException;

Calls the decryption engine to decrypt a license file.

Return Value:

No return value.

Exceptions:

com.ms.license.LicenseException if the license could not be decrypted.

encrypt

public void encrypt() throws LicenseException;

Calls the encryption engine to encrypt a license file.

Return Value:

No return value.

Exceptions:

com.ms.license.LicenseException if the license could not be encrypted.

getLicenseDescriptors

public LicenseDescriptor[] getLicenseDescriptors();

Retrieves the license descriptors for the object.

Return Value:

Returns LicenseDescriptor An array of LicenseDescriptor objects.

readLicense

public void readLicense(Object obj) throws java.io.IOException;

Reads a license file from a disk.

Return Value:

No return value. @exeception IOException if the read failed.

Parameter | Description
obj | The object used to read the license file.

readLicense

public void readLicense(String server) throws java.io.IOException;

Reads a license from a server.

Return Value:

No return value.

Parameter | Description
server | The server to get the license file from.

Exceptions:

IOException if the read failed.

writeLicense

public void writeLicense(PrintStream stream,
        LicenseDescriptor desc[]) throws java.io.IOException;

Creates a new license file and writes the contents of the LicenseDescriptor objects.

Return Value:

No return value.

Parameter | Description
stream | The stream to write the license file to.
desc | An array of LicenseDescriptor objects.

Exceptions:

IOException if the write failed.


About com.ms.object

In this topic

* Overview

* Examples

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.object | Packages | Next

About com.ms.object

This package provides classes and interfaces for implementing data transfer operations.

Overview

Many of the classes and interfaces in the com.ms.object package are designed to facilitate data transfer. The Transfer, TransferSession, and MetaObject interfaces and the Category class define the basic protocol for data transfer. The ObjectBag and SimpleTransferSession classes provide default implementations for commonly used interfaces.

During data transfer, a data recipient obtains a TransferSession and acts upon it. The recipient might, for example, interrogate the session to determine the types of transfers supported (by using the getAvailableEffects and getPreferredEffects methods). The recipient might also ask the session for the data being transferred (by using the getTransferData method). The data is represented in the form of a MetaObject, which can also be interrogated to determine what forms the transferred data can take.

The com.ms.object package also contains classes and interfaces that allow Java components to obtain a system service. For instance, a Java component that is hosted inside a Microsoft® ActiveX® container might want to obtain the ActiveXControlServices system service. To obtain a system service, a Java component that implements the ISiteable interface could query for and obtain an ISite object. This site object could then be queried for the service using the IServiceObjectProvider.queryService method. If the requested service is not available, a ServiceNotFoundException is thrown.

Examples

The recipient might want to support transfer of text in HTML format if it is available and fall back to plain text if HTML is not available. The following example illustrates how to interrogate the MetaObject to determine whether HTML is supported.

class Recipient
{
   Category htmlCategory = new Category("text/html");
   Category plainCategory = new Category("text/plain");

   // This method interrogates a MetaObject for data transfer.
   public void interrogate(MetaObject data)
   {
     try
     {
        Class streamClass = Class.forName("java.io.InputStream");
        if (data.hasObject(htmlCategory, streamClass))
        {
          InputStream stream = data.getObject(htmlCategory,
                                              streamClass);
          // Do something with HTML stream.
        }
        else if (data.hasObject(plainCategory, streamClass))
        {
          InputStream stream = data.getObject(plainCategory,
                                              streamClass);
          // Do something with plain text stream.
        }
     }
     catch(ClassNotFoundException e)
     {
     }
   }
}

For recipients that support many formats, it might be more efficient to enumerate the formats supported by the MetaObject. Using this technique, a recipient can determine possible actions based on the types of data that are offered.

class Recipient
{
   Category htmlCategory = new Category("text/html");
   Category plainCategeory = new Category ("text/plain");

   // The recipient may keep private flags to track what can
   // be done with the data.
   private static final int HAS_HTML = 1;
   private static final int HAS_TEXT = 2;

   // This method determines the values of the HAS_HTML
   // and HAS_TEXT flags based on the data being offered.
   public int interrogate(MetaObject data)
   {
     private int avail = 0;

     try
     {
        Class streamClass = Class.forName("java.io.InputStream");
        Enumeration categories = data.objectCategories();
        if (categories != null)
        {
          while (categories.hasMoreElements())
          {
             Category category = (Category)categories.nextElement();
             if (category.equals(htmlCategory))
                avail |= HAS_HTML;
             else if (category.equals(plainCategory))
                avail |= HAS_TEXT;
          }
        }
     }
     catch (ClassNotFoundException e)
     {
     }

     return avail;
  }
}

Classes

Class Category
This class provides an abstract type identity.
Class ObjectBag
This class is a default implementation of the MetaObject interface that can be used to implement delayed rendering.
Class ServiceNotFoundException
This class represents an exception indicating that a requested service was not available.
Class SimpleTransferSession
This class is a default implementation of the TransferSession interface.

Interfaces

Interface IServiceObjectProvider
This interface defines a method used to request a service from an object.
Interface ISite
This interface defines the removeSiteable method, which is called when an ISiteable object detaches itself from a site.
Interface ISiteable
This interface defines methods that set and retrieve the ISite object that is associated with an ISiteable object.
Interface MetaObject
This interface defines an abstraction for an object that has multiple identities.
Interface Transfer
This interface provides constants that represent transfer effects.
Interface TransferSession
This interface defines a data transfer session abstraction that is used to describe a transfer operation.

Hierarchy

Object
  |
  +--ObjectBag (MetaObject)
  |
  +--SimpleTransferSession (TransferSession)
  |
  +--Category

Exception
  |
  +--ServiceNotFoundException

TransferSession
Transfer
IServiceObjectProvider
ISite
ISiteable
MetaObject


Class Category

public class Category
{
  // Constructors
  public Category(String name);

  // Methods
  public boolean equals(Category other);
  public boolean equals(Object other);
  public String getName();
  public int hashCode();
  public String toString();
}

This class provides an abstract type identity. Category objects are used to describe the types of objects that are supported by a MetaObject.

Constructors

Category

public Category(String name);

Creates a new Category object with the specified name.

Parameter | Description
name | The name for the new category.

Methods

equals

public boolean equals(Category other);

Tests a category for equality with another category. Two categories are equal if they have the same name.

Return Value:

Returns true if other is not null and the two categories have the same name; otherwise, returns false.

Parameter | Description
other | The other Category object to test for equality.

equals

public boolean equals(Object other);

Tests a category for equality with another object.

Return Value:

Returns true if the other object is a category and the two categories are equal; otherwise, returns false.

Parameter | Description
other | The other object to test for equality.

getName

public String getName();

Retrieves the name of the category.

Return Value:

Returns a String that identifies the category.

hashCode

public int hashCode();

Retrieves the category's hash code.

Return Value:

Returns an integer hash code for the category.

toString

public String toString();

Produces a summary string for the category.

Return Value:

Returns a String that describes the category by using the name of the category.


Class ObjectBag

public class ObjectBag implements MetaObject
{
  // Constructors
  public ObjectBag();
  public ObjectBag(MetaObject renderer);

  // Methods
  public void addObject(Category category, Class cls, Object object);
  public Object getObject(Category category, Class cls);
  public boolean hasObject(Category category, Class cls);
  public Enumeration objectCategories();
  public Enumeration objectClasses(Category category);
}

This class is a default implementation of the MetaObject interface that can be used to implement delayed rendering. Delayed rendering allows a data source to support several different data formats and convert these formats as necessary, based on the requirements of the recipient.

For instance, a word processor might have an internal text representation, but it might also know how to convert its text representation to plain text, rich text, or other formats. Instead of providing all possible conversions when it constructs the MetaObject for a data transfer, the word processor could run the conversion on demand, depending on the format required by the recipient.

To implement delayed rendering, a data source might implement a MetaObject that always does format conversions and then wrap an ObjectBag around it. When the ObjectBag is asked for a data format it does not support, it asks the source MetaObject to obtain the data, thereby running the conversion. The converted data is then stored in the ObjectBag for future use.

Constructors

ObjectBag

public ObjectBag();

Creates an assignable ObjectBag object with no delayed renderer.

ObjectBag

public ObjectBag(MetaObject renderer);

Creates an ObjectBag object with a delayed renderer.

Parameter | Description
renderer | The MetaObject that the ObjectBag should use for delayed rendering

Methods

addObject

public void addObject(Category category, Class cls, Object object);

Adds an object to the ObjectBag.

Return Value:

No return value.

Parameter | Description
category | The Category of the object being added.
cls | The Class of the object being added. If cls is null, the class is inferred from the specified Object.
object | The object to add to the object bag.

getObject

public Object getObject(Category category, Class cls);

Requests an object with the specified category and class from the ObjectBag.

Return Value:

Returns an object with the specified category and class.

Parameter | Description
category | The Category object that represents the category that is requested.
cls | The Class object that represents the class that is requested.

hasObject

public boolean hasObject(Category category, Class cls);

Determines whether the specified category and class are supported by the ObjectBag.

Return Value:

Returns true if the ObjectBag supports the specified category and class; otherwise, returns false.

Parameter | Description
category | The Category object that represents the category being queried for.
cls | The Class object that represents the class being queried for.

objectCategories

public Enumeration objectCategories();

Enumerates the categories in the ObjectBag.

Return Value:

Returns an Enumeration of the categories in the ObjectBag.

objectClasses

public Enumeration objectClasses(Category category);

Enumerates the classes in the ObjectBag that are in the specified category.

Return Value:

Returns an Enumeration of the classes in the ObjectBag that are in the specified category.

Parameter | Description
category | The category that identifies which classes to enumerate.


Class ServiceNotFoundException

public class ServiceNotFoundException extends Exception
{
  // Constructors
  public ServiceNotFoundException();
  public ServiceNotFoundException(String s);
}

This class represents an exception indicating that a requested service was not available.

Exception
  |
  +--ServiceNotFoundException

Constructors

ServiceNotFoundException

public ServiceNotFoundException();

Creates a ServiceNotFoundException with no detail message.

ServiceNotFoundException

public ServiceNotFoundException(String s);

Creates a ServiceNotFoundException with the specified detail message.

Parameter | Description
s | The detail message.


Class SimpleTransferSession

public class SimpleTransferSession implements TransferSession
{
  // Constructors
  public SimpleTransferSession(MetaObject data, int available);
  public SimpleTransferSession(MetaObject data, int available, int preferred);

  // Methods
  public void deleteSource();
  public int getAvailableEffects();
  public int getPreferredEffects();
  public MetaObject getTransferData();
}

This class is a default implementation of the TransferSession interface. If you do not want to customize the behavior of a TransferSession but you want to source some data, the SimpleTransferSession class might be sufficient for your needs.

Be aware that this class does not support the Transfer.MOVE transfer effect because it requires an implementation of TransferSession.deleteSource (which the SimpleTransferSession class does not provide). To remedy this situation, you could extend the SimpleTransferSession class to gain the TransferSession implementation and then override the deleteSource method.

Constructors

SimpleTransferSession

public SimpleTransferSession(MetaObject data, int available);

Creates a SimpleTransferSession object with a data object and the specified available transfers. The preferred transfers of the SimpleTransferSession object default to the specified available transfers.

Parameter | Description
data | The MetaObject that represents the data that is transferred by the transfer session.
available A value that identifies the available transfer effects. It can be any one or a combination of the following values:
NONE, COPY, MOVE, or LINK.

SimpleTransferSession

public SimpleTransferSession(MetaObject data, int available, int preferred);

Creates a SimpleTransferSession data transfer session object with a data object and specified available and preferred transfer effects.

Parameter | Description
data | A MetaObject that represents the data that is transferred by the transfer session.
available A value that identifies the available transfer effects. It can be any one or a combination of the following values:
NONE, COPY, MOVE, or LINK.
preferred An integer that identifies the preferred transfer effects. It can be any one or a combination of the following values:
NONE COPY MOVE LINK

Methods

deleteSource

public void deleteSource();

This method does nothing.

Return Value:

No return value.

getAvailableEffects

public int getAvailableEffects();

Retrieves the Transfer effects that are available in the session.

Return Value:

Returns a value that identifies the available transfer effects. It can be any one or a combination of the following values:
NONE, COPY, MOVE, or LINK.

getPreferredEffects

public int getPreferredEffects();

Retrieves the Transfer effects that are preferred by the originator of the session.

Return Value:

Returns a value that identifies the preferred transfer effects. It can be any one or a combination of the following values:
NONE, COPY, MOVE, or LINK.

getTransferData

public MetaObject getTransferData();

Retrieves the data that is associated with the session.

Return Value:

Returns a MetaObject that represents the data offered for transfer.


Interface IServiceObjectProvider

public interface IServiceObjectProvider
{
  // Methods
  public Object queryService(Object id) throws ServiceNotFoundException;
}

This interface defines a method that is used to request a service from an object.

Methods

queryService

public Object queryService(Object id) throws ServiceNotFoundException;

Requests a service from an object. The object that provides the service can be the current object or a different object.

To determine whether the object supports the requested service, a typical implementation would check to see if any of the following items are true:

  • The object is an instance of the requested service.
  • The object implements the requested service.
  • The object can construct or use another object that is an instance of or implements the requested service.

If the object does not support the requested service, it delegates the method call to an upper level object (such as a containing frame). Finally, if no object in the chain supports the requested service, a ServiceNotFoundException is thrown.

Return Value:

Returns the service object, if it is available.

Parameter | Description
id | The identifier of the requested service.

Exceptions:

ServiceNotFoundException if no object supports the requested service.


Interface ISite

public interface ISite extends IServiceObjectProvider
{
  // Methods
  public void removeSiteable(ISiteable siteable);
}

This interface defines the removeSiteable method, which is called when an ISiteable object detaches itself from a site.

IServiceObjectProvider
  |
  +--ISite

Methods

removeSiteable

public void removeSiteable(ISiteable siteable);

Notifies the site that the ISiteable object is detaching itself from the site. This notification provides an opportunity for the site to perform any cleanup, such as removing the ISiteable object from its list of objects.

An ISiteable object calls this method whenever its site changes (because the setSite method has been called) or when the ISiteable object is no longer bound to the site.

Return Value:

No return value.

Parameter | Description
siteable | The object that is detaching from the site.


Interface ISiteable

public interface ISiteable
{
  // Methods
  public ISite getSite();
  public void setSite(ISite site);
}

This interface defines methods that set and retrieve the ISite object that is associated with an ISiteable object.

Methods

getSite

public ISite getSite();

Retrieves the ISite object for this instance.

Return Value:

Returns the ISite object for this instance. If no ISite object is currently set, null is returned.

setSite

public void setSite(ISite site);

Sets the ISite object for this instance. Any references to an existing site or to any services provided through the ISite object are discarded.

For the sake of serialization, the object should mark the field containing this site as "transient."

Return Value:

No return value.

Parameter | Description
site | The ISite object for this instance (can be null).


Interface MetaObject

public interface MetaObject
{
  // Methods
  public Object getObject(Category category, Class cls);
  public boolean hasObject(Category category, Class cls);
  public Enumeration objectCategories();
  public Enumeration objectClasses(Category category);
}

This interface defines an abstraction for an object that has multiple identities. A class that implements the MetaObject interface can be used to represent data that is being transferred.

Methods

getObject

public Object getObject(Category category, Class cls);

Retrieves an object instance that matches the specified Category and Class objects. Either one (but not both) of the parameters can be null.

Return Value:

Returns an object that matches the specified Category and Class; returns null if no matching object is available.

Parameter | Description
category | The Category of the requested object. If a null Category object is specified, the Category is derived from the name of the specified class.
cls | The Class of the requested object. If a null Class is specified, the request is for any object in the specified category.

hasObject

public boolean hasObject(Category category, Class cls);

Determines whether the specified Category and Class are supported by the MetaObject. Either one (but not both) of the parameters can be null.

Return Value:

Returns true if an object that matches the specified Category and Class is available; otherwise, returns false.

Parameter | Description
category | The Category that is requested. If a null Category object is specified, the category is derived from the name of the specified class.
cls | The Class that is requested. If a null Class is specified, the request is for any class in the specified category.

objectCategories

public Enumeration objectCategories();

Enumerates the categories that are supported by the MetaObject.

Return Value:

Returns an Enumeration of the Category objects that are supported.

objectClasses

public Enumeration objectClasses(Category category);

Enumerates the classes that are used to describe the specified category.

Return Value:

Returns an Enumeration of Class objects in the specified Category that are supported by the MetaObject.

Parameter | Description
category | The Category to enumerate Class objects from.


Interface Transfer

public interface Transfer
{
  // Fields
  public static final int COPY;
  public static final int LINK;
  public static final int MOVE;
  public static final int NONE;
}

This interface provides constants that represent transfer effects. These constants are used by the TransferSession interface and the SimpleTransferSession class.

Fields

COPY
A value indicating that the transfer copies data.
LINK
A value indicating that the transfer links to data.
MOVE
A value indicating that the transfer moves data.
NONE
A value indicating that there is no current transfer.


Interface TransferSession

public interface TransferSession extends Transfer
{
  // Methods
  public void deleteSource();
  public int getAvailableEffects();
  public int getPreferredEffects();
  public MetaObject getTransferData();
}

This interface defines a data transfer session abstraction that is used to describe a transfer operation. The source of a transfer creates a TransferSession and then initiates the transfer. During data transfer, a recipient obtains a TransferSession and acts on it by interrogating it for the transfer effects supported and the data being transferred.

Transfer
  |
  +--TransferSession

Methods

deleteSource

public void deleteSource();

Deletes the source data. This method facilitates MOVE operations where the destination is only capable of performing a COPY operation. That is, instead of performing a MOVE operation, a COPY operation can be performed and then the data can be deleted from the source.

Return Value:

No return value.

getAvailableEffects

public int getAvailableEffects();

Retrieves the Transfer effects that are available in the session.

Return Value:

Returns a value that identifies the available transfer effects. It can be any one (or a combination of) the following values:
NONE, COPY, MOVE, or LINK.

getPreferredEffects

public int getPreferredEffects();

Retrieves the Transfer effects that are preferred by the originator of the session.

Return Value:

Returns a value that identifies the preferred transfer effects. It can be any one (or a combination of) the following values:
NONE, COPY, MOVE, or LINK.

getTransferData

public MetaObject getTransferData();

Retrieves the data that is associated with the session.

Return Value:

Returns a MetaObject that represents the data offered for transfer.


About com.ms.object.dragdrop

In this topic

* Overview

* Drag Handler Example

* Drag Session Example

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.object.dragdrop | Packages | Next

About com.ms.object.dragdrop

This package provides classes and interfaces for implementing visual drag-and-drop operations.

Overview

The com.ms.object.dragdrop package uses the transfer model defined in the com.ms.object package, adding behavior that is specific to visual drag-and-drop operations. The basic dragdrop protocol is defined by the DragHandler, DragSession, and DragSource interfaces. The DragHelper and DragProxy classes help developers implement the dragdrop protocol for objects that are not supported by the system. DragProxy is a simple DragHandler implementation that forwards all calls to a specified DragHandler, with an optional offset to the drag coordinates. The DragHelper class implements the DragHandler interface and distributes DragHandler method calls to child handlers.

The DragHandler interface is implemented by recipients who want to receive drops from a drag source. This interface contains methods for notifying the recipient when the object has entered, exited, moved, or has been dropped by the user. DragSession extends the TransferSession interface and adds the concepts of modifier keys and mouse state. The DragSession interface is generally implemented by the dragdrop implementation. To customize the behavior of a drag operation as it progresses, you can implement the DragSource interface, which provides capabilities such as cursor control.

Drag Handler Example

The following example shows how to implement a DragHandler. In particular, this class implements a ColorTile object that can receive a new color (java.awt.Color) by a drag-and-drop operation.

class ColorTile extends Canvas implements DragHandler
{
   static final private Class colorClass = new Color( ).getClass( );

   Color color;
   Color colorHot;
   boolean hot = false;

   public ColorTile(Color c, int x, int y)
   {
      super( );
      initFromColor(c);
      reshape(16 * x + 64, 16 * y + 64, 128, 128);
   }

   private void initFromColor(Color c)
   {
      color = c.darker( );
      colorHot = c;
      hotTrack(hot);
   }

   private void hotTrack(boolean hot)
   {
      this.hot = hot;

      Color c = hot? colorHot : color;
      setBackground(c);

      if (isShowing( ))
         repaint( );
   }

   public void dragEnter(DragSession session)
   {
      hotTrack(true);
   }

   public void dragLeave( )
   {
      hotTrack(false);
   }

   public int dragOver(DragSession session, int x, int y)
   {
      //Interrogate the data to see if there is a color.

      MetaObject data = session.getTransferData( );
      if ((data !=      null) && data.hasObject(null, colorClass))
      {
         //There is a color. Return a value that indicates
         // that we can copy it if the source is allowing copy
         // operations.
         return session.getAvailableEffects( ) & Transfer.COPY;
      }

      return Transfer.NONE;
   }

   public void drop(DragSession session int x, int y)
   {
       MetaObject data = session.getTransferData( );
       if (data != null)
       {
          Object object = data.getObject(null, colorClass);
          if (object instanceof Color)
             initFromColor((Color)object);
       }
    }
}

Drag Session Example

Starting a drag session differs, depending on whether you are using AFC or AWT. Two code samples follow: the first is for AWT, and the second is for AFC.

AWT Example

import java.awt.*;
import com.ms.object.*;
import com.ms.object.dragdrop.*;
import com.ms.awt.WDragSession;

class DragMeAWT extends Canvas
{
//...
  public boolean mouseDown(Event e, int x, int y)
  {
    ObjectBag data = new ObjectBag();
    data.addObject(null, null, Color.red);
    WDragSession.beginDrag(data, Transfer.COPY | Transfer.LINK);

    return true;
  }
}

AFC Example

import com.ms.ui.*;
import com.ms.object.*;
import com.ms.object.dragdrop.*;
import java.awt.Color;

class DragMeAFC extends UICanvas
{
//...
  public boolean mouseDown(Event e, int x, int y)
  {
    ObjectBag data = new ObjectBag();
    data.addObject(null, null, Color.red);
    UIDragDrop.beginDrag(data, Transfer.COPY | Transfer.LINK);

    return true;
  }
}

Classes

Class DragHelper
This class provides a default implementation for a dragdrop protocol involving a set of objects that the system does not support.
Class DragProxy
This class provides a DragHandler implementation that forwards calls to another specified DragHandler.

Interfaces

Interface DragHandler
This interface defines methods that handle drag operations relative to other objects.
Interface DragSession
This interface defines drag modifiers used with drag-and-drop operations.
Interface DragSource
This interface defines constants and methods that can be used by the source object of a dragdrop data transfer session.

Hierarchy

Object
  |
  +--DragHelper (DragHandler)
  |
  +--DragProxy (DragHandler)

DragSource
DragSession
DragHandler


Class DragHelper

public abstract class DragHelper implements DragHandler
{
  // Methods
  public void dragEnter(DragSession session);
  public void dragLeave();
  public int dragOver(DragSession session, int x, int y);
  public void drop(DragSession session, int x, int y);
  protected abstract Object findDragObject(DragSession session, int
        x, int y);
  protected abstract DragHandler getDragHandler(
        DragSession session, Object object);
  protected void trackDragStatus(DragSession session,
        Object object, int effect);
}

This class provides a default implementation for a dragdrop protocol involving a set of objects that the system does not support. For instance, if you are designing a tree control that is not composed of system components, you could use this class (along with the DragProxy class) to help implement the enter, continue, leave, and drop behaviors over the subelements in your tree.

Typically, you would extend the DragHelper class, providing hit-testing code to implement the findDragObject and getDragHandler methods.

When a drag method is called on a class that extends DragHelper, the drag method calls the findDragObject method to hit-test the coordinates in the drag method. The derived class returns an Object that represents the hit result.

If the Object has changed since the last hit-test, the drag helper then calls the getDragHandler method to obtain a DragHandler for the new hit Object. In addition, the derived class can override the trackDragStatus method to implement highlighting or some other form of feedback.

Methods

dragEnter

public void dragEnter(DragSession session);

Notifies the recipient when a source object enters the space that is defined by a container, window, or object.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.

dragLeave

public void dragLeave();

Notifies the recipient when a source object exits the space that is defined by a container, window, or object.

Return Value:

No return value.

dragOver

public int dragOver(DragSession session, int x, int y);

Notifies the recipient when a source object continues through the space that is defined by a container, window, or object.

Return Value:

Returns one or more of the following values:
NONE, COPY, MOVE, or LINK.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.

drop

public void drop(DragSession session, int x, int y);

Notifies the recipient when a source object is dropped at a new location.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.

findDragObject

protected abstract Object findDragObject(DragSession session,
        int x, int y);

Provides a hit-test of the coordinates in the drag method.

Return Value:

Returns the object that represents the hit result.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate to hit-test.
y | The y coordinate to hit-test.

getDragHandler

protected abstract DragHandler getDragHandler(DragSession session,
        Object object);

Retrieves the DragHandler object for the specified drag session.

Return Value:

Returns a DragHandler for the drag-and-drop operation.

Parameter | Description
session | The DragSession object that represents the current drag operation.
object | The object returned by the findDragObject method.

trackDragStatus

protected void trackDragStatus(DragSession session, Object object,
        int effect);

This method is not currently implemented. It is called by the dragEnter, dragOver, and dragLeave methods to track the status of the current drag operation.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.
object | The object that is being dragged.
effect | The value that indicates the drag status.


Class DragProxy

public class DragProxy implements DragHandler
{
  // Constructors
  public DragProxy();
  public DragProxy(DragHandler handler);
  public DragProxy(DragHandler handler, int xOffset, int yOffset);

  // Methods
  public void dragEnter(DragSession session);
  public void dragLeave();
  public int dragOver(DragSession session, int x, int y);
  public void drop(DragSession session, int x, int y);
  public DragHandler getHandler();
  public Point getOffset();
  public void setHandler(DragHandler handler);
  public void setHandler(DragHandler handler, int xOffset,
        int yOffset);
  public void setOffset(Point offset);
  public void setOffset(int xOffset, int yOffset);
}

This class provides a DragHandler implementation that forwards calls to another specified DragHandler. Optionally, x and y offsets can be set and retrieved for a DragProxy object.

Constructors

DragProxy

public DragProxy();

Creates a new DragProxy object.

DragProxy

public DragProxy(DragHandler handler);

Creates a new DragProxy object that has the specified drag handler.

Parameter | Description
handler | The drag handler to assign to the DragProxy instance.

DragProxy

public DragProxy(DragHandler handler, int xOffset, int yOffset);

Creates a new DragProxy object that has the specified drag handler, x offset, and y offset.

Parameter | Description
handler | The drag handler for the DragProxy object.
xOffset | The x offset for the DragProxy object.
yOffset | The y offset for the DragProxy object.

Methods

dragEnter

public void dragEnter(DragSession session);

Notifies the recipient when a source object enters the space defined by a container, window, or object.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.

dragLeave

public void dragLeave();

Notifies the recipient when a source object exits the space defined by a container, window, or object.

Return Value:

No return value.

dragOver

public int dragOver(DragSession session, int x, int y);

Notifies the recipient when a source object continues through the space defined by a container, window, or object.

Return Value:

Returns one or more of the following values:
NONE, COPY, MOVE, or LINK.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.

drop

public void drop(DragSession session, int x, int y);

Notifies the recipient when a source object is dropped at a new location.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.

getHandler

public DragHandler getHandler();

Retrieves the drag handler for the DragProxy object.

Return Value:

Returns the drag handler for the DragProxy object.

getOffset

public Point getOffset();

Retrieves the offset for the DragProxy object.

Return Value:

Returns the Point object that represents the x offset and y offset of the DragProxy object.

setHandler

public void setHandler(DragHandler handler);

Sets the drag handler for the DragProxy object.

Return Value:

No return value.

Parameter | Description
handler | The new handler for the DragProxy object.

setHandler

public void setHandler(DragHandler handler, int xOffset, int yOffset);

Sets the drag handler and the x and y offsets for the DragProxy object.

Return Value:

No return value.

Parameter | Description
handler | The new handler for the DragProxy object.
xOffset | The new x offset for the DragProxy object.
yoffset | The new y offset for the DragProxy object.

setOffset

public void setOffset(Point offset);

Sets the x offset and y offset of the DragProxy object based on a specified Point object.

Return Value:

No return value.

Parameter | Description
offset | The Point object that represents an x offset and y offset.

setOffset

public void setOffset(int xOffset, int yOffset);

Sets the x offset and y offset of the DragProxy object.

Return Value:

No return value.

Parameter | Description
xOffset | The new value for the x offset.
yOffset | The new value for the y offset.


Interface DragHandler

public interface DragHandler
{
  // Methods
  public void dragEnter(DragSession session);
  public void dragLeave();
  public int dragOver(DragSession session, int x, int y);
  public void drop(DragSession session, int x, int y);
}

This interface defines methods that handle drag operations relative to other objects. A recipient would implement this interface to receive drops from a drag source. There are methods in this interface that notify the recipient when the object has entered, left, moved, or might have been dropped by the user.

To view an example that implements a DragHandler, see the com.ms.object.dragdrop overview.

Methods

dragEnter

public void dragEnter(DragSession session);

Notifies the recipient when a source object enters the space that is defined by a container, window, or object.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.

dragLeave

public void dragLeave();

Notifies the recipient when a source object exits the space that is defined by a container, window, or object.

Return Value:

No return value.

dragOver

public int dragOver(DragSession session, int x, int y);

Notifies the recipient when a source object continues through the space that is defined by a container, window, or object.

Return Value:

Returns one or more of the following values:
NONE, COPY, MOVE, or LINK.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.

drop

public void drop(DragSession session, int x, int y);

Notifies the recipient when a source object is dropped at a new location.

Return Value:

No return value.

Parameter | Description
session | The DragSession object that represents the current drag operation.
x | The x coordinate of the current cursor position.
y | The y coordinate of the current cursor position.


Interface DragSession

public interface DragSession extends TransferSession
{
  // Fields
  public static final int ALT;
  public static final int CONTROL;
  public static final int LBUTTON;
  public static final int MBUTTON;
  public static final int RBUTTON;
  public static final int SHIFT;

  // Methods
  public int getDragModifiers();
}

This interface defines drag modifiers used with drag-and-drop operations. These constants represent the mouse state and keyboard modifiers such as the CTRL, ALT, and SHIFT keys. In most cases, this interface should be implemented by a class that implements the dragdrop protocol.

TransferSession
  |
  +--DragSession

Methods

getDragModifiers

public int getDragModifiers();

Retrieves the drag modifiers for the current drag operation.

Return Value:

Returns any one or a combination of the following modifiers:
LBUTTON, MBUTTON, RBUTTON,
CONTROL, SHIFT, or ALT.

Fields

ALT
A drag modifier indicating that the ALT key is pressed.
CONTROL
A drag modifier indicating that the CTRL key is pressed.
LBUTTON
A drag modifier indicating that the left mouse button is pressed.
MBUTTON
A drag modifier indicating that the middle button of a three-button mouse is pressed.
RBUTTON
A drag modifier indicating that the right mouse button is pressed.
SHIFT
A drag modifier indicating that the SHIFT key is pressed.


Interface DragSource

public interface DragSource
{
  // Fields
  public static final int CANCEL;
  public static final int CONTINUE;
  public static final int DEFAULT_ACTION;
  public static final int DROP;

  // Methods
  public Object queryDragCursor(int effect);
  public int queryDragStatus(int modifiers);
}

This interface defines constants and methods that can be used by the source object of a dragdrop data transfer session. This interface allows a source object to customize the behavior of a drag operation as it progresses.

The queryDragStatus method can be used to query the current drag status of a dragged object. Drag status depends on whether the source object is able to transfer data from its current location to the current location of the mouse.

The queryDragCursor method retrieves an appropriate cursor for the drag operation, depending on the drag status. The cursor for a drag operation that can transfer the object to the current location is different from a cursor that cannot transfer the object.

Methods

queryDragCursor

public Object queryDragCursor(int effect);

Retrieves the current effect image used by the cursor as it drags an object across windows and icons.

Return Value:

Returns a cursor object that reflects the specified effect.

Parameter Description
effect The effect that the cursor provides an image for. This value can be one of the following drag effects:
CONTINUE, CANCEL, DROP, or DEFAULT_ACTION.

queryDragStatus

public int queryDragStatus(int modifiers);

Determines the current status of the drag operation.

Return Value:

Returns a drag status flag depending on the current status of the drag session. This value can be one or more of the following drag effects:
CONTINUE, CANCEL, DROP, or DEFAULT_ACTION.

Parameter Description
modifiers A flag that indicates the drag modifier for the drag operation. It can be any one of the following drag modifiers:
LBUTTON, MBUTTON, RBUTTON,
CONTROL, SHIFT, or ALT.

Fields

CANCEL
A drag-effect flag that indicates the drag operation has been cancelled.
CONTINUE
A drag-effect flag that indicates the dragged object cannot be dropped, but can continue.
DEFAULT_ACTION
A drag-effect flag that indicates that the system will determine what to do.
DROP
A drag-effect flag that indicates the dragged object can be dropped at the current location.


About com.ms.security

In this topic

* Overview of Classes

* Examples

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.security | Packages | Next

About com.ms.security

This package provides access to the security system of the Microsoft Win32 VM for Java. The security system is based on associating sets of permissions with individual classes so that the Microsoft VM can examine the call stack to determine what permissions are valid in a given context.

Overview of Classes

The StandardSecurityManager class implements a granular, permission-based security policy. The StandardSecurityManager is the installed security manager within the Microsoft VM for all Java code (except Java applications), and it processes security checks for the standard Java APIs. The StandardSecurityManager.checkXXX methods call the PolicyEngine.checkPermission methods to do the stack crawl that actually determines whether the specified operation is permitted. For instance, if your code creates a new java.io.FileOutputStream object and then attempts to write to that file, the Microsoft VM calls the StandardSecurityManager's checkWrite method, passing in the name of the file you want to write to. If the security check fails, a SecurityExceptionEx is thrown.

The PolicyEngine class contains methods that check for a particular type of permission, using either a deep or a shallow security check. A deep security check examines the call stack (beginning with the immediate caller to PolicyEngine and working backwards) and determines whether each class on the stack has the specified permission. If any class does not have the specified permission, the security check fails. If the right to the specified permission has been explicitly asserted, the stack crawl terminates immediately and the security check passes. If the right to the specified permission has been explicitly denied, the stack crawl terminates immediately and the security check fails. A shallow security check requires that you specify a skip set that indicates a set of classes to ignore during the security check. During a shallow security check, only the first class found outside the skip set is examined for the specified permission. To learn more about security checks and how to assert, deny, or revert a permission, see the PolicyEngine class.

Each permission class must implement the IPermission interface. Optionally, one or both of the IAdjustablePermission and the IEncodablePermission interfaces can be implemented. If the IAdjustablePermission interface is implemented, a permission object can be adjusted to give context information. For instance, the ThreadPermission class implements IAdjustablePermission. Therefore, a ThreadPermission object can be adjusted to indicate a ThreadGroup object that classes with the ThreadPermission should have access to. If a permission class implements the IEncodablePermission interface, the permission object can encode itself for use in digital signatures. The encoding formats that are supported (HTML, ASN, text, and others) are supplied by constants in the EncodeFormats class.

Permission types are identified by the constants in the PermissionID class. Except for PermissionID.SYSTEM, each constant corresponds to the name of a permission class that implements that type of permission. For instance, the PermissionID.REGISTRY value corresponds to the com.ms.security.permissions.RegistryPermission class. PermissionID objects are passed to the PolicyEngine.checkPermission(PermissionID,Object) methods to indicate the type of permission being checked. If you have designed a custom permission class and need a PermissionID that identifies your new class, you can call the PolicyEngine.permissionNameToID method to create a PermissionID. You can also use permissionNameToID to convert a predefined system permission name to its corresponding PermissionID.

Several of the predefined classes in the com.ms.security.permissions package implement the ISecurityRequest interface. An instance of a class that implements ISecurityRequest represents both a PermissionID and one or more parameters that are relevant to the permission type. To do a parameterized security check for a permission that has a corresponding ISecurityRequest class, you should pass an ISecurityRequest object of the appropriate type to the PolicyEngine.checkPermission(ISecurityRequest) method. The example at the end of this overview shows how to do a parameterized security check using an ISecurityRequest object. To learn more about doing security checks for predefined permissions, see the Using ISecurityRequest Objects To Perform Security Checks section of the com.ms.security.permissions overview. The com.ms.security.permissions overview also provides a list of classes that implement ISecurityRequest.

Permission objects can be grouped into a PermissionSet or a PermissionDataSet. A PermissionSet object is immutable, so you could turn your PermissionDataSet into a PermissionSet to protect your permission objects from modification. However, if you want to enumerate the permissions in the set, they must be in the form of a PermissionDataSet so that you can use the PermissionDataSetEnumerator methods. Similarly, when a set of permissions is ready to be encoded for use in a digital signature, the set must be in the form of a PermissionDataSet object. However, when the permission set is associated with a particular class (using the SecurityClassLoader methods), it should be in PermissionSet form so that it cannot be modified.

The PermissionUtils class supplies a variety of useful methods whose functionality falls into one of three categories.

  • Deep copy helpers to use when implementing IPermission.copy.
  • Comparison helpers to use when implementing SetComparison.compareSet methods.
  • Combine helpers to use when implementing IPermission.combine.

Examples

The following example illustrates one way to do a parameterized security check for the PropertyPermission that indicates permission to read the java.class.path property.

// Create a request object
PropertyAccessRequest par =
   new PropertyAccessRequest("java.class.path");
PolicyEngine.checkPermission(par);

Suppose you want to create a set of three permissions and mark a new class with those permissions. The following code could be written within a class that extends the SecurityClassLoader class.

// Create the PermissionDataSet.
PermissionDataSet pds = new PermissionDataSet();

// Create a permission object.
PropertyPermission perm1 =
   new PropertyPermission();
perm1.addAllowedProperties("java.*");

// Add the permission to the set.
pds.add(PermissionID.PROPERTY,perm1);

// Create a second permission object.
SystemStreamsPermission perm2 =
   new SystemStreamsPermission();
perm2.setCanSetSystemIn(true);

// Add the second permission to the set.
pds.add(PermissionID.SYSSTREAMS,perm2);

// Create a third permission object.
FileIOPermission perm3 = new FileIOPermission();
perm3.AddReadableFile("MySample.txt",true);
perm3.AddDeleteableFile("Useless.txt",true);

// Add the third permission to the set.
pds.add(PermissionID.FILEIO);

// Convert to a PermissionSet.
PermissionSet permSet = pds.toPermissionSet();

...
// Obtain the Principal  (prince)
// Obtain the class name (classname)
// Obtain the class data (classdata)
...

int len = classdata.length;

// Mark the class with the PermissionSet.
Class cl = defineClass(classname,classdata,0,
                       len,permSet,prince);

Classes

Class EncodeFormats
This class contains values that are used to encode permissions or retrieve information about permissions.
Class PermissionDataSet
This class represents sets of permission objects.
Class PermissionDataSetEnumerator
This class implements an enumeration of the permission identifiers stored within a PermissionDataSet object.
Class PermissionID
This class represents objects that are used to identify permission types.
Class PermissionRequestDeniedException
This class represents a security exception that is thrown by a component of the security system when a security check fails because a permission has been explicitly denied.
Class PermissionSet
This class represents an immutable form of a PermissionDataSet object.
Class PermissionTreeOutput
This class is used to create a tree representation of the permissions.
Class PermissionUtils
This class provides routines used by the permission classes.
Class PolicyEngine
This class exposes methods that perform permission-based security checks.
Class SecurityClassLoader
This class provides methods that associate permissions with classes.
Class SecurityExceptionEx
This class represents security exceptions that are thrown by a component of the security system to indicate a security violation.
Class StandardSecurityManager
This class defines a security policy that uses the permission model to perform security checks.

Interfaces

Interface IAdjustablePermission
This interface provides a method for modifying a permission object to give context information.
Interface IEncodablePermission
This interface provides methods that allow permissions to represent their internal state in any desired format.
Interface IPermission
This interface must be implemented by all classes that represent permissions.
Interface ISecurityRequest
This interface is used to associate specific types of objects with specific permission types.

Hierarchy

Object
  |
  +--EncodeFormats
  |
  +--PermissionDataSet (IEncodablePermission, com.ms.util.SetComparison)
  |
  +--PermissionDataSetEnumerator (Enumeration)
  |
  +--PermissionID
  |
  +--PermissionSet
  |
  +--PermissionUtils
  |
  +--PolicyEngine

ClassLoader
  |
  +--SecurityClassLoader

SecurityException
  |
  +--SecurityExceptionEx
     |
     +--PermissionRequestDeniedException

SecurityManager
  |
  +--StandardSecurityManager

OutputStream
  |
  +--PermissionTreeOutput

IAdjustablePermission
IEncodablePermission
IPermission
ISecurityRequest


Class EncodeFormats

public class EncodeFormats
{
  // Fields
  public static final String ASN1;
  public static final String DEFAULT;
  public static final String DESCRIPTION;
  public static final String DISPLAY;
  public static final String DISPLAYNAME;
  public static final String DISPLAYTREE;
  public static final String HTML;
  public static final String INI;
  public static final String PICS;
  public static final String TEXT;
  public static final String XML;
}

This class contains values that are used to encode permissions or retrieve information about permissions.

Fields

ASN1
The value that indicates the ASN (Abstract Syntax Notation) format.
DEFAULT
The value that indicates the default format.
DESCRIPTION
A value used to return a description of a permission.
DISPLAY
A value used to return information about a permission.
DISPLAYNAME
A value used for retrieving friendly names (for example, ToolTips text).
DISPLAYTREE
A value used for displaying permissions in tree form in the security dialog box.
HTML
The value that indicates the HTML format.
INI
Reserved.
PICS
Reserved.
TEXT
The value that indicates the text format.
XML
The value that indicates the XML (eXtensible Markup Language) format.


Class PermissionDataSet

public class PermissionDataSet implements IEncodablePermission,
             com.ms.util.SetComparison
{
  // Constructors
  public PermissionDataSet();
  public PermissionDataSet(PermissionDataSet other);

  // Methods
  public synchronized boolean add(PermissionID pid,
        IPermission perm);
  public void adjust (String tag, Object adjustment);
  public void adjustForCodebase(URL codebase);
  public void adjustWithReflectionLoader(ClassLoader cl);
  public void adjustWithThreadGroup(ThreadGroup tg);
  public synchronized PermissionDataSet combine(
        PermissionDataSet other);
  public synchronized int compare(PermissionDataSet other);
  public int compareSet (Object other);
  public synchronized PermissionDataSet copy ();
  public boolean decode(String tag, InputStream data);
  public PermissionDataSetEnumerator elements();
  public boolean encode(String tag, OutputStream out);
  public synchronized IPermission find(PermissionID pid);
  public boolean isFullyTrusted();
  public String mapFormat(String format);
  public void remove(PermissionID pid);
  public void setFullyTrusted(boolean flag);
  public int size();
  public String[] supportedFormats();
  public synchronized PermissionSet toPermissionSet();
  public String toString();
}

This class represents sets of permission objects. Methods are provided for normal container operations such as insertion, deletion, and enumeration.

While in the PermissionDataSet form, the set can be manipulated freely. However, if the PermissionDataSet is converted to a PermissionSet, the new set cannot be modified.

This class implements the IEncodablePermission and the com.ms.util.SetComparison interfaces.

Constructors

PermissionDataSet

public PermissionDataSet();

Creates a new, empty set of permission objects.

PermissionDataSet

public PermissionDataSet(PermissionDataSet other);

Creates a new set of permission objects, based on an existing PermissionDataSet object. The new set will be a copy of the existing set.

Parameter | Description
other | The existing PermissionDataSet object.

Methods

add

public synchronized boolean add(PermissionID pid,IPermission perm);

Adds a permission to the set.

Return Value:

Returns false if a permission of the same type already exists in the set; otherwise, returns true.

Parameter | Description
pid | The permission type.
perm | The permission object.

Remarks:

The permission is specified by its type, and an IPermission instance that corresponds to that type must be specified. If a permission of that type already exists in the set, the add operation fails.

adjust

public void adjust (String tag, Object adjustment);

Adjusts each permission in the set with the given parameters.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type.
adjustment | The adjustment-specific object.

Remarks:

This method calls the adjustPermission method on all of the permission objects in the set that implement the IAdjustablePermission interface.

adjustForCodebase

public void adjustForCodebase(URL codebase);

Adjusts a PermissionDataSet object to include additional access based on a codebase URL.

Return Value:

No return value.

Parameter | Description
codebase | The URL instance to pass as the second parameter when calling the adjustPermission method on the permission objects.

Remarks:

This method calls adjustPermission("codebase",codebase) on all the permission objects in the set that implement the IAdjustablePermission interface.

adjustWithReflectionLoader

public void adjustWithReflectionLoader(ClassLoader cl);

Adjusts a PermissionDataSet with a class loader that indicates whether reflection access to a given class is allowed.

Return Value:

No return value.

Parameter | Description
cl | The class loader instance to pass as the second parameter when calling the adjustPermission method on the permission objects.

Remarks:

This method calls adjustPermission("classloader",cl) on all the permission objects in the set that implement the IAdjustablePermission interface.

adjustWithThreadGroup

public void adjustWithThreadGroup(ThreadGroup tg);

Adjusts a PermissionDataSet object to include additional thread access, based on a master thread group.

Return Value:

No return value.

Parameter | Description
tg | The master thread group that is passed as the second parameter when calling the adjustPermission method on the permission objects.

Remarks:

This method calls adjustPermission("threadgroup",tg) on all the permission objects in the set that implement the IAdjustablePermission interface.

combine

public synchronized PermissionDataSet combine(PermissionDataSet other);

Combines the data in the permission set with another permission set, and returns it as a third permission set.

Return Value:

Returns a new PermissionDataSet object that contains the combined permissions.

Parameter | Description
other | The permission set to combine with the first set.

compare

public synchronized int compare(PermissionDataSet other);

Compares the permissions in the PermissionDataSet object against the permissions in another set.

Return Value:

Returns one of the following com.ms.util.SetComparison result codes:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
other | The second permission set to compare against the first.

compareSet

public int compareSet (Object other);

Compares the PermissionDataSet object to another set.

Return Value:

Returns one of the following com.ms.util.SetComparison result codes:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
other | The object that the PermissionDataSet object is being compared with.

copy

public synchronized PermissionDataSet copy ();

Copies the permission set.

Return Value:

Returns a copy of the set.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into a set of permission objects.

Return Value:

Returns true if the decoding process is completed successfully; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct this object from. The type of data in the stream is specified by the tag parameter.

elements

public PermissionDataSetEnumerator elements();

Returns an enumeration of the permission types stored within this PermissionDataSet object. This method calls the constructor for the PermissionDataSetEnumerator class.

Return Value:

Returns the enumeration object.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of the set of permissions and sends encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding process is completed successfully; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The stream to write the encoded data to.

find

public synchronized IPermission find(PermissionID pid);

Looks for a specific type of permission in the set.

Return Value:

Returns the permission object, if one is found; otherwise, returns null.

Parameter | Description
pid | The type of permission to find.

isFullyTrusted

public boolean isFullyTrusted();

Determines whether the state of the permission set is fully trusted.

Return Value:

Returns true if the permission set is fully trusted; otherwise, returns false.

mapFormat

public String mapFormat(String format);

Given an encoding type, returns a tag which can then be used to perform encode and decode operations.

Return Value:

Returns the permission-specific tag for the specified encoding format. If the specified format is not supported, null is returned.

Parameter | Description
format | The requested encoding format.

remove

public void remove(PermissionID pid);

Removes a permission from the set. If a permission of the specified type exists within the permission set, this method removes it.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to remove.

setFullyTrusted

public void setFullyTrusted(boolean flag);

Sets the fully trusted state of the permission set. If the flag parameter is true, the set is put in the special "fully trusted" state, and it is considered to contain all possible permissions.

Return Value:

No return value.

Parameter | Description
flag | The value that indicates how to set the state. If the value is true, the state will be set to fully trusted. If the value is false, the state will no longer be set to fully trusted.

size

public int size();

Retrieves the number of permissions objects contained in the set.

Return Value:

Returns the number of permission objects in the set.

supportedFormats

public String[] supportedFormats();

Returns the encoding formats that the PermissionDataSet supports.

Return Value:

Returns an array that contains identifiers for the supported formats.

toPermissionSet

public synchronized PermissionSet toPermissionSet();

Turns the PermissionDataSet into a PermissionSet. The PermissionSet form is immutable and can no longer be modified.

Return Value:

Returns the PermissionSet object that is an immutable form of the PermissionDataSet object.

toString

public String toString();

Converts the contents of the PermissionDataSet object to its textual form.

Return Value:

Returns the textual form of the permission data set.


Class PermissionDataSetEnumerator

public class PermissionDataSetEnumerator implements Enumeration
{
  // Methods
  public boolean hasMoreElements();
  public boolean hasMorePermissionIDs();
  public Object nextElement();
  public PermissionID nextPermissionID();
}

This class implements an enumeration of the permission identifiers stored within a PermissionDataSet object. To acquire a PermissionDataSetEnumerator object for a particular PermissionDataSet, call the PermissionDataSet.elements method.

Also see com.ms.security.PermissionDataSet

Methods

hasMoreElements

public boolean hasMoreElements();

Determines whether the enumeration contains additional elements. This method implements the java.util.Enumeration.hasMoreElements method.

Return Value:

Returns true if the enumeration contains additional elements; otherwise, returns false.

hasMorePermissionIDs

public boolean hasMorePermissionIDs();

Determines whether the enumeration contains additional PermissionID objects.

Return Value:

Returns true if the enumeration contains additional PermissionID objects; otherwise, returns false.

nextElement

public Object nextElement();

Retrieves the next PermissionID from the enumeration. This method implements the java.util.Enumeration.nextElement method.

Return Value:

Returns the next PermissionID object from the enumeration.

Exceptions:

java.util.NoSuchElementException if no more PermissionID objects exist in the enumeration.

nextPermissionID

public PermissionID nextPermissionID();

Retrieves the next PermissionID object from the enumeration.

Return Value:

Returns the next PermissionID object from the enumeration.

Exceptions:

java.util.NoSuchElementException if no more PermissionID objects exist in the enumeration.


Class PermissionID

public final class PermissionID
{
  // Fields
  public final static PermissionID CLIENTSTORE;
  public final static PermissionID EXEC;
  public final static PermissionID FILEIO;
  public final static PermissionID MULTIMEDIA;
  public final static PermissionID NETIO;
  public final static PermissionID PRINTING;
  public final static PermissionID PROPERTY;
  public final static PermissionID REFLECTION;
  public final static PermissionID REGISTRY;
  public final static PermissionID SECURITY;
  public final static PermissionID SYSSTREAMS;
  public final static PermissionID SYSTEM;
  public final static PermissionID THREAD;
  public final static PermissionID UI;
  public final static PermissionID USERFILEIO;

  // Methods
  public String toString();
}

This class represents objects that are used to identify permission types. The members of this class are constants that represent and identify standard system permissions.

Since there is no public constructor for this class, PermissionID objects cannot be directly created. Instead, they can be retrieved using the PolicyEngine.permissionNameToID method.

Some security APIs allow you to pass the name of the permission instead of a PermissionID object. However, the APIs that take a PermissionID object are usually faster than the variations that take permission names. This is because the APIs that take a permission name must first look up the name to map it to the corresponding PermissionID object.

Methods

toString

public String toString();

Converts the permission identifier to its string representation.

Return Value:

Returns the string representation of the permission identifier.

Fields

CLIENTSTORE
The permission identifier representing the permission type that controls access to the client storage APIs. This identifier corresponds to the permission implementation in the com.ms.security.permissions.ClientStoragePermission class.
EXEC
The permission identifier representing the permission type that controls the ability to execute applications. This identifier corresponds to the permission implementation in the com.ms.security.permissions.ExecutionPermission class.
FILEIO
A permission identifier representing the permission type that controls the ability to perform file I/O operations. This identifier corresponds to the permission implementation in the com.ms.security.permissions.FileIOPermission class.
MULTIMEDIA
This identifier corresponds to the permission implementation in the com.ms.security.permissions.MultimediaPermission class.
NETIO
The permission identifier representing the permission type that controls networking operations. This identifier corresponds to the permission implementation in the com.ms.security.permissions.NetIOPermission class.
PRINTING
The permission identifier representing the permission type that controls the ability to use the printing APIs. This identifier corresponds to the permission implementation in the com.ms.security.permissions.PrintingPermission class.
PROPERTY
The permission identifier representing the permission type that controls access to the system properties. This identifier corresponds to the permission implementation in the com.ms.security.permissions.PropertyPermission class.
REFLECTION
The permission identifier representing the permission type that controls the ability to use the reflection APIs. This identifier corresponds to the permission implementation in the com.ms.security.permissions.ReflectionPermission class.
REGISTRY
The permission identifier representing the permission type that controls access to the system registry. This identifier corresponds to the permission implementation in the com.ms.security.permissions.RegistryPermission class.
SECURITY
The permission identifier representing the permission type that controls access to the JDK security APIs. This identifier corresponds to the permission implementation in the com.ms.security.permissions.SecurityPermission class.
SYSSTREAMS
The permission identifier representing the permission type that controls the ability to set the system streams. This identifier corresponds to the permission implementation in the com.ms.security.permissions.SystemStreamsPermission class.
SYSTEM
A special permission identifier that represents all possible permissions. This identifier does not correspond to a specific permission class.
THREAD
The permission identifier representing the permission type that controls threading operations. This identifier corresponds to the permission implementation in the com.ms.security.permissions.ThreadPermission class.
UI
The permission identifier representing the permission type that controls access to extended AWT functionality. This identifier corresponds to the permission implementation in the com.ms.security.permissions.UIPermission class.
USERFILEIO
The permission identifier representing the permission type that controls access to user-directed file I/O. This identifier corresponds to the permission implementation in the com.ms.security.permissions.UserFileIOPermission class.


Class PermissionRequestDeniedException

public class PermissionRequestDeniedException extends SecurityExceptionEx
{
  // Constructors
  public PermissionRequestDeniedException();
  public PermissionRequestDeniedException(String detail);
}

This class represents a security exception that is thrown by a component of the security system when a security check fails because a permission has been explicitly denied. Permissions are explicitly denied using the PolicyEngine.denyPermission method. This class extends the SecurityExceptionEx class.

SecurityException
  |
  +--SecurityExceptionEx
    |
    +--PermissionRequestDeniedException

Constructors

PermissionRequestDeniedException

public PermissionRequestDeniedException();

Creates an instance of PermissionRequestDeniedException.

PermissionRequestDeniedException

public PermissionRequestDeniedException(String detail);

Creates an instance of PermissionRequestDeniedException with the specified detail description.

Parameter | Description
detail | The detail description that describes the error.


Class PermissionSet

public final class PermissionSet
{
  // Constructors
  public PermissionSet(PermissionDataSet pds);

  // Methods
  public PermissionDataSet getPermissions ();
}

This class represents an immutable form of a PermissionDataSet object. After a PermissionDataSet object has been converted to a PermissionSet object, the contents of the permission set can no longer be modified.

The SecurityClassLoader.defineClass method, which attaches a set of permissions to a class, requires a PermissionSet as one of its parameters.

Constructors

PermissionSet

public PermissionSet(PermissionDataSet pds);

Creates a PermissionSet object from a PermissionDataSet object. The contents of the PermissionDataSet object are copied to the PermissionSet so that any future changes to the PermissionDataSet will not affect the PermissionSet.

Parameter | Description
pds | The PermissionDataSet to copy.

Methods

getPermissions

public PermissionDataSet getPermissions ();

Copies the contents of the PermissionSet, and then returns it as a PermissionDataSet that can be examined and modified. Any changes to the resulting PermissionDataSet will not affect the original PermissionSet.

Return Value:

Returns a copy of the contents of the PermissionSet as a PermissionDataSet.


Class PermissionTreeOutput

public class PermissionTreeOutput extends OutputStream
{
  // Constructors
  public PermissionTreeOutput();

  // Methods
  public void addField();
  public void addNode(int level);
  public void addPermission(int level, IPermission perm);
  public void addPermission(int level, IPermission perm,
        boolean highRisk);
  public int count();
  public String dump();
  public void flush() throws IOException;
  public void increase();
  public int[] nodeLevel();
  public char[][] nodeValue();
  public int[] riskFactor();
  public void setStartLevel(int sl);
  public int startLevel();
  public String toString();
  public void writeField(String s) throws IOException;
  public void writeNode(String s, int level) throws IOException;
  public void writePermission(String s, int level,
        IPermission perm) throws IOException;
  public void writePermission(String s, int level,
        IPermission perm, boolean highRisk) throws IOException;
}

This class is used to create a tree representation of the permissions. In the security dialog boxes for Microsoft® Internet Explorer version 4.01, the permissions are displayed in the form of a tree control decorated with icons that indicate risk factors.

This class is used with the IEncodablePermission.encode method and the EncodeFormats.DISPLAYTREE format. To be displayed correctly in the security dialog boxes, a permission must be able to handle the EncodeFormat.DISPLAYTREE encoding type. The method that encodes the permission in DISPLAYTREE format should ensure that the OutputStream that receives the encoding is an instance of PermissionTreeOutput. Then the writePermission, writeNode, and writeField methods can be used to display information about the permission.

For instance, to add a title node for displaying the permission, you would use one of the writePermission methods. To add a sub-node heading for grouping related permission parameters, use the writeNode method. To add a leaf node that contains a specific parameter value, use the writeField method.

The following code would produce the tree displayed below. For brevity, only the mapFormat and encode methods are shown. However, your class would need to implement all the methods of the IEncodablePermission and IPermission interfaces.

public class MyPermission implements IPermission, IEncodablePermission
{
  private String treedisplaytag = "someString";
  private boolean param1;
  private int param2;
  private String param3;

  // Methods and data members are omitted for brevity.

  // Map the supported formats to tags.
  public String mapFormat(String format)
  {
    if (format == EncodeFormats.DISPLAYTREE)
      return treedisplaytag;

    // else check to see if format represents
    // another supported format.
    ...
  }

  // Encode the permission to a supported format.
  public boolean encode(String tag, OutputStream myStream)
  {
    if (tag.equals(treedisplaytag))
    {
      return encodeTreeDisplay(myStream);
    }

    // else check to see if the tag indicates
    // another supported encoding.
    ...
  }

  // Encode the permission to the DISPLAYTREE format.
  boolean encodeTreeDisplay(OutputStream myStream)
  {
    if(myStream instanceof PermissionTreeOutput)
    {
      PermissionTreeOutput tree = (PermissionTreeOutput) myStream;
      treeDisplay(tree);
      return true;
    }
    else return false;
  }

  // Write information to the tree.
  void treeDisplay(PermissionTreeOutput treeDisplay)
  {
    treeDisplay.writePermission("My Sample Permission", 0, this);
    treeDisplay.writeNode("Parameter 1", 1);
    treeDisplay.writeField("this.param1");
    treeDisplay.writeNode("Parameter 2", 1);
    treeDisplay.writeNode("Sub-Param 2", 2);
    treeDisplay.writeField("this.param2");
    treeDisplay.writeNode("Parameter 3", 1);
    .
    .
    .
  }
}

The displayed tree:

+--+ My Sample Permission
   |
   +--+ Parameter 1
   |  |
   |  +--- X (the value of param1)
   |
   +--+ Parameter 2
   |  |
   |  +--+ Sub-Param 2
   |     |
   |     +--- Y (the value of sub-param2)
   |
   +--+ Parameter 3
   .
   .
   .

Also see com.ms.security.IEncodablePermission

OutputStream
  |
  +--PermissionTreeOutput

Constructors

PermissionTreeOutput

public PermissionTreeOutput();

Creates a new PermissionTreeOutput stream.

Methods

addField

public void addField();

Creates a leaf in the tree for displaying permission parameters.

Return Value:

No return value.

addNode

public void addNode(int level);

Creates a new node for displaying a header for permission data.

Return Value:

No return value.

Parameter | Description
level | The depth of the tree at which to place the node.

addPermission

public void addPermission(int level, IPermission perm);

Inserts a node for the specified permission and assigns it a risk value based on the default permission set.

Return Value:

No return value.

Parameter | Description
level | The depth of the tree at which to place the node.
perm | The permission that is being displayed at the current node.

addPermission

public void addPermission(int level, IPermission perm,
        boolean highRisk);

Inserts a node for the specified permission. If the permission is not explicitly high risk, it is checked against the default sets to determine the risk factor.

Return Value:

No return value.

Parameter | Description
level | The depth of the tree at which to place the node.
perm | The permission that is being displayed at the current node.
highRisk | Specifies whether this permission should be flagged as high risk.

count

public int count();

Retrieves the number of elements in the tree.

Return Value:

Returns the number of elements in the tree.

setStartLevel

public void setStartLevel(int sl);

Sets the depth of the root node. Use this method when combining two (or more) separate trees into one tree.

Return Value:

No return value

Parameter | Description
sl | The depth of the root node.

startLevel

public int startLevel();

Retrieves the starting level of the root node.

Return Value:

Returns the depth of the root node.

toString

public String toString();

Converts the display tree to a String where the nodes and values are delimited by tabs and newline characters.

Return Value:

Returns a formatted text version of the tree.

writeField

public void writeField(String s) throws IOException;

Creates a leaf with the specified string as its value.

Return Value:

No return value.

Parameter | Description
s | The value to display at the leaf that is created.

Exceptions:

IOException if an error occurs while writing to the output stream.

writeNode

public void writeNode(String s, int level) throws IOException;

Creates a node with the specified string as the name for a new node in the display tree.

Return Value:

No return value.

Parameter | Description
s | The name of the node.
level | The depth of the tree at which to place the node.

Exceptions:

IOException if an error occurs while writing to the output stream.

writePermission

public void writePermission(String s, int level,
        IPermission perm) throws IOException;

Creates a node with the specified string as the name for a new permission in the display tree.

Return Value:

No return value.

Parameter | Description
s | The name of the permission.
level | The depth of the tree at which to place the node.
perm | The permission that is being displayed at the current node.

Exceptions:

IOException if an error occurs while writing to the output stream.

writePermission

public void writePermission(String s, int level, IPermission perm,
        boolean highRisk) throws IOException;

Creates a node with the specified string as the name for a new permission in the display tree. In addition, the permission can be flagged as high risk.

Return Value:

No return value.

Parameter | Description
s | The name of the permission.
level | The depth of the tree at which to place the node.
perm | The permission that is being displayed at the current node.
highRisk | Specifies whether this permission should be flagged as high risk.

Exceptions:

IOException if an error occurs while writing to the output stream.


Class PermissionUtils

public class PermissionUtils
{
  // Methods
  public static String ArraytoString (Object o);
  public static IntRanges[] combineArraysOfIntRanges (
        IntRanges[] r1, IntRanges[] r2);
  public static String[] combineArraysOfStrings (String[] list1,
        String[] list2);
  public static WildcardExpression combinePatterns (
        WildcardExpression spec1, WildcardExpression spec2);
  public static Vector combineVectorsOfIntRanges (Vector v1, Vector
        v2);
  public static int compareArraysOfStrings (String[] list1,
        String[] list2, int cmp);
  public static int compareBooleans (boolean f1, boolean f2,
        int prevcmp);
  public static int compareFlags (int flags1, int flags2, int mask,
        int prevcmp);
  public static int compareIncludeExcludePatterns (
        WildcardExpression include1, WildcardExpression exclude1,
        WildcardExpression include2, WildcardExpression exclude2,
        int cmp );
  public static int compareInclusiveBooleans (boolean f1,
        boolean f2, int prevcmp);
  public static int compareInclusiveFlags (int flags1, int flags2,
        int mask, int prevcmp);
  public static int compareLimits (long limit1, long limit2,
        int prevcmp);
  public static String ComparisonResulttoString (int cmp);
  public static Vector concatVectors (Vector v1, Vector v2);
  public static IntRanges[] copyArrayOfIntRanges (IntRanges[] ap);
  public static Vector[] copyArrayOfVectorsOfIntRanges (
        Vector[] av);
  public static WildcardExpression[] copyArrayOfWildcardExpressions
        (WildcardExpression[] ap);
  public static Vector copyVectorOfIntRanges (Vector v);
  public static int invertComparisonResult (int cmp);
  public static int mergeComparisonResults (int cmp1, int cmp2);
  public static String[] parseStringIntoArray(String str,
        String delims);
}

This class provides routines used by the permission classes. It includes several methods that assist with copying, comparing, and combining assorted types of elements of permissions. Three categories of functions describe the methods in this class:

  • Deep copy helpers for implementing IPermission.copy. The object returned is completely independent of the original, and changes made to the original or to the copy will not affect the other. In other words, containers return a new container, containing a clone of each element; elements that are containers recursively copy their elements.
  • Comparison helpers for implementing compareSet. These helper methods include methods for comparing simple types and String arrays. The mergeComparisonResults method is also included for combining the results for individual aspects of a permission into a single result for the entire permission.
  • Combining helpers for implementing IPermission.combine. With one exception, which is the concatVectors method, all of these methods return the concatenation of deep copies of two objects.

Methods

ArraytoString

public static String ArraytoString (Object o);

Recursively constructs a string representation for an array of any type and for each of its elements.

Return Value:

Returns a string representation of the specified array.

Parameter | Description
o | The array to construct the string representation of. The component type can be any class type or any primitive type.

Exceptions:

IllegalArgumentException if the specified object is not an array.

combineArraysOfIntRanges

public static IntRanges[] combineArraysOfIntRanges (IntRanges[] r1,
        IntRanges[] r2);

Copies two arrays of IntRanges into a new array. The elements are copied using IntRanges.copy.

Return Value:

Returns a new array containing copies of the elements of r1, followed by copies of the elements of r2.

Parameter | Description
r1 | The first array of IntRanges, or null.
r2 | The second array of IntRanges, or null.

combineArraysOfStrings

public static String[] combineArraysOfStrings (String[] list1,
        String[] list2);

Copies two arrays of strings into a new list. The strings in list1 are copied first into the new list, followed by the strings in list2.

Return Value:

Returns a new list containing copies of the strings in list1, followed by copies of the strings in list2.

Parameter | Description
list1 | The first list of strings, or null.
list2 | The second list of strings, or null.

combinePatterns

public static WildcardExpression combinePatterns (WildcardExpression spec1,
        WildcardExpression spec2);

Combines two WildcardExpression objects. The resulting expression will first match any strings that are matched by the first expressions, followed by the strings matched by the second expression. The combined expression is independent of the original expressions; changes to the combined expression will not affect the originals and vice versa.

Return Value:

Returns a new expression, matching any strings matched by spec1 or spec2, in that order.

Parameter | Description
spec1 | The first source expression to combine, or null.
spec2 | The second source expression to combine, or null.

combineVectorsOfIntRanges

public static Vector combineVectorsOfIntRanges (Vector v1, Vector v2);

Combines two vectors containing IntRanges objects.

Return Value:

Returns a new vector containing the elements of v1, followed by the elements of v2.

Parameter | Description
v1 | The first Vector of IntRanges, or null.
v2 | The second Vector of IntRanges, or null.

compareArraysOfStrings

public static int compareArraysOfStrings (String[] list1, String[] list2,
        int cmp);

Compares two arrays of strings.

Return Value:

Returns a new comparison result, merged with the specified previous comparison result using mergeComparisonResults.

Parameter | Description
list1 | The first list of strings, or null.
list2 | The second list of strings, or null.
cmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

compareBooleans

public static int compareBooleans (boolean f1, boolean f2, int prevcmp);

Compares two booleans. Each boolean represents access to resources that are independent of the other resources of the permissions.

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

The following table shows how booleans are compared by this method.
f1 | f2 | Result before merging
true | true | SetComparison.EQUAL
true | false | SetComparison.EMPTY_SUPERSET
false | true | SetComparison.EMPTY_SUBSET
false | false | SetComparison.EMPTY

Parameter | Description
f1 | If true, access to the resource in the first permission is granted; otherwise, access is denied.
f2 | If true, access to the resource in the second permission is granted; otherwise, access is denied.
prevcmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

compareFlags

public static int compareFlags (int flags1, int flags2, int mask,
        int prevcmp);

Compares two sets of flags. Each flag represents access to resources that are independent of other resources of the permissions. The flags to be compared are selected by a bitmask and are compared as a unit.

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

The following table shows the results of comparing different sets of flags.
flags1 & mask | flags2 & mask | Result before merging
nonzero | nonzero | SetComparison.EQUAL
nonzero | zero | SetComparison.EMPTY_SUPERSET
zero | nonzero | SetComparison.EMPTY_SUBSET
zero | zero | SetComparison.EMPTY

Parameter | Description
flags1 | The flags that determine access to resources in the first permission
flags2 | The flags that determine access to resources in the second permission.
mask | A bitmask that is combined with the flags (using the logical AND operator (&)) to determine which resources are to be compared as a unit.
prevcmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

compareIncludeExcludePatterns

public static int compareIncludeExcludePatterns (
        WildcardExpression include1, WildcardExpression exclude1,
        WildcardExpression include2, WildcardExpression exclude2, int cmp );

Compares sets of resources specified by include/exclude patterns. The include pattern specifies resources for which access will be granted, and the exclude rules specify resources that are to be excluded from the include rules.

The following table lists several include/exclude pairs and specifies the result obtained by comparing each pair using this method.
Pair 1 Pair 2 Result
include *
exclude *.txt 		include * SUBSET
include *
exclude *.txt 		include *.doc SUPERSET
include *
exclude *.txt 		include *
exclude *.doc 		OVERLAP
include *
exclude *.txt 		include *
exclude foo.txt 		SUBSET
include *
exclude *.txt 		include *.txt DISJOINT

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

Parameter | Description
include1 | For the first permission, the patterns that specify resources to grant access to, or null.
exclude1 | For the first permission, the patterns that specify resources to exclude from the include rules.
include2 | For the second permission, the patterns that specify resources to grant access to.
exclude2 | For the second permission, the patterns that specify resources to exclude from the include rules.
cmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

Exceptions:

IllegalArgumentException if any of the exclude rules are not a subset of one or more of the include rules, or if the exclude rules are specified without the include rules.

compareInclusiveBooleans

public static int compareInclusiveBooleans (boolean f1, boolean f2,
        int prevcmp);

Compares two booleans that represent inclusive access to resources. A boolean value of false means that access to resources may be granted; a value of true means that more resources will be granted. Typically, this comparator is used only when the possession of the permission itself has meaning, because it becomes impossible to determine DISJOINT or EMPTY permissions after use of this comparator.

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

The following table shows how booleans are compared by this method.
f1 | f2 | Result before merging
true | true | SetComparison.EQUAL
true | false | SetComparison.SUPERSET
false | true | SetComparison.SUBSET
false | false | SetComparison.EQUAL

Parameter | Description
f1 | A flag that specifies the type of access to the resource in the first permission. If false, access to the resource is not denied; if true, more privileged access to the resource is granted.
f2 | A flag that specifies the type of access to the resource in the second permission. If false, access to the resource is not denied; if true, more privileged access to the resource is granted.
prevcmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

compareInclusiveFlags

public static int compareInclusiveFlags (int flags1, int flags2, int mask,
        int prevcmp);

Compares two sets of flags that represent inclusive access to resources. The flags to be compared are selected by a bitmask and are compared as a unit. A clear flag means that access to resources may be granted; a set flag means that more resources will be granted. Typically, this comparator is only used when the possession of the permission itself has meaning, because it becomes impossible to determine DISJOINT or EMPTY permissions after use of this comparator.

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

The following table shows how flags are compared by this method.
flags1 & mask | flags2 & mask | Result before merging
nonzero | nonzero | SetComparison.EQUAL
nonzero | zero | SetComparison.SUPERSET
zero | nonzero | SetComparison.SUBSET
zero | zero | SetComparison.EQUAL

Parameter | Description
flags1 | The flags that specify the type of access to the resource in the first permission. If bits are clear, access to the resource is not denied; if bits are set, more privileged access to the resource is granted.
flags2 | The flags that specify the type of access to the resource in the second permission. If bits are clear, access to the resource is not denied; if bits are set, more privileged access to the resource is granted.
mask | A bitmask that is combined with the flags (using the logical AND operator (&)) to determine which resources to compare as a unit.
prevcmp | A previous comparison result for other resources of the permissions. For the first resource of a permission, this is typically SetComparison.EMPTY.

compareLimits

public static int compareLimits (long limit1, long limit2, int prevcmp);

Compares two positive numerical limits. A higher value is considered more privileged.

Return Value:

Returns a new comparison result, merged with the previous comparison result using mergeComparisonResults.

The following table shows how limits are compared by this method.
limit1 | limit2 | Result before merging
0 | 0 | SetComparison.EMPTY
>0 | 0 | SetComparison.EMPTY_SUPERSET
0 | >0 | SetComparison.EMPTY_SUBSET
>limit2 | >0 | SetComparison.SUPERSET
>0 | >limit1 | SetComparison.SUBSET
=limit2 | =limit1 | SetComparison.EQUAL

Parameter | Description
limit1 | The first numerical limit.
limit2 | The second numerical limit.
prevcmp | A previous comparison result.

ComparisonResulttoString

public static String ComparisonResulttoString (int cmp);

Converts com.ms.util.SetComparison results to a string format.

Return Value:

Returns one of the following result strings:

  • "empty" (EMPTY)
  • "equal" (EQUAL)
  • "disjoint" (DISJOINT)
  • "overlap" (OVERLAP)
  • "inclusive subset" (SUBSET)
  • "inclusive superset" (SUPERSET)
  • "empty subset" (EMPTY_SUBSET)
  • "empty superset" (EMPTY_SUPERSET)

Parameter | Description
cmp | A comparison result from the SetComparison.compareSet method.

concatVectors

public static Vector concatVectors (Vector v1, Vector v2);

Combines two vectors by copying their contents into a new Vector.

Caution This is not a deep copy. It is only safe for use with the IPermission.combine method when the element type is immutable, such as the String type.

Return Value:

Returns a new vector containing the elements of v1, followed by the elements of v2. If either of the vectors are null, the other non-null vector is returned.

Parameter | Description
v1 | The first vector to combine, or null.
v2 | The second vector to combine, or null.

copyArrayOfIntRanges

public static IntRanges[] copyArrayOfIntRanges (IntRanges[] ap);

Returns a deep copy of an array of IntRanges objects. Each element is copied using the IntRanges.copy method.

Return Value:

Returns null if ap is null; otherwise, returns a new array that contains copies of the elements of ap.

Parameter | Description
ap | An array of IntRanges, or null. The array can contain null elements.

copyArrayOfVectorsOfIntRanges

public static Vector[] copyArrayOfVectorsOfIntRanges (Vector[] av);

Returns a deep copy of an array of Vectors containing IntRanges objects. Each Vector is copied using copyVectorOfIntRanges.

Return Value:

Returns null if av is null; otherwise, a new array of vectors is returned that contains new vectors with copies of their elements.

Parameter | Description
av | An array of Vectors, or null. The elements of the array or the vectors can be null.

copyArrayOfWildcardExpressions

public static WildcardExpression[] copyArrayOfWildcardExpressions (
        WildcardExpression[] ap);

Returns a deep copy of an array of WildcardExpressions. Each expression is copied using WildcardExpression.copy.

Return Value:

Returns null if ap is null; otherwise, a new array is returned that contains copies of the elements of ap.

Parameter | Description
ap | An array of WildcardExpressions, or null.

copyVectorOfIntRanges

public static Vector copyVectorOfIntRanges (Vector v);

Returns a deep copy of a vector of IntRanges objects. Each element is copied using the IntRanges.copy method.

Return Value:

Returns a new Vector object containing copies of the elements of v, or returns null if v is null.

Parameter | Description
v | The vector of IntRanges to copy, or null. The vector can contain null elements.

invertComparisonResult

public static int invertComparisonResult (int cmp);

Inverts comparison results.

Return Value:

Returns the inverted comparison result, described as follows:

  • If cmp is SUBSET, SUPERSET is returned.
  • If cmp is SUPERSET, SUBSET is returned.
  • If cmp is EMPTY_SUBSET, EMPTY_SUPERSET is returned.
  • If cmp is EMPTY_SUPERSET, EMPTY_SUBSET is returned.

Any other result is not affected by this method and is simply returned. Notice that EQUAL and DISJOINT are not inverted by this method.

Parameter Description
cmp The result to be inverted. It can be any of the following comparison results of the compare method:
  • SetComparison.SUBSET returns SetComparison.SUPERSET.
  • SetComparison.SUPERSET returns SetComparison.SUBSET.
  • SetComparison.EMPTY_SUBSET returns SetComparison.EMPTY_SUPERSET.
  • SetComparison.EMPTY_SUPERSET returns SetComparison.EMPTY_SUBSET.

mergeComparisonResults

public static int mergeComparisonResults (int cmp1, int cmp2);

Merges the comparison results from SetComparison.compareSet of two different sets into one, as though they were part of the same set.

Return Value:

Returns the merged comparison result.

Parameter | Description
cmp1 | The first comparison result.
cmp2 | The second comparison result.

parseStringIntoArray

public static String[] parseStringIntoArray(String str,String delims);

Splits a string into an array of strings at the specified delimiters.

Return Value:

Returns the string that results from parsing.

Parameter | Description
str | The string that is parsed.
delims | The delimiters to use when parsing.


Class PolicyEngine

public class PolicyEngine
{
  // Methods
  public static native void assertPermission(PermissionID pid);
  public static void checkCallerForAllPermissions(Class[] skipset);
  public static void checkCallersPermission(PermissionID pid,
        Class[] skipset);
  public static void checkCallersPermission(String pname,
        Class[] skipset);
  public static void checkCallersPermission(PermissionID pid,Object
        sreq,Class[] skipset);
  public static void checkCallersPermission(String pname,
        Object sreq,Class[] skipset);
  public static void checkCallersPermission(ISecurityRequest sreq,
        Class[] skipset);
  public static void checkClass(Class cls,PermissionID pid);
  public static void checkClass(Class cls,String pname);
  public static void checkClass(Class cls,PermissionID pid,
        Object sreq);
  public static void checkClass(Class cls,ISecurityRequest sreq);
  public static void checkClassForAllPermissions(Class cls);
  public static void checkForAllPermissions();
  public static void checkPermission(PermissionID pid);
  public static void checkPermission(String pname);
  public static void checkPermission(PermissionID pid,Object sreq);
  public static void checkPermission(String pname,Object sreq);
  public static void checkPermission(ISecurityRequest sreq);
  public static native void denyPermission(PermissionID pid);
  public static Class getClassOfCaller ();
  public static Class getClassOfCaller (Class[] skip);
  public static native PermissionDataSet getPermissionsOfClass (
        Class c);
  public static native Principal getPrincipalOfClass (Class c);
  public static synchronized PermissionID permissionNameToID(String
        pname);
  public static native void revertPermission(PermissionID pid);
}

This class exposes methods that perform permission-based security checks. These security checks are based on a security model that allows you to associate sets of permissions with the classes in the system. Then, at any point in time, the execution context can be examined to determine which operations are allowed by the permissions active within that context. The class types found on the call stack provide the required information about the active permissions. For more information about permissions, see the com.ms.security package overview.

The PolicyEngine class provides several different ways to examine the execution context to determine whether a given operation is allowed. The two main types of security checks are deep checks and shallow checks. Deep checks examine the entire call stack to ensure that all the classes within that execution context possess a certain permission. The PolicyEngine.checkPermission methods perform deep checks. In contrast, shallow checks do not use the depth of the stack to determine when to terminate the stack crawl. They are provided as a means of implementing roughly the same type of behavior as the original JDK SecurityManager methods classDepth and classLoaderDepth. The PolicyEngine.checkCallersPermission methods perform shallow checks. In general, deep checks are preferred over shallow checks.

Deep security checks are implemented in the following way: The stack is examined, starting with the immediate caller to the PolicyEngine class and working backward.

During a deep security check, the following steps are taken:

  1. Get the set of permissions associated with the class type of the stack frame, and then find the IPermission instance for the specific type of permission that is being checked for within that set.
  2. If the permission set does not contain an instance of the type of permission that is being searched for, terminate the stack crawl. The check fails.
  3. If this is a parameterized check, call the check method (IPermission.check) on the permission instance that has been found, passing it the security request object. If the check method throws an exception, terminate the stack crawl. The check fails.
  4. If the permission type has been explicitly denied by the current stack frame (using the denyPermission method), terminate the stack crawl. The security check fails.
  5. If the permission type has been explicitly asserted by the current stack frame (using the assertPermission method), terminate the stack crawl. The security check succeeds.
  6. The current frame has passed. Continue the stack crawl with the next frame.

Shallow security checks only check the immediate caller outside a boundary that is defined by a specified skip set. A skip set is a set of classes that is ignored during the security check. The first (and only the first) class found outside of the skip set will be checked for the permissions in question.

Shallow security checks are implemented in the following way. The stack is examined, starting with the immediate caller to the PolicyEngine class, and working backward. During a shallow security check, the following steps are taken:

  1. Get the class type associated with the current stack frame. If the class type is not within the specified skip set, the frame that should be checked has been found. Proceed to step 4.
  2. The class type of the current frame is in the skip set; however, the stack frame must still be checked for any explicit assertions or denials. If the permission type has been explicitly denied by the current stack frame (using the denyPermission method), terminate the stack crawl. The security check fails. If the permission type has been explicitly asserted by the current stack frame (using the assertPermission method), terminate the stack crawl. The security check succeeds.
  3. Since this frame was in the skip set, and no assertions or denials stopped the crawl, search for the next frame and continue the crawl. Proceed to step 1.
  4. The frame to be examined has been found. Get the set of permissions associated with the class type of the stack frame, and then find the IPermission instance for the specific type of permission that is being checked for within that set.
  5. If the permission set does not contain an instance of the type of permission that is being searched for, terminate the stack crawl. The security check fails.
  6. If this is a parameterized check, call the check method (IPermission.check) on the permission instance that was found, passing it the security request object. If the check method throws an exception, terminate the stack crawl. The security check fails.
  7. The current frame has passed, so terminate the stack crawl. The security check succeeds.

Deep and shallow security checks are provided in both parameterized and unparameterized forms.

Unparameterized checks simply ensure that all the classes in question possess a certain type of permission. This type of check is used for simple permissions, like the printing permission. Either a class has the printing permission or it doesn't.

Parameterized checks are used for more complex permissions, where the parameter to the check method is an object that is specific to the permission type. For instance, when checking for the file I/O permission, you must specify exactly which file I/O operation is being attempted and which file is involved. To check file I/O permission, you would create an instance of the com.ms.security.permissions.FileIORequest class that indicates which file is involved and which I/O operation is requested. You would then call the PolicyEngine.checkPermission(ISecurityRequest) method, passing in the FileIORequest object. If the check succeeds (no SecurityException is thrown), the specified operation is allowed.

Methods

assertPermission

public static native void assertPermission(PermissionID pid);

Asserts the right to a certain type of permission. This method causes the security system to ignore your callers when you cause a security check of the asserted type to occur.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to assert.

Remarks:

Normally, when checking a given permission, the security system examines every frame on the call stack to ensure that all the callers possess the ability to perform the operation in question. However, if the security system sees a stack frame where the requested permission has been asserted (with this method), the stack crawl stops early and the security check succeeds.

The asserted permission state disappears when the stack frame of the caller to assertPermission exits (by executing a return statement or throwing an exception). The revertPermission method can be used to un-assert a permission type.

The following example shows how to assert the right to perform file I/O operations.

   ...
   // Assert the right to perform file I/O
   PolicyEngine.assertPermission(PermissionID.FILEIO);

   // Now, do some file operation. Since you have asserted
   // your rights to file I/O, this check will succeed even if your callers do
   // not possess the ability to perform file I/O.
   FileInputStream fis = new FileInputStream("c:\\MySample.txt");
   ...

Note To assert all permissions, pass PermissionID.SYSTEM to the assertPermission method. This assertion forces the security system to ignore your callers during all security checks. Only fully trusted code can assert the SYSTEM permission.

See Also: denyPermission, revertPermission

checkCallerForAllPermissions

public static void checkCallerForAllPermissions(Class[] skipset);

Performs a security check to determine whether the first calling class outside the skip set is fully trusted.

Note Permission assertions and denials of the permission type PermissionID.SYSTEM are recognized within the skip set frames. They will affect the stack crawl and could cause it to terminate early.

Return Value:

No return value.

Parameter | Description
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkCallersPermission

public static void checkCallersPermission(PermissionID pid,Class[] skipset);

Performs a simple (non-parameterized) security check for a specific type of permission. This check is shallow. Only the first stack frame found outside the specified skip set will be checked.

Note Permission assertions and denials are recognized within the skip set frames, and could cause the stack crawl to terminate early.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to check for.
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkCallersPermission

public static void checkCallersPermission(String pname,Class[] skipset);

Performs a simple (non-parameterized) security check for a specific type of permission. This check is shallow. Only the first stack frame found outside the specified skip set will be checked. A permission name is used to specify the permission type (instead of a PermissionID).

Note Permission assertions and denials are recognized within the skip set frames, and could cause the stack crawl to terminate early.

Return Value:

No return value.

Parameter | Description
pname | The name of the permission to check for.
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkCallersPermission

public static void checkCallersPermission(PermissionID pid,Object sreq,
        Class[] skipset);

Performs a parameterized security check for a specific type of permission. The check is shallow. Only the first stack frame found outside the specified skip set will be checked.

Note Permission assertions and denials are recognized within the skip set frames, and may cause the stack crawl to terminate early.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to check for.
sreq | The security request object that indicates the specific resource to check for within the realm of the permission type. The type of the object depends on the type of the permission being checked.
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkCallersPermission

public static void checkCallersPermission(String pname,Object sreq,
        Class[] skipset);

Performs a parameterized security check for a specific type of permission. The check is shallow. Only the first stack frame found outside the specified skip set will be checked. A permission name is used to specify the permission type (instead of a PermissionID).

Note Permission assertions and denials are recognized within the skip set frames, and may cause the stack crawl to terminate early.

Return Value:

No return value.

Parameter | Description
pname | The name of the permission to check for.
sreq | The security request object.
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkCallersPermission

public static void checkCallersPermission(ISecurityRequest sreq,
        Class[] skipset);

Performs a parameterized security check for a specific type of permission. The check is shallow. Only the first stack frame found outside the specified skip set will be checked.

This method is a variation on the checkCallersPermission(PermissionID,Object,Class[]) method, where the sreq parameter indicates the permission type, and it also represents the security request object.

Return Value:

No return value.

Parameter | Description
sreq | The object that indicates the type of permission to check for and represents the security request object.
skipset | The set of classes to ignore on the call stack.

Exceptions:

SecurityException if the security check fails.

checkClass

public static void checkClass(Class cls,PermissionID pid);

Performs a security check directly against a specified class. If the class does not possess the specified type of permission, a SecurityException is thrown.

Return Value:

No return value.

Parameter | Description
cls | The class to check against.
pid | The type of permission to check for.

Exceptions:

SecurityException if the security check fails.

checkClass

public static void checkClass(Class cls,String pname);

Performs a security check directly against a specified class. If the class does not possess the specified type of permission, a SecurityException is thrown. The permission type is specified as a permission name (instead of a PermissionID object).

Return Value:

No return value.

Parameter | Description
cls | The class to check against.
pname | The name of the permission to check for.

Exceptions:

SecurityException if the security check fails.

checkClass

public static void checkClass(Class cls,PermissionID pid,Object sreq);

Performs a security check directly against a specified class. The class must possess the specified type of permission, and the parameterized check against the class's associated permission object must pass, or a SecurityException is thrown.

Return Value:

No return value.

Parameter | Description
cls | The class to check against.
pid | The type of permission to check for.
sreq | The security request object.

Exceptions:

SecurityException if the security check fails.

checkClass

public static void checkClass(Class cls,ISecurityRequest sreq);

Performs a security check directly against a specified class. The class must possess the specified type of permission, and the parameterized check against the class's associated permission object must pass, or a SecurityException is thrown.

Parameter | Description
cls | The class to check against.
sreq | The object that determines the type of permission to check for and also represents the security request object.

Remarks:

This method is a variation on the checkClass(Class,PermissionID,Object) method, where the ISecurityRequest object is used to determine the permission type, and it is also used as the permission request object.

Exceptions:

SecurityException if the security check fails.

checkClassForAllPermissions

public static void checkClassForAllPermissions(Class cls);

Performs a security check directly against a class object. If the class is not fully trusted, the security check fails.

Return Value:

No return value.

Parameter | Description
cls | The class to check against.

Exceptions:

SecurityException if the security check fails.

checkForAllPermissions

public static void checkForAllPermissions();

Performs a security check to determine whether all the calling class types on the call stack are fully trusted. If any of the calling classes are not fully trusted, the security check fails (a SecurityException is thrown).

Note Permission assertions and denials on the permission type PermissionID.SYSTEM affect the stack crawl, causing it to terminate early without examining the entire stack.

Return Value:

No return value.

Exceptions:

SecurityException if the security check fails.

checkPermission

public static void checkPermission(PermissionID pid);

Performs a simple (non-parameterized) security check for a specified type of permission. For the security check to pass, all the callers on the call stack must possess the specified type of permission.

Note Permission assertions and denials might affect the stack crawl, which could cause it to terminate early without examining the entire stack.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to check for.

Exceptions:

SecurityException if the security check fails.

checkPermission

public static void checkPermission(String pname);

Performs a simple (non-parameterized) security check for a specified type of permission. A permission name is used to specify the permission type. For the security check to pass, all the callers on the call stack must possess the specified type of permission.

Note Permission assertions and denials might affect the stack crawl, causing it to terminate early without examining the entire stack.

Return Value:

No return value.

Parameter | Description
pname | The name of the permission to check for.

Exceptions:

SecurityException if the security check fails.

checkPermission

public static void checkPermission(PermissionID pid,Object sreq);

Performs a parameterized security check for a specific type of permission.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to check for.
sreq | The security request object that indicates the specific resource to check for within the realm of the permission type. The type of this object depends on the type of the permission being checked.

Remarks:

For the security check to pass, all the callers on the call stack must possess the specified type of permission. In addition, all the permission objects associated with the calling class types found on the stack must validate that the operation indicated by the security request object is allowed. Validation is accomplished by calling the IPermission.check method of all the found permission instances.

Note Permission assertions and denials might affect the stack crawl, causing it to terminate early without examining the entire stack.

Exceptions:

SecurityException if the security check fails.

checkPermission

public static void checkPermission(String pname,Object sreq);

Performs a parameterized security check for a specific type of permission. A permission name is used to specify the permission type (instead of a PermissionID).

Return Value:

No return value.

Parameter | Description
pname | The name of the permission to check for.
sreq | The security request object that indicates the specific resource to check for within the realm of the permission type. The type of this object depends on the type of the permission being checked.

Remarks:

For the security check to pass, all the callers on the call stack must possess the specified type of permission. In addition, all the permission objects associated with the calling class types found on the stack must validate that the operation indicated by the security request object is allowed. Validation is accomplished by calling the IPermission.check method of all the found permission instances.

Note Permission assertions and denials might affect the stack crawl, causing it to terminate early without examining the entire stack.

Exceptions:

SecurityException if the security check fails.

checkPermission

public static void checkPermission(ISecurityRequest sreq);

Performs a parameterized security check for a specific type of permission. This method is a variation on the checkPermission(PermissionID,Object) method where the sreq parameter is used to determine the permission type and is also used as the security request object.

Calling the checkPermission(ISecurityRequest) method is equivalent to the following call.

   checkPermission(sreq.getPermissionID(),sreq);

Return Value:

No return value.

Parameter | Description
sreq | The object that determines the permission type and indicates the resource to check for.

Exceptions:

SecurityException if the security check fails.

See Also: PolicyEngine.checkPermission(PermissionID,Object)

denyPermission

public static native void denyPermission(PermissionID pid);

Denies the right to a certain type of permission. Any stack-based security checks (for the specific type of permission that has been denied) that encounter the stack frame of the caller to denyPermission will fail. This forces the methods that you call to assert their permissions (using the assertPermission method) to pass security checks.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to deny.

Remarks:

Normally, when checking a given permission, the security system examines every frame on the call stack to ensure all the callers possess the ability to perform the operation in question. If the security system sees a stack frame where that permission has been denied (with this method), the stack crawl stops early and the security check fails.

The denied permission state will disappear when the stack frame of the caller to denyPermission exits (by executing a return statement or throwing an exception). The revertPermission method can be used to un-deny a permission type.

The following example shows you how to deny the right to perform file I/O operations.

   ...
   // Deny your right to perform file I/O.

   PolicyEngine.denyPermission(PermissionID.FILEIO);

   // Now, call into some other code in the MySample
   // class. If that code wants to perform some file I/O operations,
   // it must assert its rights to do so, or the file I/O
   // security checks will fail because you have denied your rights to
   // them.

   MySample.doSomething();

   ...

Note To deny all permissions, pass PermissionID.SYSTEM to the denyPermission method. This forces any code you call to assert its rights to any permissions it needs to utilize. Only fully trusted code can deny the SYSTEM permission.

See Also: assertPermission, revertPermission

getClassOfCaller

public static Class getClassOfCaller ();

Retrieves the class type of the immediate caller of this method.

Return Value:

Returns the class type of the immediate caller of this method.

getClassOfCaller

public static Class getClassOfCaller (Class[] skip);

Retrieves the class type of the caller of this method, skipping any classes found in the specified skip set.

Return Value:

Returns the class type of the caller.

Parameter | Description
skip | The set of classes to ignore.

getPermissionsOfClass

public static native PermissionDataSet getPermissionsOfClass (Class c);

Obtains the permissions of a class. Only fully trusted classes are allowed to call this method.

Return Value:

Returns the permissions of the specified class.

Parameter | Description
c | The class whose permissions are being obtained.

getPrincipalOfClass

public static native Principal getPrincipalOfClass (Class c);

Obtains the principal associated with a specified class. Only fully trusted classes are allowed to call this method.

Return Value:

Returns the principal associated with the specified class.

Parameter | Description
c | The class to examine.

Exceptions:

SecurityException if the calling class is not fully trusted.

permissionNameToID

public static synchronized PermissionID permissionNameToID(String pname);

Creates a PermissionID object from a permission name.

Return Value:

Returns the PermissionID that maps to the specified permission name.

Parameter | Description
pname | The name of the permission.

Remarks:

Permission names must be the name of the class that implements the permission. The permission class must be a fully trusted system class. Only fully trusted code can create new permission identifiers.

revertPermission

public static native void revertPermission(PermissionID pid);

Negates the effects of any assertions (assertPermission) or denials (denyPermission) that have been performed for the specified permission type by the current stack frame.

Return Value:

No return value.

Parameter | Description
pid | The type of permission to revert.

Remarks:

The following example asserts a right, and then reverts it.

   ...

   // Assert your rights to perform file I/O operations

   PolicyEngine.assertPermission(PermissionID.FILEIO);

   // Do some file I/O. Your callers will be ignored during
   // the file I/O security check that this operation causes
   // because you have asserted your rights.

   FileInputStream fis = new FileInputStream("c:\\MySample.txt");

   // Remove the file I/O assertion.

   PolicyEngine.revertPermission(PermissionID.FILEIO);

   // Do some more file I/O. This time your callers will be
   // included in the security check since
   // your file I/O rights are no longer asserted.

   FileInputStream fis = new FileInputStream("c:\\MySample.txt");
   ...

See Also: assertPermission, denyPermission


Class SecurityClassLoader

public abstract class SecurityClassLoader extends ClassLoader
{
  // Fields
  protected URL codeBase;
  protected ThreadGroup threadGroup;

  // Constructors
  protected SecurityClassLoader();

  // Methods
  protected final synchronized Class defineClass( String name,
        byte data[],int offset,int length,
        PermissionSet permissions,Principal principal);
  protected Class findPackageManagerClass(String name)
        throws ClassNotFoundException;
  protected Class findPackageManagerClass(String name,
        boolean fNameSpaceOnly) throws ClassNotFoundException;
  protected InputStream findPackageManagerResource(String name);
  public Object getSecurityContext();
  public ThreadGroup getThreadGroup();
  protected void setCodeBase(URL codeBase);
  protected void setPackageManagerNamespace(String namespace);
  protected void setThreadGroup(ThreadGroup tg);
}

This class provides methods that associate permissions with classes. You can specify the permissions and a java.security.Principal object to associate with a new class.

ClassLoader
  |
  +--SecurityClassLoader

Constructors

SecurityClassLoader

protected SecurityClassLoader();

Instantiates a new SecurityClassLoader instance.

Exceptions:

SecurityException if all of the callers on the current execution stack are not fully trusted.

Methods

defineClass

protected final synchronized Class defineClass( String name,byte data[],int
        offset,int length, PermissionSet permissions,Principal principal);

Converts an array of bytes into an instance of Class and associates the new class with a set of permissions and a principal.

Return Value:

Returns the Class object that was created from the data.

Parameter | Description
name | The expected name of the class, using "." (not "/") as a separator, and without a trailing .class suffix. This value will be null if the name is unknown.
data | The bytes that make up the class.
offset | The start offset of the class data.
length | The length of the class data.
permissions | The permissions to associate with the new class. The value can be null, in which case the new class will have no associated permissions.
principal | The principal to associate with the new class. The value can be null, in which case the new class will have no associated principal.

Remarks:

This method is similar to the java.lang.Class.defineClass method with the added ability to associate a set of permissions with a class. As with the java.lang.Class.defineClass method, the class must be resolved before it can be used.

Exceptions:

ClassFormatError if the data does not contain a valid Class.

findPackageManagerClass

protected Class findPackageManagerClass(String name)
        throws ClassNotFoundException;

Finds a specified class from the package manager. Within the package manager, this method will search for the class in both the global namespace and the namespace associated with the loader (if any). Calling this method is equivalent to calling findPackageManagerClass(name,false).

Return Value:

Returns a package manager class with the specified name.

Parameter | Description
name | The name of the class.

Exceptions:

ClassNotFoundException if this method cannot find a definition for the class.

findPackageManagerClass

protected Class findPackageManagerClass(String name,boolean fNameSpaceOnly)
        throws ClassNotFoundException;

Finds a specified class from the package manager. If the class is found, it will be marked with the set of permissions that are associated with its package within the package manager. The principal associated with the class will be based on the principal that the package manager associates with its package.

Return Value:

Returns a package manager class with the specified name.

Parameter | Description
name | The name of the class.
fNameSpaceOnly | The flag that indicates whether to ignore the global package manager namespace during the search for the class. If the value is true, only the package manager namespace associated with the class loader will be searched; otherwise, the global namespace and the package manager namespace will be searched.

Remarks:

The fNameSpaceOnly parameter can be used to force this method to look only in the package manager namespace associated with this loader. However, only rarely would you need to exclude the global namespace from the search path. Normally, you would pass false for the fNameSpaceOnly parameter, or simply use the findPackageManagerClass method that has only one parameter.

Exceptions:

ClassNotFoundException if this method cannot find a definition for the specified class.

findPackageManagerResource

protected InputStream findPackageManagerResource(String name);

Retrieves an InputStream associated with a package manager resource with the specified name. As with the findSystemResourceX APIs, this method expects the name to be separated with a "/". For example, the package manager resource name "my/sample/baz.gif" indicates the baz.gif file within the my.sample package.

Return Value:

Returns an InputStream associated with the resource, or null if the InputStream cannot be found.

Parameter | Description
name | The name of the resource to find.

getSecurityContext

public Object getSecurityContext();

Retrieves the security context object associated with the class loader. Currently, this returns the codebase URL.

Return Value:

Returns the codebase URL associated with the class loader.

getThreadGroup

public ThreadGroup getThreadGroup();

Retrieves the thread group associated with the loader.

Return Value:

Returns the thread group associated with the loader.

setCodeBase

protected void setCodeBase(URL codeBase);

Sets the codebase URL associated with the class loader. Call this method before using the loader to load classes.

Return Value:

No return value.

Parameter | Description
codeBase | The codebase URL to associate with the loader.

Exceptions:

SecurityException if the loader already has an associated codebase URL.

setPackageManagerNamespace

protected void setPackageManagerNamespace(String namespace);

Sets the package manager namespace associated with the loader.

Return Value:

No return value.

Parameter | Description
namespace | The name of the package manager namespace to associate with the loader.

Remarks:

All package management class and resource loads done by this loader will look in this explicitly-named namespace in addition to the default global package manager namespace.

Exceptions:

SecurityException if the loader already has an associated package manager namespace.

setThreadGroup

protected void setThreadGroup(ThreadGroup tg);

Sets the thread group associated with the class loader. Call this method before using the loader to load classes.

Return Value:

No return value.

Parameter | Description
tg | The thread group to associate with the class loader.

Exceptions:

SecurityException if the loader already has an associated ThreadGroup object.

Fields

codeBase
The codebase URL associated with code from the class loader.
threadGroup
The loader's thread group.

This thread group serves as the master thread group for all code associated with this class loader. For applets, each individual applet instance will have a sub-thread group of this thread group. The security system uses this thread group to determine the active context-based thread group at any given point.

For more details on how the security system uses this thread group, see the StandardSecurityManager.getThreadGroup method.


Class SecurityExceptionEx

public class SecurityExceptionEx extends SecurityException
{
  // Constructors
  public SecurityExceptionEx();
  public SecurityExceptionEx(String s);

  // Methods
  public String getFailingClassName();
  public String getFailingMethodName();
  public String toString();
}

This class represents security exceptions that are thrown by a component of the security system to indicate a security violation. The SecurityExceptionEx class differs from the standard java.lang.SecurityException class in that it can also keep track of who caused the security violation.

This extended behavior of a SecurityExceptionEx object is currently useful only within the IPermission.check method. If an IPermission.check method, which has been called by the Microsoft Win32 VM for Java in response to one of the PolicyEngine.checkPermission APIs, throws an instance of SecurityExceptionEx, the Microsoft VM will fill in the class and method names of the stack frame that failed the check. SecurityExceptionEx instances that are thrown in other contexts do not contain the class and method name information, and the getFailingClassName and getFailingMethodName methods will then return null.

SecurityException
  |
  +--SecurityExceptionEx

Constructors

SecurityExceptionEx

public SecurityExceptionEx();

Creates a new SecurityExceptionEx object with no detail message.

SecurityExceptionEx

public SecurityExceptionEx(String s);

Creates a new SecurityExceptionEx object based on the specified detail message.

Parameter | Description
s | The detail message.

Methods

getFailingClassName

public String getFailingClassName();

Retrieves the name of the class that caused the security violation. Typically, this would be the class type of a caller (found on the call stack) that lacked the proper permissions to satisfy a permission-based security check using the PolicyEngine class.

Return Value:

Returns the name of the class that caused the security violation. This value might be null, depending on the context in which the SecurityExceptionEx is thrown.

getFailingMethodName

public String getFailingMethodName();

Retrieves the name of a specific method, found on the call stack, that caused a security violation. Typically, a security violation occurs when the class associated with the method lacks the proper permissions to satisfy a permission-based security check using the PolicyEngine class.

Return Value:

Returns the name of the method that caused the security violation. This value might be null, depending on the context in which the SecurityExceptionEx is thrown.

toString

public String toString();

Converts the SecurityExceptionEx object to its string representation.

Return Value:

Returns the string representation of the SecurityExceptionEx object.

Remarks:

The representation of a SecurityExceptionEx differs slightly from the standard java.lang.Throwable output in that it also includes the class and method name of the stack frame that caused the security violation.

The string representation of a SecurityExceptionEx object is shown in the following example.

  <ex-name>[<class>.<method>]: <detail>
  or
  <ex-name>[Unknown]: <detail>

The bracketed names have the following meanings.

<ex-name>
The name of the exception (com.ms.security.SecurityExceptionEx).
<class>
The name of the failing class.
<method>
The name of the failing method.
<detail>
The detail message.


Class StandardSecurityManager

public class StandardSecurityManager extends java.lang.SecurityManager
{
  // Constructors
  public StandardSecurityManager();

  // Methods
  public synchronized void checkAccept(String host, int port);
  public void checkAccess(Thread t);
  public void checkAccess(ThreadGroup g);
  public void checkAwtEventQueueAccess();
  public synchronized void checkConnect (String host, int port);
  public void checkConnect(String host, int port, Object context);
  public void checkCreateClassLoader();
  public void checkDelete(String file);
  public void checkExec (String cmd);
  public void checkExit(int status);
  public void checkFileDialog();
  public void checkLink(String lib);
  public synchronized void checkListen(int port);
  public void checkMemberAccess(Class clazz, int which);
  public void checkMulticast(InetAddress maddr);
  public void checkMulticast(InetAddress maddr, byte ttl);
  public synchronized void checkMultimedia();
  public void checkPackageAccess(String pkg);
  public static void checkPackageAccessFromClassName(
        String classname);
  public synchronized void checkPackageDefinition(String pkg);
  public static void checkPackageDefinitionFromClassName(
        String classname);
  public void checkPrintJobAccess();
  public void checkPropertiesAccess();
  public void checkPropertyAccess(String key);
  public void checkRead(String file);
  public static void checkRead(URL url);
  public void checkRead(String file, Object context);
  public void checkRead(FileDescriptor fd);
  public void checkRegistry (int access, String value);
  public void checkSecurityAccess(String provider);
  public void checkSetFactory();
  public void checkSystemClipboardAccess();
  public void checkSystemStreams(int streamID);
  public boolean checkTopLevelWindow(Object window);
  public void checkWrite(String file);
  public void checkWrite (FileDescriptor fd);
  public Object getSecurityContext();
  public ThreadGroup getThreadGroup();
  public static void installStandardSecurity();
}

This class defines a security policy that uses the permission model to perform security checks. The StandardSecurityManager.checkXXX methods call the PolicyEngine.checkPermission methods to do the stack crawl that actually determines whether the specified operation is permitted.

SecurityManager
  |
  +--StandardSecurityManager

Constructors

StandardSecurityManager

public StandardSecurityManager();

Constructs and initializes a StandardSecurityManager object.

Methods

checkAccept

public synchronized void checkAccept(String host, int port);

Determines whether classes within the current execution context, based on the call stack of the current thread, can accept a socket connection from the specified host and port.

The check succeeds only if all the classes found on the call stack possess NetIOPermissions, and if those permissions allow the specified host and port for connections. This method overrides the java.lang.SecurityManager.checkAccept(String,int) method.

Return Value:

No return value.

Parameter | Description
host | The host.
port | The port.

Exceptions:

SecurityException if the security check fails.

checkAccess

public void checkAccess(Thread t);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to manipulate the specified thread.

Return Value:

No return value.

Parameter | Description
t | The thread whose call stack is being checked for permissions.

Remarks:

The check succeeds only if all the classes found on the call stack possess ThreadPermissions, and if those permissions allow access to the specified thread. This method overrides the java.lang.SecurityManager.checkAccess method.

Exceptions:

SecurityException if the security check fails.

checkAccess

public void checkAccess(ThreadGroup g);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to manipulate the specified thread group.

Return Value:

No return value.

Parameter | Description
g | The thread group whose call stack is being checked for permissions.

Remarks:

The check succeeds only if all the classes found on the call stack possess ThreadPermissions, and if those permissions allow access to the specified thread group. This method overrides the java.lang.SecurityManager.checkAccess method.

Exceptions:

SecurityException if the security check fails.

checkAwtEventQueueAccess

public void checkAwtEventQueueAccess();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to access the AWT event queue.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess UIPermissions, and those permissions allow access to the AWT event queue. This method overrides the java.lang.SecurityManager.checkAwtEventQueueAccess method.

Exceptions:

SecurityException if the security check fails.

checkConnect

public synchronized void checkConnect (String host, int port);

Determines whether classes within the current execution context, based on the call stack of the current thread, can open a socket connection to the specified host on the specified port.

Return Value:

No return value.

Parameter | Description
host | The host.
port | The port.

Remarks:

The check succeeds only if all the classes found on the call stack possess NetIOPermissions, and if those permissions allow connections to the specified host and port. This method overrides the java.lang.SecurityManager.checkConnect(String,int) method.

Exceptions:

SecurityException if the security check fails.

checkConnect

public void checkConnect(String host, int port, Object context);

Determines whether classes within the current execution context, based on the call stack of the current thread, can open a socket connection to the specified host on the specified port. This method overrides the java.lang.SecurityManager.checkConnect(String,int) method.

Note The context parameter is ignored, and this method simply forwards the check to the checkConnect(String host,int port) method.

Return Value:

No return value.

Parameter | Description
host | The host.
port | The port.
context | This parameter is ignored.

Exceptions:

SecurityException if the security check fails.

See Also: checkConnect(String,int)

checkCreateClassLoader

public void checkCreateClassLoader();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to create class loader objects.

Return Value:

No return value.

Remarks:

The check succeeds only if the calling code is fully trusted. This method overrides the java.lang.SecurityManager.checkCreateClassLoader method.

Exceptions:

SecurityException if the security check fails.

checkDelete

public void checkDelete(String file);

Determines whether the specified file can be deleted by the classes active within the current execution context.

Return Value:

No return value.

Parameter | Description
file | The system-dependent filename.

Remarks:

The check succeeds only if all the classes found on the call stack possess FileIOPermissions, and if those permissions allow delete access to the specified file. This method overrides the java.lang.SecurityManager.checkDelete(String) method.

Exceptions:

SecurityException if the security check fails.

checkExec

public void checkExec (String cmd);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to execute the specified application.

The check succeeds only if all of the classes found on the call stack possess ExecutionPermissions, and if those permissions allow the specified application to be run. This method overrides the java.lang.SecurityManager.checkExec method.

Return Value:

No return value.

Parameter | Description
cmd | The application for which permission to execute is being checked.

Exceptions:

SecurityException if the security check fails.

checkExit

public void checkExit(int status);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to terminate the Microsoft Win32 VM for Java.

Return Value:

No return value.

Parameter | Description
status | This parameter is ignored.

Remarks:

The check succeeds only if all the classes found on the call stack are fully trusted. This method overrides the java.lang.SecurityManager.checkExit method.

Exceptions:

SecurityException if the security check fails.

checkFileDialog

public void checkFileDialog();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to display and use file dialog boxes (java.awt.FileDialog).

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess UIPermissions, and if those permissions allow the creation of file dialog boxes.

Exceptions:

SecurityException if the security check fails.

checkLink

public void checkLink(String lib);

Determines whether the current execution context, based on the calling classes on the call stack, allows the loading of the specified native code library (DLL).

Return Value:

No return value.

Parameter | Description
lib | The DLL for which permission to load is checked.

Remarks:

The check succeeds only if the caller is fully trusted system code. This method overrides the java.lang.SecurityManager.checkLink method.

Exceptions:

SecurityException if the security check fails.

checkListen

public synchronized void checkListen(int port);

Determines whether classes within the current execution context, based on the call stack of the current thread, can wait for connection requests on the specified local port number.

Return Value:

No return value.

Parameter | Description
port | The local port from which permission to listen is being checked.

Remarks:

The check succeeds only if all the classes found on the call stack possess NetIOPermissions, and if those permissions allow listening for connections on the specified port. This method overrides the java.lang.SecurityManager.checkListen(int) method.

Exceptions:

SecurityException if the security check fails.

checkMemberAccess

public void checkMemberAccess(Class clazz, int which);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to use the reflection APIs to access members of the specified type from the specified class.

Return Value:

No return value.

Parameter | Description
clazz | The class to which access is being checked.
which | The type of class members to which access is being checked.

Remarks:

The check succeeds only if all the classes found on the call stack possess ReflectionPermissions, and if those permissions allow access to the specified class.

Exceptions:

SecurityException if the security check fails.

checkMulticast

public void checkMulticast(InetAddress maddr);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to use IP multicast.

Return Value:

No return value.

Parameter | Description
maddr | The Internet address.

Remarks:

The check succeeds only if all the classes found on the call stack possess NetIOPermissions, and if those permissions allow multicast operations on the specified Internet address. This method overrides the java.lang.SecurityManager.checkMulticast(InetAddress) method.

Exceptions:

SecurityException if the security check fails.

checkMulticast

public void checkMulticast(InetAddress maddr, byte ttl);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to use IP multicast.

Return Value:

No return value.

Parameter | Description
maddr | The Internet address.
ttl | The time to live for the packet.

Remarks:

The check succeeds only if all the classes found on the call stack possess NetIOPermissions, and if those permissions allow multicast operations on the specified address. This method overrides the java.lang.SecurityManager.checkMulticast(InetAddress,byte) method.

Exceptions:

SecurityException if the security check fails.

checkMultimedia

public synchronized void checkMultimedia();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to utilize extended multimedia features.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess MultimediaPermissions. This method is currently used by the com.ms.directX APIs.

Exceptions:

SecurityException if the security check fails.

checkPackageAccess

public void checkPackageAccess(String pkg);

Determines whether access to classes within the specified package is permitted. Package access is denied if a system property of the form package.restrict.access.packagename exists. This method overrides the java.lang.SecurityManager.checkPackageAccess(String) method.

Note Because of both the nature of class loaders and the fact that this check is made at load time instead of class resolution time, no specific contextual information can be extrapolated to determine who is attempting to access the specified package. Therefore, this check does not fit into the class-granular permissions model. Its results are based on a global state, so it will always return the same result, independent of the current execution context.

Return Value:

No return value.

Parameter | Description
pkg | The name of the package to which access is being checked.

Exceptions:

SecurityException if package access is prohibited.

checkPackageAccessFromClassName

public static void checkPackageAccessFromClassName(String classname);

If a security manager is installed, checks to see if applets can access classes located in the package that contains a specified class.

Return Value:

No return value.

Parameter | Description
classname | The name of the class from which the package to check is determined. The class name must be separated from the package name (if any) by a dot (.).

Remarks:

The checkPackageAccess method of the current security manager is called to determine whether the package access is allowed. If a security manager is not installed, this method does nothing. If the class name does not specify a package, the call succeeds.

Note This method requires a full class name. Do not trim off the class name as you would when calling java.lang.SecurityManager.checkPackageAccess.

Exceptions:

SecurityException if access to the package is prohibited.

checkPackageDefinition

public synchronized void checkPackageDefinition(String pkg);

Determines whether classes within the specified package can be defined.

Return Value:

No return value.

Parameter | Description
pkg | The name of the package that determines which package to check.

Remarks:

The package definition is denied if a system property of the form package.restrict.definition.packagename exists. This method overrides the java.lang.SecurityManager.checkPackageAccess(String) method.

Note Because of both the nature of class loaders and the fact that this check is made at load time instead of class resolution time, no specific contextual information can be extrapolated to determine who is attempting to define a class in the specified package. Therefore, this check cannot fit into the class-granular permissions model. This check is based on a global state, and will always return the same result, independent of the current execution context.

Exceptions:

SecurityException if the package definition is prohibited.

checkPackageDefinitionFromClassName

public static void checkPackageDefinitionFromClassName(String classname);

If a security manager is installed, checks to see if applets can define classes in the package of the specified class name.

Return Value:

No return value.

Parameter | Description
classname | The name of the class that determines which package to check. The class name must be separated from the package name (if any) by dots (.).

Remarks:

The checkPackageDefinition method of the current security manager is called to determine if the package definition is allowed. If the class name does not specify a package, the call will succeed. If a security manager is not installed, this method does nothing.

Note This method expects a full class name. Do not trim off the class name as you would when calling java.lang.SecurityManager.checkPackageDefinition.

Exceptions:

SecurityException if the package definition is prohibited.

See Also: checkPackageDefinition

checkPrintJobAccess

public void checkPrintJobAccess();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to initiate a print job.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess UIPermissions, and if those permissions allow printing. This method overrides the java.lang.SecurityManager.checkPrintJobAccess method.

Exceptions:

SecurityException if the security check fails.

checkPropertiesAccess

public void checkPropertiesAccess();

Determines whether the system properties object can be passed to the caller of the System.getProperties method.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess PropertyPermissions and if those permissions grant unlimited system properties access. This method overrides the java.lang.SecurityManager.checkPropertiesAccess method.

Exceptions:

SecurityException if the security check fails.

checkPropertyAccess

public void checkPropertyAccess(String key);

Determines if the specified system property can be read by all the classes within the current execution context.

Return Value:

No return value.

Parameter | Description
key | The system property for which read access is being checked.

Remarks:

The check succeeds only if all the classes found on the call stack possess PropertyPermissions and those permissions allow read access to the specified property. This method overrides the java.SecurityManager.checkPropertyAccess method.

Exceptions:

SecurityException if the security check fails.

checkRead

public void checkRead(String file);

Determines whether the specified file can be read by the classes active within the current execution context.

Return Value:

No return value.

Parameter | Description
file | The file for which permission to be read by active classes is being checked.

Remarks:

The check succeeds if all the classes found on the call stack possess FileIOPermissions and those permissions allow read access to the specified file. This method overrides the java.lang.SecurityManager.checkRead(String) method.

Exceptions:

SecurityException if the security check fails.

checkRead

public static void checkRead(URL url);

Determines whether the specified URL can be read by the code in the current execution context.

Return Value:

No return value.

Parameter | Description
url | The URL for which permission to read is being checked.

Remarks:

If the specified URL is a file:// URL, this method performs a checkRead(String file) to determine if the file specified by the URL can be read. Otherwise, this method performs a checkConnect(url.getHost(),url.getPort()) to determine if the the host/port can be connected to.

Exceptions:

SecurityException if the security check fails.

checkRead

public void checkRead(String file, Object context);

Determines whether the specified file and the specified context object can be read by the classes within the current execution context. This method overrides the java.lang.SecurityManager.checkRead method.

Note The context object must be an URL object.

Return Value:

No return value.

Parameter | Description
file | The system-dependent filename.
context | The URL to be checked in addition to the file.

Exceptions:

SecurityException if the file is not found.

checkRead

public void checkRead(FileDescriptor fd);

Determines whether classes within the current execution context, based on the call stack of the current thread, can use the specified FileDescriptor object to read from the file it is associated with.

Return Value:

No return value.

Parameter | Description
fd | The file descriptor associated with the file from which permission to read is being checked.

Remarks:

The check succeeds only if all the classes found on the call stack are fully trusted system classes. This method overrides the java.lang.SecurityManager.checkRead(FileDescriptor) method.

Exceptions:

SecurityException if the security check fails.

checkRegistry

public void checkRegistry (int access, String value);

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to perform the specified access to the specified portion of the registry.

Return Value:

No return value.

Parameter | Description
access | The access type.
value | The registry key.

Remarks:

The check succeeds only if all the classes found on the call stack possess RegistryPermissions, and if those permissions allow the specified access type onto the specified portion of the registry.

Exceptions:

SecurityException if the security check fails.

See Also: com.ms.lang.RegKey

checkSecurityAccess

public void checkSecurityAccess(String provider);

Determines if classes within the current execution context, based on the call stack of the current thread, are allowed to perform a security provider-related operation (using the java.security classes).

The check succeeds only if all the classes found on the call stack possess SecurityPermissions. This method overrides the java.lang.SecurityManager.checkSecurityAccess(String) method.

Note This check is used by the JDK security-related APIs within the java.security classes. It is not directly relevant to the Microsoft® security model.

Return Value:

No return value.

Parameter | Description
provider | This parameter is ignored.

checkSetFactory

public void checkSetFactory();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to install a networking object factory.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack are fully trusted. This method overrides the java.lang.SecurityManager.checkSetFactory method.

Exceptions:

SecurityException if the security check fails.

checkSystemClipboardAccess

public void checkSystemClipboardAccess();

Determines whether classes within the current execution context, based on the call stack of the current thread, are allowed to access the system Clipboard.

Return Value:

No return value.

Remarks:

The check succeeds only if all the classes found on the call stack possess UIPermissions, and if those permissions allow access to the system Clipboard. This method overrides the java.lang.SecurityManager.checkSystemClipboardAccess method.

Exceptions:

SecurityException if the security check fails.

checkSystemStreams

public void checkSystemStreams(int streamID);

Determines if classes within the current execution context, based on the call stack of the current thread, are allowed to set the specified system stream.

Return Value:

No return value.

Parameter Description
streamID The system stream to set. The value must be one of the following:
0
Indicates an attempt to set System.in using System.setIn.
1
Indicates an attempt to set System.out using System.setOut.
2
Indicates an attempt to set System.err using System.setErr.

Remarks:

The check succeeds only if all the classes found on the call stack possess SystemStreamsPermissions, and if those permissions allow the specified stream to be modified.

This security check is called by the java.lang.System APIs that set system streams using the System.setIn, System.setOut, and System.setErr methods.

Exceptions:

SecurityException if the security check fails.

checkTopLevelWindow

public boolean checkTopLevelWindow(Object window);

Determines if classes within the current execution context, based on the call stack of the current thread, are allowed to create top-level windows.

Return Value:

Returns false if top-level window creation is allowed and a top-level window requires a warning banner; otherwise, returns true.

Parameter | Description
window | The top-level window.

Remarks:

The check succeeds only if all the classes found on the call stack possess UIPermissions, and if all those permissions allow the creation of top-level windows. If top-level window creation is not allowed, a SecurityException is thrown.

If top-level window creation is allowed, this check determines whether the top-level window for each calling class requires no warning banner. No warning banner is required if all the UIPermission objects associated with the calling classes specify that no warning banners are necessary.

This method overrides the java.lang.SecurityManager.checkTopLevelWindow method.

Exceptions:

SecurityException if the security check fails.

checkWrite

public void checkWrite(String file);

Determines whether the specified file can be written to by the classes active within the current execution context.

The check succeeds only if all of the classes found on the call stack possess FileIOPermissions and if those permissions allow write access to the specified file. This method overrides the java.lang.SecurityManager.checkWrite(String) method.

Return Value:

No return value.

Parameter | Description
file | The system-dependent filename.

Exceptions:

SecurityException if the security check fails.

checkWrite

public void checkWrite (FileDescriptor fd);

Determines whether classes within the current execution context, based on the call stack of the current thread, can use the specified FileDescriptor object to write to the file it is associated with.

Return Value:

No return value.

Parameter | Description
fd | The file descriptor that is associated with the file.

Remarks:

The check succeeds only if all the classes found on the call stack are fully trusted system classes. This method overrides the java.lang.SecurityManager.checkWrite(FileDescriptor) method.

Exceptions:

SecurityException if the security check fails.

getSecurityContext

public Object getSecurityContext();

Retrieves the codebase URL associated with the nearest SecurityClassLoader instance found on the call stack. The SecurityClassLoader instance is found by examining the classes associated with each stack frame, and then examining the class loader associated with each class.

Return Value:

Returns the URL associated with the nearest SecurityClassLoader instance.

getThreadGroup

public ThreadGroup getThreadGroup();

Determines the active thread group based on the current execution context.

Return Value:

Returns the active thread group.

Remarks:

This method overrides the java.lang.SecurityManager.getThreadGroup method. This method is called by the constructors of the java.lang.Thread class. Its purpose is to ensure that new threads are created in the thread group associated with the active code instead of in the thread group of the current thread.

To understand why this scheme is useful, consider the AWT event dispatch thread, which is a system thread that lives in the system thread group. If an applet creates a new thread while executing code on the dispatch thread, the new thread will be created in the thread group associated with that applet. If, instead, an attempt had been made to create the thread in the system thread group, it is likely that the attempt would have failed because the applet code probably does not have access rights to the system thread group.

The algorithm for determining the active thread group is as follows.

  1. Based on the classes associated with each stack frame on the call stack, locate the nearest SecurityClassLoader instance.
  2. If no SecurityClassLoader is found, the active thread group is simply the thread group of the current thread, as follows.

Thread.currentThread().getThreadGroup()
  3. Otherwise, a SecurityClassLoader instance was found. If the thread group of the current thread is a child of the thread group associated with that loader, return it. otherwise, return the thread group associated with the loader.

installStandardSecurity

public static void installStandardSecurity();

Creates a new StandardSecurityManager and installs it as the active security manager.

Return Value:

No return value.

Exceptions:

SecurityException if a security manager is already installed.


Interface IAdjustablePermission

public interface IAdjustablePermission
{
  // Methods
  void adjustPermission (String tag, Object adjustment);
}

This interface provides a method for modifying a permission object to give context information.

Methods

adjustPermission

void adjustPermission (String tag, Object adjustment);

Modifies the permission object so that it gives context information. The tag parameter identifies the type of adjustment being made. The adjustment parameter is an object specific to the type of adjustment being made.

The following table lists the values for the tag parameter that are recognized by the system permissions, and it also describes the corresponding adjustment objects.

"codebase"
The adjustment object is the java.net.URL instance that specifies where classes that will possess the permission are loaded from. The networking I/O permission class (com.ms.security.permissions.NetIOPermission) and file I/O permission class (com.ms.security.permissions.FileIOPermission) respond to this adjustment type.
"classloader"
The adjustment object is the java.lang.ClassLoader instance used to load the classes that will possess the permission. The reflection permission class (com.ms.security.permissions.ReflectionPermission) responds to this adjustment type.
"thread group"
The adjustment object is the java.lang.ThreadGroup instance that the classes with the permission should have access to. The threading permission class (com.ms.security.permissions.ThreadPermission) responds to this adjustment type.

Note If this method is called with an adjustment object that it does not recognize, the method does nothing. No exception is thrown.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type.
adjustment | The adjustment object.


Interface IEncodablePermission

public interface IEncodablePermission
{
  // Methods
  boolean decode(String tag, InputStream data);
  boolean encode(String tag, OutputStream data);
  String mapFormat(String format);
  String[] supportedFormats();
}

This interface provides methods that allow permissions to represent their internal state in any desired format. For example, a permission can encode itself into an arbitrary binary format or a textual format.

The contract with the caller of the IEncodablePermission interface can be described in the following way.

  • The caller can obtain a tag for a specified format, and then call the encode and decode methods with that tag.
  • If a caller chooses to persist the encoding, the caller must store the tag along with the encoding.
  • To decode the persisted encoding, the caller must get the tag from its storage location, and then pass it (along with the encoding) to the decode method.
  • The caller can request the tag for a specified format using the mapFormat method.
  • If the specified format is not available, the caller can obtain the default tag by passing null to the mapFormat method.
  • If the caller does not recognize the format, the caller must be able to store the default encoding in an opaque manner (as binary data of an arbitrary length).
  • An instance of any class that implements the IEncodablePermission interface is guaranteed that its default encoding can be stored.

The tag is defined by a class that implements the IEncodablePermission interface and is meaningful only to that class. It is not meaningful to any other IEncodablePermission class. The tag allows the object to do version control and to handle multiple types of encodings. The tag is an arbitrary string that the permission class decides on. It is likely that the string will contain some type of version information; its form is determined by the permission class.

This interface is useful for developers who write Java packages that are digitally signed. When the package is installed on a client's computer, the user gets a dialog box asking for permission to access certain resources. The permission needs to be attached to the digital signature so that the security system can determine what permissions are needed. The developer should create a permission class that implements IEncodablePermission. The signcode tool takes the name of the permission class, creates an instance of it, and then calls the encode method of the permission class to cause the instance to encode itself. This encoding is stored inside the digital signature, which is then attached to a package.

The security system within the Microsoft Win32 VM for Java gets the encoding from the signature and creates an instance of the permission class. It then calls the class's decode method, passing in the tag that was used at the time of signing (the tag is part of the signature's encoding). Because signatures are static, and because the permission class can be located in any package, the current implementation of the permission class can determine what version of the IEncodablePermission class was encoded with the tag.

For example, suppose you created a package of classes that manipulate SQL databases. This package might contain applets that access portions of the database, based on a table name. You could create a database permission class called DBPermission that stores the name of an SQL table. Then you would sign each applet with the DBPermission, asking for a specific table. The DBPermission class would then be distributed with your package, and the applets are sent to Web sites that are accessed by users.

You might, at some point, enhance your package by adding the ability to restrict access to particular rows and columns of a database. You would then update your permission class to keep track of the rows and columns that can be accessed. New applets would be signed with the new permission. However, the old applets might still be in use on the Internet, signed with the old permission. The tag provides a way to identify the version used to encode a permission class.

If permissions that implement the IEncodablePermission interface are inserted into a PermissionDataSet object so that they can be used in digital signatures, the signing tool will find out whether the permissions support ASN1 format. If ASN1 is not supported, the class's default encoding will be used.

Methods

decode

boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

boolean encode(String tag, OutputStream data);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The output stream to send the encoded data to.

mapFormat

String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

supportedFormats

String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.


Interface IPermission

public interface IPermission extends com.ms.util.SetComparison
{
  // Methods
  void check(Object request) throws SecurityException ;
  IPermission combine(IPermission other) ;
  IPermission copy() ;
}

This interface must be implemented by all classes that represent permissions. Instances of the classes that implement this interface can be used as permissions that are attached to classes and used to perform security checks.

SetComparison
  |
  +--IPermission

Methods

check

void check(Object request) throws SecurityException ;

Determines whether the permission object allows the specified action. The request parameter represents a request to perform a particular action. The type of the request parameter depends on the type of the permission object that is being checked.

Return Value:

No return value.

Parameter | Description
request | The object that represents the action for which permission is being checked.

Exceptions:

SecurityException if the state of the permission object indicates that the action is not allowed.

combine

IPermission combine(IPermission other) ;

Creates and returns a new permission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting permission object.

Parameter | Description
other | The permission object that indicates additional resources to allow access to.

Exceptions:

IllegalArgumentException if the specified permission object is not of the same type as the permission object it is being combined with.

copy

IPermission copy() ;

Creates a new permission object that is equivalent to the current one. The copy operation is deep so that modifications to the copy do not affect the behavior of the original object.

Return Value:

Returns a permission object that is a copy of the current one.


Interface ISecurityRequest

public interface ISecurityRequest
{
  // Methods
  PermissionID getPermissionID();
}

This interface is used to associate specific types of objects with specific permission types.

For parameterized security checks, the basic PolicyEngine APIs require you to specify both the type of permission to check, and the security request object to pass to the IPermission.check methods. However, there are also variations of the PolicyEngine check methods that take an ISecurityRequest object instead. The ISecurityRequest object identifies the permission type and also represents the security request object.

For example, the FileIORequest class implements the ISecurityRequest interface (returning PermissionID.FILEIO), so the following security checks are equivalent to each other.

  ...
  // Create an ISecurityRequest object.
  FileIORequest sreq = new FileIORequest(FileIORequest.READ,"c:\\MySample.txt");

  // The first security check.
  // The permission type is explicitly specified.
  // Use the checkPermission(PermissionID,Object) method
  // to check permissions.
  PolicyEngine.checkPermission(PermissionID.FILEIO,sreq);

  // The second security check.
  // PolicyEngine determines the permission type from
  // the FileIORequest object. It performs the same check as
  // above.
  //
  // Use the checkPermission(ISecurityRequest) method
  // to check permissions.
  PolicyEngine.checkPermission(sreq);

Methods

getPermissionID

PermissionID getPermissionID();

Retrieves the permission type associated with the object.

Return Value:

Returns the permission type associated with the object.


About com.ms.security.permissions

In this topic

* Permission Objects

* ISecurityRequest Objects

* Using ISecurityRequest Objects to Perform Security Checks

* Implementing a Custom Permission

* Classes

* Hierarchy

Packages | Packages | Next
Package com.ms.security.permissions | Packages | Next

About com.ms.security.permissions

The com.ms.security.permissions package contains classes used to represent two types of objects: permission objects and ISecurityRequest objects.

Permission Objects

A permission object is an object that specifies a set of rights that can be associated with a class. Classes that represent permission objects must implement the IPermission interface. The com.ms.security.permissions package supplies several classes that represent permission objects. Each of these classes controls the ability to perform certain operations, as described in the following table.

Permission Class | Operations Controlled
ClientStoragePermission | Controls access to client-side storage.
ExecutionPermission | Controls the ability to run other programs.
FileIOPermission | Controls the ability to read, write, and delete files.
MultimediaPermission | Controls access to enhanced multimedia functionality.
NetIOPermission | Controls the ability to perform networking operations.
PrintingPermission | Controls the ability to print.
PropertyPermission | Controls the ability to access and manipulate global system properties.
ReflectionPermission | Controls the ability to perform reflection operations.
RegistryPermission | Controls the ability to access the registry.
SecurityPermission | Controls access to the java.lang.security package.
SystemStreamsPermission | Controls the ability to change the values of system streams.
ThreadPermission | Controls the ability to create and manipulate threads and thread groups.
UIPermission | Controls access to enhanced user interface functionality.
UserFileIOPermission | Controls the ability to perform user-directed file I/O.

To associate a group of permission objects with a class, you would bundle the objects together in a set (either a PermissionDataSet or a PermissionSet) and then use SecurityClassLoader methods to associate the set of permissions with a particular class. The security system for the Microsoft Win32 VM for Java can then examine the permissions associated with the classes on the call stack to determine which permissions are allowed in a particular context. To see an example that creates a set of permissions, puts them in a PermissionSet, and then associates the PermissionSet with a class, see the Examples section of the com.ms.security overview.

ISecurityRequest Objects

An ISecurityRequest object is an instance of a class that implements the ISecurityRequest interface. The com.ms.security.permissions package supplies classes that implement the ISecurityRequest interface. These classes represent objects that have two purposes: they identify a permission type and they also represent the parameters relevant to the permission type. The following table lists each of these classes along with the permission type that each class identifies.

Class | Permission Type
ExecutionRequest | PermissionID.EXEC
FileIORequest | PermissionID.FILEIO
NetIORequest | PermissionID.NETIO
PropertyAccessRequest | PermissionID.PROPERTY
ReflectionRequest | PermissionID.REFLECTION
RegistryRequest | PermissionID.REGISTRY
UIAccessRequest | PermissionID.UI
UserFileIOAccess | PermissionID.USERFILEIO

Instances of classes that implement ISecurityRequest are passed to PolicyEngine.checkPermission(ISecurityRequest) methods to do security checks for their respective permission types. An ISecurityRequest object contains parameters that are passed to the permission's check method. For example, to check for the registry permission, you should create and pass a RegistryRequest object to the PolicyEngine.checkPermission(ISecurityRequest) method. The parameters specified by the RegistryRequest object will be passed on to the RegistryPermission.check method.

Using ISecurityRequest Objects to Perform Security Checks

To perform a non-parameterized security check such as a check for PrintingPermission, you would simply call the PolicyEngine.checkPermission(PermissionID) method, as in the following example.

// Check to see that all of your
// callers have the rights to print.
PolicyEngine.checkPermission(PermissionID.PRINTING);

To perform a parameterized security check, you must past a security request object of the correct type to the PolicyEngine.checkPermission method. If the permission being checked is one of the permissions that has a corresponding ISecurityRequest object, then you should create the appropriate ISecurityRequest object and then pass it to the PolicyEngine.checkPermission(ISecurityRequest) method. The following example shows how to use a FileIORequest object to perform a security check that determines whether a file called "c:\\MyFile.txt" can be deleted.

...
// Create a FileIORequest object that indicates that you
// want to delete the file called "c:\\MyFile.txt".
FileIORequest sreq =
   new FileIORequest(FileIORequest.DELETE,"c:\\MyFile.txt");

// Check to see that all of your callers
// have the rights to delete that file.
PolicyEngine.checkPermission(sreq);
...

For parameterized security checks for a permission that does not have a predefined ISecurityRequest class (such as ThreadPermission), you must pass to the PolicyEngine.checkPermission method the PermissionID (or the name of the permission) and an Object whose type depends on the type of permission being checked. For example, to check for ThreadPermission, you would pass PermissionID.THREAD and an Object of type Thread or ThreadGroup. In general, to find out what type of Object to pass to the checkPermission method, consult the documentation for the check method of the permission you want to check.

If a security check fails, a SecurityExceptionEx is thrown. For more information about how security checks are implemented by the Microsoft Win32 VM for Java, see the PolicyEngine class.

Implementing a Custom Permission

There may be times when you want to implement your own permission class. As mentioned above, every permission class must implement the IPermission interface. In addition, a custom permission class may need to implement the following interfaces:
IEncodablePermission | If instances of your custom permission class need to be encoded for storage in a digital signature, your permission class should implement the IEncodablePermission interface. The IEncodablePermission interface can also be implemented to allow a user-friendly name for the class to be displayed in security dialog boxes.
IAdjustablePermission | If instances of your custom permission class need to contain context information, the permission class must implement the IAdjustablePermission interface.

The following code shows how to implement a custom permission class called NamePermission that keeps track of names that are allowed. Notice that NamePermission implements the mandatory IPermission interface.

package MyPackage;
import com.ms.security.*;

public class NamePermission implements IPermission
{
  String[] allowedNames;

  void setAllowedNames(String[] names)
  {
  // Copy the array of allowed names.
  int len = names.length;
  allowedNames = new String[len];
  System.arraycopy(names,0,allowedNames,0,len);
  }

  void check(Object request) throws SecurityException
  {
  // See if the Object is a String.
  if (!(request instanceof String) )
  throw new IllegalArgumentException("Illegal argument.");

  // See if the name is in the array of allowed names.
  for (int i= 0; i < allowedNames.length; i++ )
    if (allowedNames[i].equals( (String)request ) )
      return;

  // Not in the list, so throw exception.
  throw new SecurityException("Security check failed.");
  }

  IPermission copy()
  {
  // Create a new NamePermission object.
  NamePermission copy = new NamePermission();

  // Initialize the copy with the
  // allowed names.
  copy.setAllowedNames(allowedNames);

  return copy;
  }

  IPermission combine(IPermission other)
  {
  // See if the other permission
  // object is of the right type.
  if(!(other instanceof NamePermission))
     throw new IllegalArgumentException("Illegal argument.");

  // Create a NamePermission object.
  NamePermission comb = new NamePermission();

  // Combine the two permission objects.
  comb.allowedNames =
    PermissionUtils.combineArraysOfStrings(this.allowedNames,
                       ((NamePermission)other).allowedNames);

  // Return the combination.
  return comb;
  }

  int compare(IPermission other)
  {
  //
  if (!(other instanceof NamePermission))
     throw new IllegalArgumentException("Illegal argument.");

  // Return the result of comparing the names
  // allowed by the two permission objects.
  return PermissionUtils.compareArraysOfStrings(this.allowedNames,
                            ((NamePermission)other).allowedNames);
  }
}

You could then determine whether a particular name (such as "Pat") is allowed.

// Create a security request object.
String name = "Pat";

// Do the security check, passing
// in the security request object.
PolicyEngine.checkPermission("MyPackage.NamePermission",name);

Classes

Class ClientStoragePermission
This class represents a permission for controlling access to client-side storage that is available through the ClientStore class.
Class ExecutionPermission
This class represents a permission that controls the ability to run other programs.
Class ExecutionRequest
This class represents a request to execute an application.
Class FileIOPermission
This class represents a permission that controls the ability to access files.
Class FileIORequest
This class represents a request for access to the file system.
Class MultimediaPermission
This class represents a permission that allows the use of enhanced multimedia functionality.
Class NetIOPermission
This class represents a permission that controls the ability to perform networking operations.
Class NetIORequest
This class represents a request to perform a network-related action.
Class PrintingPermission
This class represents a permission that controls access to the printing APIs.
Class PropertyAccessRequest
This class represents a request to access the system properties.
Class PropertyPermission
This class represents a permission that controls the ability to access and manipulate the global system properties.
Class ReflectionPermission
This class represents a permission that controls the ability to perform reflection operations.
Class ReflectionRequest
This class represents a request to use the reflection APIs to gain access to members of a specified class.
Class RegistryPermission
This class represents a permission that controls the ability to access the registry.
Class RegistryRequest
This class represents a request for access to a registry key.
Class SecurityPermission
This class represents a permission that controls access to the JDK security classes (the java.lang.security package).
Class SystemStreamsPermission
This class represents a permission that controls the ability to change the values of the system streams java.lang.System.in, java.lang.System.out, and java.lang.System.err.
Class ThreadPermission
This class represents a permission that controls the ability to create and manipulate threads and thread groups.
Class UIAccessRequest
This class represents objects that indicate a request to use an extended aspect of the user interface APIs.
Class UIPermission
This class represents a permission that controls the ability to use some of the enhanced functionality of the AWT.
Class UserFileIOAccess
This class represents a request to perform a user-directed file I/O operation.
Class UserFileIOPermission
This class represents a permission that controls the ability to perform user-directed file I/O operations using the UserFileDialog class.

Hierarchy

Object
  |
  +--ClientStoragePermission (IPermission, IEncodablePermission, Cloneable)
  |
  +--ExecutionPermission (IPermission, IEncodablePermission)
  |
  +--ExecutionRequest (ISecurityRequest)
  |
  +--FileIOPermission (IPermission, IEncodablePermission, IAdjustablePermission)
  |
  +--FileIORequest (ISecurityRequest)
  |
  +--MultimediaPermission (IPermission, IEncodablePermission)
  |
  +--NetIOPermission (IPermission, IEncodablePermission, IAdjustablePermission)
  |
  +--NetIORequest (ISecurityRequest)
  |
  +--PrintingPermission (IPermission, IEncodablePermission)
  |
  +--PropertyAccessRequest (ISecurityRequest)
  |
  +--PropertyPermission (IPermission, IEncodablePermission)
  |
  +--ReflectionPermission (IPermission, IEncodablePermission, IAdjustablePermission)
  |
  +--ReflectionRequest (ISecurityRequest)
  |
  +--RegistryPermission (IPermission, IEncodablePermission)
  |
  +--RegistryRequest (ISecurityRequest)
  |
  +--SecurityPermission (IPermission, IEncodablePermission)
  |
  +--SystemStreamsPermission (IPermission, IEncodablePermission)
  |
  +--ThreadPermission (IPermission, IEncodablePermission, IAdjustablePermission)
  |
  +--UIAccessRequest (ISecurityRequest)
  |
  +--UIPermission (IPermission, IEncodablePermission)
  |
  +--UserFileIOAccess (ISecurityRequest)
  |
  +--UserFileIOPermission (IPermission, IEncodablePermission)


Class ClientStoragePermission

public class ClientStoragePermission implements IPermission,
            IEncodablePermission, Cloneable
{
  // Fields
  public static final int FL_CANROAM;
  public static final int FL_GLOBALEXEMPT;

  // Constructors
  public ClientStoragePermission ();
  public ClientStoragePermission (long limit);
  public ClientStoragePermission (long limit, int flags);

  // Methods
  public void check(Object request) throws SecurityException;
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy ();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public int getFlags ();
  public long getStorageLimit ();
  public String mapFormat(String format);
  public void reset ();
  public void setFlags (int flags);
  public void setStorageLimit (long limit);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission for controlling access to client-side storage that is available through the ClientStore class.

The ClientStoragePermission permission specifies a limit on the total amount of data that can be written. If the FL_GLOBALEXEMPT flag has been specified, the limit is an absolute limit. If the limit has not been specified, the amount of data written is also bounded by the global limit.

If the FL_CANROAM flag has been specified, "roaming" files can be created. Roaming files are created in the user's profile and are present on any computer the user is logged on to.

Constructors

ClientStoragePermission

public ClientStoragePermission ();

Creates a new ClientStoragePermission instance. The client storage allowed to classes with this permission has no storage space limits.

ClientStoragePermission

public ClientStoragePermission (long limit);

Creates a new ClientStoragePermission instance.

Parameter | Description
limit | The client storage space limit.

Remarks:

The client storage allowed to classes with this permission is limited to the specified amount of client storage space.

ClientStoragePermission

public ClientStoragePermission (long limit, int flags);

Creates a new ClientStoragePermission instance.

Parameter | Description
limit | The client storage space limit.
flags | The flags that can affect the type of client storage that classes with this permission have. They can be one or both of the following: FL_CANROAM and FL_GLOBALEXEMPT.

Remarks:

The client storage allowed to classes with this permission are limited to the specified amount of client storage space.

Methods

check

public void check(Object request) throws SecurityException;

The check method for this permission does nothing.

Return Value:

No return value.

Parameter | Description
request | This parameter is ignored.

combine

public IPermission combine (IPermission source2);

Creates and returns a new ClientStoragePermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting ClientStoragePermission object.

Parameter | Description
source2 | The other ClientStoragePermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of ClientStoragePermission.

compareSet

public int compareSet (Object target);

Compares the ClientStoragePermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the ClientStoragePermission instance is compared with.

copy

public IPermission copy ();

Retrieves a copy of the ClientStoragePermission object.

Return Value:

Returns the copy of the ClientStoragePermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getFlags

public int getFlags ();

Retrieves the flags that control access to storage.

Return Value:

Returns one or both of the flags that control storage access: FL_GLOBALEXEMPT and FL_CANROAM.

getStorageLimit

public long getStorageLimit ();

Obtains the limit on the amount of data that can be stored.

Return Value:

Returns The storage limit in bytes.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset ();

Resets the permission so that no special flags are active and there is no storage space limit.

Return Value:

No return value.

setFlags

public void setFlags (int flags);

Sets flags for controlling access to storage.

Return Value:

No return value.

Parameter | Description
flags | The values that control storage access. They must be one or both of FL_GLOBALEXEMPT and FL_CANROAM.

setStorageLimit

public void setStorageLimit (long limit);

Sets a limit on the amount of data that can be stored.

Return Value:

No return value.

Parameter | Description
limit | The amount of data that can be stored.

Remarks:

If the FL_GLOBALEXEMPT flag is in effect, this limit is an absolute limit; otherwise, the amount of data stored is also bounded by the global limit.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.

Fields

FL_CANROAM
The value that indicates that classes with this permission can create roaming files.
FL_GLOBALEXEMPT
The value that indicates that classes with this permission are not subject to the global scratch space limit.


Class ExecutionPermission

public class ExecutionPermission implements IPermission,
            IEncodablePermission
{
  // Constructors
  public ExecutionPermission ();

  // Methods
  public void check(Object param);
  public IPermission combine(IPermission other);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public void excludeApplications(String pattern);
  public WildcardExpression getExcludedApplications();
  public WildcardExpression getIncludedApplications();
  public void includeApplications(String pattern);
  public boolean isUnrestricted();
  public String mapFormat(String format);
  public void reset ();
  public void setUnrestricted(boolean flag);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to run other programs. The StandardSecurityManager checks for this permission type when performing the checkExec operation.

Also see com.ms.security.permissions.ExecutionRequest

Constructors

ExecutionPermission

public ExecutionPermission ();

Creates a new ExecutionPermission instance.

Remarks:

The new instance does not allow access for executing applications. Use either the setUnrestricted or includeApplications methods to add applications to the permission.

Methods

check

public void check(Object param);

Determines whether the permission allows the applications specified in an ExecutionRequest object to be executed.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of ExecutionRequest.

Remarks:

The following rules are used to determine whether the check passes or fails.

  1. If this permission object allows unrestricted access, the check passes.
  2. If the specified application is within the set of explicitly denied applications, the check fails.
  3. If the specified application is within the set of explicitly allowed applications, the check succeeds; otherwise, it fails.

Exceptions:

SecurityException if this permission does not allow the specified program to run.

combine

public IPermission combine(IPermission other);

Creates and returns a new ExecutionPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting ExecutionPermission object.

Parameter | Description
other | The ExecutionPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of the ExecutionPermission class.

compareSet

public int compareSet (Object target);

Compares the ExecutionPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the ExecutionPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the ExecutionPermission instance.

Return Value:

Returns a copy of the ExecutionPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

excludeApplications

public void excludeApplications(String pattern);

Explicitly excludes applications from the set of programs that the permission allows.

Return Value:

No return value.

Parameter | Description
pattern | The pattern that specifies the applications that are explicitly prohibited. It can contain wildcard expressions.

Remarks:

Because all applications are prohibited by default, this call is only useful to remove programs from an expression that was previously added with an includeApplications call.

For example, the following code creates an ExecutionPermission object that allows access to all .exe applications, except Notepad.exe.

   ...
   ExecutionPermission eperm = new ExecutionPermission()
   eperm.includeApplications("*.exe");
   eperm.excludeApplications("notepad.exe");
   ...

Note This method does nothing if the permission object already specifies unrestricted access.

See Also: com.ms.util.WildcardExpression

getExcludedApplications

public WildcardExpression getExcludedApplications();

Retrieves a WildcardExpression instance that contains all the applications that have been explicitly denied.

Return Value:

Returns a wildcard expression that contains the denied applications.

getIncludedApplications

public WildcardExpression getIncludedApplications();

Retrieves a WildcardExpression instance that contains all the applications that have been explicitly included in the set of programs that the permission allows.

Return Value:

Returns the wildcard expression that contains the allowed applications.

includeApplications

public void includeApplications(String pattern);

Adds specific applications to the set of programs that the permission allows. Applications are specified by a pattern string that can contain wildcard expressions.

Examples:

  includeApplications("notepad.exe");
  includeApplications("c:\\anything\\*.exe");

Note This method does nothing if the permission object already specifies unrestricted access.

Return Value:

No return value.

Parameter | Description
pattern | The pattern that specifies the applications that are allowed. It can contain wildcard expressions.

See Also: com.ms.util.WildcardExpression

isUnrestricted

public boolean isUnrestricted();

Determines whether the permission object allows unrestricted access to execute applications.

Return Value:

Returns true if the permission object allows unrestricted access to execute applications; otherwise, returns false.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset ();

Resets the permission object so that it no longer allows access for executing applications.

Return Value:

No return value.

setUnrestricted

public void setUnrestricted(boolean flag);

Turns the unrestricted state of this permission object on or off.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether to turn the unrestricted state on or off. If true, this method turns the unrestricted state on; otherwise, this method turns the unrestricted state off.

Remarks:

If the unrestricted state is on, the permission object allows any application to be executed by the classes that possess this permission. If the unrestricted state is off, the permission allows only the execution of applications explicitly specified by the includeApplications method. By default, the unrestricted state is off.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class ExecutionRequest

public class ExecutionRequest implements ISecurityRequest
{
  // Constructors
  public ExecutionRequest(String torun);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request to execute an application. It is intended to be used as the security request object for a parameterized security check involving the execution permission. The ExecutionPermission.check method expects an ExecutionRequest object as its parameter.

The following example uses an ExecutionRequest object to perform a security check.

  ...

  // Create an ExecutionRequest object that indicates that you want
  // to execute the application "notepad.exe".

  ExecutionRequest sreq = new ExecutionRequest("notepad.exe");

  // Check to see that all of your callers have the rights to
  // execute the notepad program.

  PolicyEngine.checkPermission(sreq);

  ...

For more information about checking execution permissions, see the PolicyEngine class and the ExecutionPermission class.

Constructors

ExecutionRequest

public ExecutionRequest(String torun);

Creates an ExecutionRequest object based on the specified application to run.

Parameter | Description
torun | The application to be executed.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the ExecutionRequest object. This method satisfies the ISecurityRequest interface and returns PermissionID.EXEC to indicate that instances of the ExecutionRequest class are associated with the execution permission.

Return Value:

Returns PermissionID.EXEC.

toString

public String toString ();

Converts the ExecutionRequest object to its string representation.

Return Value:

Returns the string representation of the ExecutionRequest object.


Class FileIOPermission

public class FileIOPermission implements IPermission,
            IEncodablePermission, IAdjustablePermission
{
  // Constructors
  public FileIOPermission();

  // Methods
  public void addDeleteableFile (String filename,
        boolean allowed) throws IOException;
  public void addDeleteableFiles (String pattern, boolean allow);
  public void addFile (int access, String filename,
        boolean allowed) throws IOException;
  public void addFiles (int access, WildcardExpression newspec,
        boolean allowed);
  public void addReadableFile (String filename,
        boolean allowed) throws IOException;
  public void addReadableFiles (String pattern, boolean allow);
  public void addWriteableFile(String filename,
        boolean allowed) throws IOException;
  public void addWriteableFiles (String pattern, boolean allow);
  public void adjustPermission (String tag, Object adjustment);
  public void check(Object param) throws SecurityException;
  public IPermission combine(IPermission source2);
  public int compareSet(Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public boolean getCanReadFromFileURLCodebase();
  public WildcardExpression getDeleteableFiles (boolean allowed);
  public WildcardExpression getFiles (int access, boolean allowed);
  public WildcardExpression getReadableFiles (boolean allowed);
  public WildcardExpression getWriteableFiles (boolean allowed);
  public String mapFormat(String format);
  public void reset();
  public void setCanReadFromFileURLCodebase(boolean flag);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to access files. The StandardSecurityManager checks for this permission type when performing the checkRead, checkWrite, and checkDelete operations.

The permission distinguishes between the following three different types of file I/O access.

FileIORequest.READ
Read-only access to the contents of the file or access to information about the file, such as its length or last modification time.
FileIORequest.WRITE
Write access to the contents of the file or access to change information about the file, such as its name.
FileIORequest.DELETE
The ability to delete the file.

The specific files that the permission instance allows for each of these access types are defined by a pair of include/exclude patterns.

When permissions are checked, the requested filename is expanded to its full form using java.io.File.getCanonicalPath, so the permission objects must contain full path specifications. The addReadableFile, addWriteableFile, and addDeleteableFile methods can be used to convert a single filename to its full form and add it to the permission.

This class implements the IPermission, the IEncodablePermission, and the IAdjustablePermission interfaces.

Also see com.ms.security.permissions.FileIORequest

Constructors

FileIOPermission

public FileIOPermission();

Creates a new FileIOPermission instance.

Remarks:

The new instance does not allow any file I/O operations.

Methods

addDeleteableFile

public void addDeleteableFile (String filename, boolean allowed)
        throws IOException;

Adds a file to the set, either allowing or denying that file for delete access.

Return Value:

No return value.

Parameter | Description
filename | The name of the file to add to the permission.
allowed | The flag that indicates whether you are allowing or denying the file. If the value is true, the file is allowed; otherwise, the file is denied.

Exceptions:

IOException if an error occurs while getting the full name of the file.

addDeleteableFiles

public void addDeleteableFiles (String pattern, boolean allow);

Adds a pattern that specifies a set of files that are allowed or denied for deleting.

Return Value:

No return value.

Parameter | Description
pattern | The string that indicates which files to allow or deny. It must be of the form accepted by a WildcardExpression with the ESCAPED flag enabled.
allow | The flag that indicates whether you are allowing or denying the files specified by the pattern. If the value is true, the files are allowed. Otherwise, the files are denied. You can deny files only if the file was previously allowed.

addFile

public void addFile (int access, String filename, boolean allowed)
        throws IOException;

Adds a specific file to the permission, either allowing or denying that file for the specified access types. The file is expanded to its fully qualified form using the java.io.File.getCanonicalPath method.

Return Value:

No return value.

Parameter | Description
access | An access type that is one of the following values: FileIORequest.READ, FileIORequest.WRITE, or FileIORequest.DELETE.
filename | The name of the file to add to the permission.
allowed | The flag that indicates whether you are allowing or denying the file for the specified access type. If the value is true, the file is allowed; otherwise, the file is denied.

Exceptions:

IOException if an error occurs while getting the full name of the file.

addFiles

public void addFiles (int access, WildcardExpression newspec,
        boolean allowed);

Adds a set of files to this permission, either allowing or denying those files for the specified access type. The files to be added are specified as a WildcardExpression object.

Return Value:

No return value.

Parameter | Description
access | An access type that is one of the following values: FileIORequest.READ, FileIORequest.WRITE, or FileIORequest.DELETE.
newspec | The wildcard expression that indicates the files to add.
allowed | The flag that indicates whether you are allowing or denying the file for the specified access type. If the value is true, the files are allowed; otherwise, they are denied.

addReadableFile

public void addReadableFile (String filename, boolean allowed)
        throws IOException;

Adds a file to the set, either allowing or denying that file for read access. Calling this method is equivalent to the following call.

addFile(FileIORequest.READ,filename,allowed)

Return Value:

No return value.

Parameter | Description
filename | The name of the file to add to the permission.
allowed | The flag that indicates whether you are allowing or denying the file. If the value is true, the file is allowed; otherwise, the file is denied.

Exceptions:

IOException if an error occurs while getting the full name of the file.

addReadableFiles

public void addReadableFiles (String pattern, boolean allow);

Adds a pattern that specifies a set of files that are allowed or denied for reading.

Return Value:

No return value.

Parameter | Description
pattern | The string that indicates which files to allow or deny. It must be of the form accepted by a WildcardExpression with the ESCAPED flag enabled.
allow | The flag that indicates whether you are allowing or denying the files specified by the pattern. If the value is true, the files are allowed. Otherwise, the files are denied. You can deny files only if the file was previously allowed.

addWriteableFile

public void addWriteableFile(String filename, boolean allowed)
        throws IOException;

Adds a file to the set, either allowing or denying that file for write access. Calling this method is equivalent to the following call.

addFile(FileIORequest.WRITE,filename,allowed)

Return Value:

No return value.

Parameter | Description
filename | The name of the file to add to the permission.
allowed | The flag that indicates whether you are allowing or denying the file. If the value is true, the file is allowed; otherwise, the file is denied.

Exceptions:

IOException if an error occurs while getting the full name of the file.

addWriteableFiles

public void addWriteableFiles (String pattern, boolean allow);

Adds a pattern that specifies a set of files that are allowed or denied for writing.

Return Value:

No return value.

Parameter | Description
pattern | The string that indicates which files to allow or deny. It must be of the form accepted by a WildcardExpression with the ESCAPED flag enabled.
allow | The flag that indicates whether you are allowing or denying the files specified by the pattern. If the value is true, the files are allowed. Otherwise, the files are denied. You can deny files only if the file was previously allowed.

adjustPermission

public void adjustPermission (String tag, Object adjustment);

Adjusts the permission object with some run-time state.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type. Every type except "codebase" is ignored.
adjustment | This parameter must be an instance of java.net.URL for the "codebase" tag.

Remarks:

The FileIOPermission only responds to the "codebase" adjustment type, and expects the adjustment parameter to be of type URL in that case. All other adjustment types are ignored.

If the URL is a file:// URL and if the permission allows reading from file:// URL codebases, this method adds read access for the "codebase" directory (and everything below it) to the permission object.

check

public void check(Object param) throws SecurityException;

Determines if the specified file I/O operation is allowed by this permission object.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of the FileIORequest class.

Exceptions:

SecurityException if this permission does not allow the specified file I/O operation.

combine

public IPermission combine(IPermission source2);

Creates and returns a new FileIOPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting FileIOPermission object.

Parameter | Description
source2 | The FileIOPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of FileIOPermission.

compareSet

public int compareSet(Object target);

Compares the FileIOPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the FileIOPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the FileIOPermission instance.

Return Value:

Returns the copy of the FileIOPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getCanReadFromFileURLCodebase

public boolean getCanReadFromFileURLCodebase();

Returns the flag that controls whether classes that possess this permission should have read access to the directory that they were loaded from, if that location is a file:// URL.

Return Value:

Returns true if the permission allows reading from file:// URL codebases; otherwise, returns false.

getDeleteableFiles

public WildcardExpression getDeleteableFiles (boolean allowed);

Obtains a pattern that matches all files that are permitted or all files that are explicitly prohibited for delete access. The allowed flag indicates whether you want to obtain the pattern that matches files that have been explicitly allowed or explicitly denied.

Return Value:

Returns the WildcardExpression that matches the requested files.

Parameter | Description
allowed | The flag that indicates whether you want to obtain the pattern for explicitly allowed files or explicitly denied files. If true, the method returns a pattern that matches all files that are explicitly allowed; otherwise, the method returns a pattern that matches all files that are explicitly denied.

getFiles

public WildcardExpression getFiles (int access, boolean allowed);

Retrieves a WildcardExpression object that indicates all the files that this permission object matches for the specified access type.

Return Value:

Returns the wildcard expression that indicates the matching files.

Parameter | Description
access | An access type that is one of the following values: FileIORequest.READ, FileIORequest.WRITE, or FileIORequest.DELETE.
allowed | The flag that indicates whether this method retrieves the pattern that matches files that have been explicitly allowed or explicitly denied. If true, this method returns the pattern for files that have been explicitly allowed; otherwise, it returns the pattern for files that have been explicitly denied.

getReadableFiles

public WildcardExpression getReadableFiles (boolean allowed);

Obtains a pattern that matches all files that are permitted or all files that are explicitly prohibited for read access. The allowed flag indicates whether you want to obtain the pattern that matches files that have been explicitly allowed or explicitly denied.

Return Value:

Returns the WildcardExpression that matches the requested files.

Parameter | Description
allowed | The flag that indicates whether you want to obtain the pattern for explicitly allowed files or explicitly denied files. If true, the method returns a pattern that matches all files that are explicitly allowed; otherwise, the method returns a pattern that matches all files that are explicitly denied.

getWriteableFiles

public WildcardExpression getWriteableFiles (boolean allowed);

Obtains a pattern that matches all files that are permitted or all files that are explicitly prohibited for write access. The allowed flag indicates whether you want to obtain the pattern that matches files that have been explicitly allowed or explicitly denied.

Return Value:

Returns the WildcardExpression that matches the requested files.

Parameter | Description
allowed | The flag that indicates whether you want to obtain the pattern for explicitly allowed files or explicitly denied files. If true, the method returns a pattern that matches all files that are explicitly allowed; otherwise, the method returns a pattern that matches all files that are explicitly denied.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission state to empty. This is a state in which the object allows no file I/O access.

Return Value:

No return value.

setCanReadFromFileURLCodebase

public void setCanReadFromFileURLCodebase(boolean flag);

Sets the flag that controls whether classes that possess this permission should have read access to the directory that they were loaded from, if that location is a file:// URL.

Return Value:

No return value.

Parameter | Description
flag | The value that indicates whether this permission should allow reading from the "codebase" directory for file:// URLs. If true, the flag will be set so that reading is allowed; otherwise, the flag is set so that reading is not allowed.

Remarks:

If the flag is set to true, a later "codebase" adjustment by using the adjustPermission method will include the "codebase" directory in the set of files that can be read by this permission. If this flag is false, a later call to the adjustPermission method will do nothing.

supportedFormats

public String[] supportedFormats();

Returns the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class FileIORequest

public class FileIORequest implements ISecurityRequest
{
  // Fields
  public static final int DELETE;
  public static final int READ;
  public static final int WRITE;

  // Constructors
  public FileIORequest (int type, String file);
  public FileIORequest (int type);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request for access to the file system. FileIORequest instances should be used as the security request objects for parameterized security checks involving the file I/O permission. The FileIOPermission.check method expects a FileIORequest object as its parameter.

The following example shows how to use a FileIORequest object to perform a security check to determine whether a file called sample.txt can be opened for reading.

  ...
  // Create a FileIORequest object that indicates that you want to
  // read the file called "c:\\sample.txt".

  FileIORequest sreq = new FileIORequest(FileIORequest.READ,"c:\\sample.txt");

  // Check to see that all of your callers
  // have the rights to read that file.

  PolicyEngine.checkPermission(sreq);
  ...

For more information about checking file I/O permissions, see the PolicyEngine class and the FileIOPermission class.

Constructors

FileIORequest

public FileIORequest (int type, String file);

Creates a FileIORequest object based on the access type requested and the name of the file to which access is requested.

Parameter | Description
type | The type of access that is requested. This value must be some combination of READ, WRITE, and DELETE.
file | The name of the file to which I/O access is requested.

FileIORequest

public FileIORequest (int type);

Creates a FileIORequest object based on the access type requested.

Parameter | Description
type | The access type that is requested. This value must be some combination of READ, WRITE, and DELETE.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the FileIORequest object.

Return Value:

Returns PermissionID.FILEIO.

Remarks:

This method satisfies the ISecurityRequest interface and returns PermissionID.FILEIO to indicate that instances of the FileIORequest class are associated with the file I/O permission.

toString

public String toString ();

Converts the FileIORequest object to its string representation.

Return Value:

Returns the string representation of the FileIORequest object.

Fields

DELETE
The file I/O access type that represents an attempt to delete a file.
READ
The file I/O access type that represents an attempt to open a file for reading.
WRITE
The file I/O access type that represents an attempt to open a file for writing.


Class MultimediaPermission

public class MultimediaPermission implements IPermission,
            IEncodablePermission
{
  // Methods
  public void check(Object request) throws SecurityException;
  public IPermission combine(IPermission other);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public String mapFormat(String format);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that allows the use of enhanced multimedia functionality. Currently, this permission allows access to extended aspects of the Microsoft® DirectX® APIs. Security checks for the multimedia permission are non-parameterized.

This class implements the IPermission and the IEncodablePermission interfaces.

Methods

check

public void check(Object request) throws SecurityException;

Performs a check on the permission object. Because security checks for the multimedia permission are non-parameterized, this method always succeeds.

Return Value:

No return value.

Parameter | Description
request | This parameter is ignored.

combine

public IPermission combine(IPermission other);

Returns a new MultimediaPermission instance. Since checks for MultimediaPermission are non-parameterized, the combine operation serves no purpose.

Return Value:

Returns a new MultimediaPermission instance.

Parameter | Description
other | This parameter is ignored, but it must be an instance of the MultimediaPermission class.

compareSet

public int compareSet (Object target);

Compares the MultimediaPermission instance against the specified permission object.

Return Value:

Returns EQUAL if the specified object is an instance of the MultimediaPermission class.

Parameter | Description
target | The permission object that the MultimediaPermission instance is compared against. It must be an instance of the MultimediaPermission class.

Exceptions:

IllegalArgumentException if the specified Object is not an instance of the MultimediaPermission class.

copy

public IPermission copy();

Retrieves a new instance of the MultimediaPermission class.

Return Value:

Returns a new MultimediaPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that this permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves the string representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class NetIOPermission

public class NetIOPermission implements IPermission,
            IEncodablePermission, IAdjustablePermission
{
  // Fields
  public static final int ALL_API_FLAGS;
  public static final int ALLOW;
  public static final int ALLOWALL;
  public static final int ALLOWBIND;
  public static final int ALLOWCONNECT;
  public static final int ALLOWMULTICAST;
  public static final int BIND;
  public static final int CONNECT;
  public static final int DENY;
  public static final int DENYALL;
  public static final int DENYBIND;
  public static final int DENYCONNECT;
  public static final int DENYMULTICAST;
  public static final int HOSTS;
  public static final int IPS;
  public static final int MULTICAST;

  // Constructors
  public NetIOPermission ();

  // Methods
  public void addAddress (int flags, InetAddress addr);
  public void addAddress (int flags, InetAddress addr,
        IntRanges ports);
  public void addAllFormsByName (int flags, String spec,
        IntRanges ports);
  public void addAllFormsByName (int flags, String spec);
  public void addConnectHost (String hostspec, boolean fAllow);
  public void addGlobalPortRules (int flags, String spec);
  public void addGlobalPorts (int flags, int start, int end);
  public void addHost (int flags, String hostspec);
  public void addHost (int flags, String hostspec, IntRanges ports);
  public void addHostRules (int flags, String spec);
  public void addIP (int flags, int addr);
  public void addIP (int flags, int addr, IntRanges ports);
  public void addIP (int flags, byte[] addr);
  public void addIP (int flags, byte[] addr, IntRanges ports);
  public void addIPRules (int flags, String spec);
  public void addIPs (int flags, int s, int e, IntRanges ports);
  public void addIPs (int flags, int s, int e);
  public void addIPs (int flags, byte[] s, byte[] e,
        IntRanges ports);
  public void addIPs (int flags, byte[] s, byte[] e);
  public void addPattern (int flags, String spec);
  public void addPattern (int flags, String spec, IntRanges ports);
  public void adjustPermission (String tag, Object adjustment);
  public void check (Object param) throws SecurityException;
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public boolean getCanConnectToFileURLCodeBase();
  public boolean getCanConnectToNonFileURLCodeBase();
  public String getGlobalPortRules (int flags);
  public IntRanges getGlobalPorts (int flags);
  public String getHostRules (int flags);
  public WildcardExpression getHosts (int flags);
  public String getIPRules (int flags);
  public IntRanges getIPs (int flags);
  public IntRanges[] getPorts (int flags);
  public String mapFormat(String format);
  public void reset();
  public void setCanConnectToFileURLCodeBase (boolean f);
  public void setCanConnectToNonFileURLCodeBase (boolean f);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to perform networking operations. A NetIOPermission object contains components for the following three basic types of network operations:

CONNECT
The ability to have general communication with specific hosts.
BIND
The ability to accept connections on specific interfaces and ports. The ability to accept a connection from a specific host is controlled by the CONNECT rules.
MULTICAST
The ability to join specific multicast groups. Communication with specific members of the multicast group is controlled by the CONNECT rules.

For each type of operation, the permissions are specified as ranges of IP (Internet Protocol) addresses, hostname patterns, and ports. Ports can be specified for individual ranges or patterns, or for all ranges or patterns. The global port rules supercede any individual port rules.

All the permission's operators are incremental. The reset method can be used to clear an existing permission of all components.

The components of the permission can be added individually or one hostname mask/address range/port range at a time. Multiple components can also be added in string format. For example, the string ".microsoft.com;myhost.com" could be used to indicate the specific host named "myhost.com." and all host names that end in ".microsoft.com".

Address ranges have the normal dotted IP form. An asterisk (*) can be used in place of a byte to represent any valid byte. A single address can be specified, or starting and ending ranges can be delimited by a dash.

Port lists must have the same syntax accepted by the string constructors of the com.ms.util.IntRanges class. For example, "80,1024-2000" is a valid port list. Ports can be specified on individual hostname patterns or addresses by appending a colon and a port range. For example, "*.microsoft.com:80" and "1.2.*.*:1024-5000" are both valid port specifications.

For hostnames, multiple addresses and address ranges are delimited by semicolons. For example, "1.2.*.*;4.5.6.7-4.5.6.50" is a valid hostname.

Some of the addXXX methods in this class take a flag parameter that consists of two values combined with a logical OR operator (|). The first value specifies the connection type by using one or more of MULTICAST, BIND, or CONNECT. The second value specifies ALLOW or DENY to indicate whether the address, port, or hostname being added is supposed to use the exclude or include rules. An IllegalArgumentException is thrown by these methods if the arguments don't apply to one or more of the specified types.

The flags can be used to update multiple aspects of the permission with one method call. For example, the following code sample adds "localhost" as a hostname that can be both connected and bound to.

     NetIOPermission data;
     data.addHost(NetIOPermission.ALLOWALL, "localhost");

The getXXX methods also take a flag parameter that consists of two values combined with a logical OR operator (|). To indicate the connection type, you must specify exactly one of MULTICAST, BIND or CONNECT. If more than one of these is specified, an IllegalArgumentException is thrown. For the second value, you should specify ALLOW or DENY.

For your convenience, combination flags are provided to use for the flag parameters. With these values, you don't have to use the OR (|) operator.

  • ALLOWCONNECT
  • DENYCONNECT
  • ALLOWBIND
  • DENYBIND
  • ALLOWMULTICAST
  • DENYMULTICAST
  • ALLOWALL
  • DENYALL

The addXXX methods accept all of the flags in the previous list, but the getXXX methods do not accept the last two.

Hostname masks are input to the permission as strings and retrieved as expressions.

IP addresses are only supported in 32-bit lengths. Addresses are added as integers, byte arrays (for use with the java.net.InetAddress.getAddress method), or as com.ms.util.IntRanges.

The setCanConnectToFileURLCodeBase and setCanConnectToNonFileURLCodeBase methods are used to control whether the permission allows connections to the host from which the classes with the permission were loaded. If set, the permission can be updated with the codebase by the com.ms.security.PermissionDataSet.adjustForCodebase method.

Constructors

NetIOPermission

public NetIOPermission ();

Constructs an empty networking permission.

Methods

addAddress

public void addAddress (int flags, InetAddress addr);

Adds an InetAddress object to the permissions with no port rules. The permission will allow access to all ports, unless global rules have been previously specified.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the InetAddress object being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
addr | The Internet address that the access flags apply to.

addAddress

public void addAddress (int flags, InetAddress addr, IntRanges ports);

Adds an InetAddress object to the permissions with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the InetAddress object being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
addr | The Internet address that the access flags apply to.
ports | The ports that apply on the address.

addAllFormsByName

public void addAllFormsByName (int flags, String spec, IntRanges ports);

Adds all forms of the specified address. The address is added using the following procedure.

  • If the address is in dotted IP form, it will be resolved to a hostname. The hostname and all addresses will be added. If the address cannot be resolved, only the specified address is added.
  • If the address is a hostname, it will be resolved to its addresses. The hostname and all addresses will be added. If the hostname cannot be resolved, only the specified hostname is added. The hostname will be added in its fully-qualified form.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
spec | The textual IP or host specification.
ports | The ports that apply to the hosts or IPs.

addAllFormsByName

public void addAllFormsByName (int flags, String spec);

Adds all forms of the specified address.

  • If the address is in dotted IP form, it will be resolved to a hostname. The hostname and all addresses will be added. If the address cannot be resolved, only the specified address is added.
  • If the address is a hostname, it will be resolved to its addresses. The hostname and all addresses will be added. If the hostname cannot be resolved, only the specified hostname is added. The hostname will be added in its fully-qualified form.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
spec | The textual IP or host specification.

addConnectHost

public void addConnectHost (String hostspec, boolean fAllow);

Adds an allowed or denied hostname pattern to the connect permissions.

Return Value:

No return value.

Parameter | Description
hostspec | The host specification.
fAllow | If the value is true, allow connections to the specified hosts. If the value is false, explicitly deny connections to the specified hosts.

addGlobalPortRules

public void addGlobalPortRules (int flags, String spec);

Adds global port rules for the specified connection type.

Return Value:

No return value.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the global port rules being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
spec | The port rules to add.

addGlobalPorts

public void addGlobalPorts (int flags, int start, int end);

Adds a global port range for the specified connection types.

Return Value:

No return value.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the port range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
start | The beginning range value.
end | The ending range value.

addHost

public void addHost (int flags, String hostspec);

Adds a hostname pattern to the permissions with no port rules. The permission will allow access to all ports, unless global rules have been previously specified.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
hostspec | The host specification.

addHost

public void addHost (int flags, String hostspec, IntRanges ports);

Adds a hostname pattern to the permissions with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be one of ALLOW or DENY to indicate whether the hostname pattern being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
hostspec | The host specification.
ports | The ports that apply to the hosts.

addHostRules

public void addHostRules (int flags, String spec);

Adds a set of host rules and per-host port rules for the specified access types.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rules being added indicate inclusion or exclusion. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
spec | The textual host/port specification.

addIP

public void addIP (int flags, int addr);

Adds a single 32-bit address to the permissions with no port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
addr | The 32-bit address.

addIP

public void addIP (int flags, int addr, IntRanges ports);

Adds a single 32-bit address to the permissions with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit address being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
addr | The 32-bit address.
ports | The ports that apply to this rule.

addIP

public void addIP (int flags, byte[] addr);

Adds a single address to the permissions with no port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
addr | The address.

addIP

public void addIP (int flags, byte[] addr, IntRanges ports);

Adds a single address to the permissions with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
addr | The 32-bit address.
ports | The ports that apply to this rule.

addIPRules

public void addIPRules (int flags, String spec);

Adds a set of IP rules and per-IP port rules from the string form for the specified access types.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
spec | The textual IP/port specification.

addIPs

public void addIPs (int flags, int s, int e, IntRanges ports);

Adds a 32-bit address range to the permissions with the specified port rules and the specified access types.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connect type. The second flag should be either ALLOW or DENY to indicate whether the address range being added should use the include or exclude rules. For convenience, instead of using two flags OR'd together, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
s | The starting address in the range.
e | The ending address in the range.
ports | The ports that apply.

addIPs

public void addIPs (int flags, int s, int e);

Adds a 32-bit address range to the permissions with no port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
s | The starting address in the range.
e | The ending address in the range.

addIPs

public void addIPs (int flags, byte[] s, byte[] e, IntRanges ports);

Adds an address range to the permissions with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags. The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.
s | The starting address in the range.
e | The ending address in the range.
ports | The ports that apply.

addIPs

public void addIPs (int flags, byte[] s, byte[] e);

Adds an address range to the permissions with no port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the address range being added should use the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
s | The starting address in the range.
e | The ending address in the range.

addPattern

public void addPattern (int flags, String spec);

Parses a pattern and adds it to the permission as an IP or host rule, as appropriate.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, MULTICAST, or ALL_API_FLAGS to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rule being added indicates inclusion or exclusion. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.
spec | The textual IP/host specification.

addPattern

public void addPattern (int flags, String spec, IntRanges ports);

Parses a pattern and adds it to the permission as an IP or host rule, as appropriate, with the specified port rules.

Return Value:

No return value.

Parameter | Description
flags | The access flags, which consist of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rule being added indicates inclusion or exclusion. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWALL, DENYALL, ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND.
spec | The textual IP/host specification.
ports | The ports that apply to the hosts or IPs.

adjustPermission

public void adjustPermission (String tag, Object adjustment);

Adjusts this permission object with some runtime state.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type. Everything but "codebase" is ignored.
adjustment | This parameter must be an instance of java.net.URL for the "codebase" tag.

Remarks:

The NetIOPermission only responds to the "codebase" adjustment type, and expects the adjustment parameter to be URL in that case. All other adjustment types are ignored.

If the URL is a file:// URL, and this permission allows connection back to the localhost if the cobebase URL is a file:// URL, localhost is added to the set of hosts that this permission allows connections to.

If the URL is not a file:// URL, and this permission allows connections back to non file:// URL hosts, the host of the codebase URL is added to the set of hosts that this permission allows connections to.

check

public void check (Object param) throws SecurityException;

Determines whether the specified networking I/O operation is allowed by the permission object.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of NetIORequest.

Exceptions:

SecurityException if this permission does not allow the specified networking operation.

combine

public IPermission combine (IPermission source2);

Creates and returns a new NetIOPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting NetIOPermission object.

Parameter | Description
source2 | The NetIOPermission to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of NetIOPermission.

compareSet

public int compareSet (Object target);

Compares the NetIOPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the NetIOPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the NetIOPermission instance.

Return Value:

Returns the copy of the NetIOPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getCanConnectToFileURLCodeBase

public boolean getCanConnectToFileURLCodeBase();

Returns the flag that controls whether classes that possess this permission can connect back to the local host if from a file:// URL codebase.

Return Value:

Returns true if the permission allows connections back to file:// URL codebase hosts; otherwise, returns false.

getCanConnectToNonFileURLCodeBase

public boolean getCanConnectToNonFileURLCodeBase();

Retrieves the flag that controls whether classes that possess this permission can connect back to non-file:// URL codebase hosts.

Return Value:

Returns true if the permission allows connections back to non-file:// URL codebase hosts; otherwise, returns false.

getGlobalPortRules

public String getGlobalPortRules (int flags);

Obtains the global port rules for the specified connection type in String form.

Return Value:

Returns the port ranges in textual form.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rules should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

getGlobalPorts

public IntRanges getGlobalPorts (int flags);

Obtains the global ports rules for the specified connection type.

Return Value:

Returns the port ranges for the connection type.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rules should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

getHostRules

public String getHostRules (int flags);

Obtains the combined set of hostname patterns and corresponding port rules for the specified connection type, in String form.

Return Value:

Returns a String that describes the hosts that apply to the specified connection type.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rules should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

getHosts

public WildcardExpression getHosts (int flags);

Obtains a combined pattern that matches all the hostname patterns for the specified connection type.

Return Value:

Returns a WildcardExpression that describes the hosts that apply to the specified connection type.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the pattern should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

getIPRules

public String getIPRules (int flags);

Obtains the combined set of 32-bit IP ranges and corresponding port rules for the specified connection type, in String form.

Return Value:

Returns the string form of the IP ranges that apply to the specified connection type.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be either BIND or CONNECT to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the 32-bit IP ranges should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, or DENYBIND.

getIPs

public IntRanges getIPs (int flags);

Obtains the combined set of 32-bit IP ranges for the specified connection type.

Return Value:

Returns the IP ranges that apply to the specified connection type.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the IP ranges should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

getPorts

public IntRanges[] getPorts (int flags);

Obtains the port rules corresponding to each of the hosts or IPs for the specified connection type.

Return Value:

Returns the port ranges that apply to the hosts or IPs.

Parameter | Description
flags | The connection type, which consists of two separate flags combined with a logical OR operator (|). The first flag should be BIND, CONNECT, or MULTICAST to specify the connection type. The second flag should be either ALLOW or DENY to indicate whether the rules should be obtained using the include or exclude rules. For convenience, instead of using the logical OR operator with the two flags, you can use one of the combination flags: ALLOWCONNECT, DENYCONNECT, ALLOWBIND, DENYBIND, ALLOWMULTICAST, or DENYMULTICAST.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission state to empty.

Return Value:

No return value.

setCanConnectToFileURLCodeBase

public void setCanConnectToFileURLCodeBase (boolean f);

Sets the flag that controls whether classes that possess this permission can connect to the local host if the codebase URL associated with the classes is a file:// URL.

Return Value:

No return value.

Parameter | Description
f | If this value is true, the permission will allow connections back to the local host if the codebase URL is a file:// URL.

Remarks:

If this flag is set to true, a later "codebase" adjustment using the adjustPermission method will include the local host in the set of hosts that this permission can connect to.

setCanConnectToNonFileURLCodeBase

public void setCanConnectToNonFileURLCodeBase (boolean f);

Sets the flag that controls whether classes that possess this permission can connect back to their originating host if the codebase URL is not a file:// URL.

Return Value:

No return value.

Parameter | Description
f | If this value is true, the permission allows connections back to the originating host if the codebase URL is not a file:// URL.

Remarks:

If this flag is set to true, a later "codebase" adjustment using the adjustPermission method will include the host of the codebase URL to the set of hosts that this permission can connect to.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.

Fields

ALL_API_FLAGS
A combination of the CONNECT, BIND, and MULTICAST flags.
ALLOW
A flag that indicates that some operation should be allowed by this permission.
ALLOWALL
A combination of the ALLOW, CONNECT, and BIND flags.
ALLOWBIND
A combination of the ALLOW and BIND flags.
ALLOWCONNECT
A combination of the ALLOW and CONNECT flags.
ALLOWMULTICAST
A combination of the ALLOW and MULTICAST flags.
BIND
A flag that indicates an operation that listens on a local port for network connections from other hosts.
CONNECT
A flag that indicates a network connection operation.
DENY
A flag that indicates that some operation should be denied by this permission.
DENYALL
A combination of the DENY, CONNECT, and BIND flags.
DENYBIND
A combination of the DENY and BIND flags.
DENYCONNECT
A combination of the DENY and CONNECT flags.
DENYMULTICAST
A combination of the DENY and MULTICAST flags.
HOSTS
A flag that indicates that network computers are identified by host name.
IPS
A flag that indicates that network computers are identified by an IP address.
MULTICAST
A flag that indicates a multicast socket operation.


Class NetIORequest

public class NetIORequest implements ISecurityRequest
{
  // Fields
  public static final int ACCEPT;
  public static final int CONNECT;
  public static final int LISTEN;
  public static final int MULTICAST;

  // Constructors
  public NetIORequest (int accesstype, String hostname);
  public NetIORequest (int accesstype, String hostname, int port);
  public NetIORequest (int accesstype, int port);
  public NetIORequest (int accesstype, InetAddress addr, int ttl);
  public NetIORequest (int accesstype, InetAddress addr);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request to perform a network-related action. Use NetIORequest objects as the security request objects for parameterized security checks involving the networking I/O permission. The NetIOPermission.check method expects a NetIORequest object as its parameter.

This example shows how to use a NetIORequest object to perform a security check.

...
// Create a NetIORequest that indicates that you want to
// connect to the host 'any.thing.com'.

NetIORequest sreq = new NetIORequest(NetIORequest.CONNECT,
   "any.thing.com");

// Check to see that all of your callers have the rights to
// connect to that host.

PolicyEngine.checkPermission(sreq);
...

For more information about checking networking permissions, see the PolicyEngine class and the NetIOPermission class.

Constructors

NetIORequest

public NetIORequest (int accesstype, String hostname);

Creates a networking I/O request that specifies an attempt to connect to the specified host or to receive connections from the specified host.

Parameter | Description
accesstype | The type of access requested.
hostname | The name of the host.

NetIORequest

public NetIORequest (int accesstype, String hostname, int port);

Creates a networking I/O request that specifies an attempt to connect to the specified host/port or to receive connections from the specified host on the specified port.

Parameter | Description
accesstype | The type of access requested. The value must be CONNECT or ACCEPT.
hostname | The network host to access.
port | The port to access.

NetIORequest

public NetIORequest (int accesstype, int port);

Creates a networking I/O request that specifies an attempt to listen for networking connections on the specified port.

Parameter | Description
accesstype | The type of access requested. The value should be LISTEN.
port | The local port number to listen on.

NetIORequest

public NetIORequest (int accesstype, InetAddress addr, int ttl);

Creates a networking I/O request that specifies an attempt to perform a multicast operation to the specified Internet address with the specified time to live value.

Parameter | Description
accesstype | The type of access requested. The value should be MULTICAST.
addr | The Internet address.
ttl | The time to live value.

NetIORequest

public NetIORequest (int accesstype, InetAddress addr);

Creates a networking I/O request that specifies an attempt to perform a multicast operation to the specified Internet address.

Parameter | Description
accesstype | The type of access requested. The value should be MULTICAST.
addr | The Internet address.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the NetIORequest object.

Return Value:

Returns PermissionID.NETIO.

Remarks:

This method satisfies the ISecurityRequest interface and returns PermissionID.NETIO to indicate that instances of the NetIORequest class are associated with the networking permission.

toString

public String toString ();

Converts the NetIORequest object to its string representation.

Return Value:

Returns the string representation of the NetIORequest object.

Fields

ACCEPT
The network I/O access type that indicates an attempt to accept network connections from a remote computer.
CONNECT
The network I/O access type that indicates an attempt to initiate a connection with a remote machine.
LISTEN
The network I/O access type that indicates an attempt to listen for networking connections on a local port.
MULTICAST
The network I/O access type that indicates an attempt to perform a multicast socket operation.


Class PrintingPermission

public class PrintingPermission implements IPermission,
            IEncodablePermission
{
  // Methods
  public void check(Object request) throws SecurityException;
  public IPermission combine (IPermission other);
  public int compareSet (Object other);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public String mapFormat(String format);
  public String[] supportedFormats();
}

This class represents a permission that controls access to the printing APIs. Security checks for the printing permission are non-parameterized. When the permission-based security model is enabled, classes that possess the PrintingPermission can use the printing services.

This class implements the IPermission and the IEncodablePermission interfaces.

Methods

check

public void check(Object request) throws SecurityException;

Performs a check on the permission object. Because checks for the printing permission are non-parameterized, this method always succeeds.

Return Value:

No return value.

Parameter | Description
request | This parameter is ignored.

combine

public IPermission combine (IPermission other);

Returns a new PrintingPermission instance. Because checks for the printing permission are non-parameterized, the combine operation serves no purpose.

Return Value:

Returns a new PrintingPermission instance.

Parameter | Description
other | This parameter is ignored, but it must be an instance of the PrintingPermission class.

compareSet

public int compareSet (Object other);

Compares the PrintingPermission instance with another permission object.

Return Value:

Returns EQUAL if the other object is an instance of the PrintingPermission class.

Parameter | Description
other | The permission object that the PrintingPermission instance is compared with. This parameter must be an instance of the PrintingPermission class.

Exceptions:

IllegalArgumentException if the specified Object is not an instance of the PrintingPermission class.

copy

public IPermission copy();

Retrieves a new instance of the PrintingPermission class.

Return Value:

Returns a new PrintingPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into the permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that this permission type supports.

Return Value:

Returns an array of the supported format identifiers.


Class PropertyAccessRequest

public class PropertyAccessRequest implements ISecurityRequest
{
  // Fields
  public static final int ALL;
  public static final int INDIVIDUAL;

  // Constructors
  public PropertyAccessRequest (int type,String param);
  public PropertyAccessRequest();
  public PropertyAccessRequest (String prop);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request to access the system properties. Use an instance of this class as the security request object for a parameterized security check involving the system properties permission. The PropertyPermission.check method expects a PropertyAccessRequest object as its parameter.

The following example shows how to use a PropertyAccessRequest object to perform a security check.

...
// Create a PropertyAccessRequest object that indicates
// that you want to read the system property called
// java.class.path.

PropertyAccessRequest sreq =
   new PropertyAccessRequest("java.class.path");

// Check to see that all of your callers have the
// rights to read that system property.

PolicyEngine.checkPermission(sreq);
...

For more information about checking system properties, see the PolicyEngine class and the PropertyPermission class.

Constructors

PropertyAccessRequest

public PropertyAccessRequest (int type,String param);

Creates a property access request for a specified access type and a specified property.

Return Value:

Returns the request object that represents a request for access to the specified property.

Parameter | Description
type | The type of property access. This can be ALL or INDIVIDUAL.
param | If type is INDIVIDUAL, this value should be the property name for the specified access type. If type is ALL, the value should be null.

PropertyAccessRequest

public PropertyAccessRequest();

Creates a property access request that indicates a request for unrestricted access to properties.

Return Value:

Returns the request object that indicates a request to access all system properties.

PropertyAccessRequest

public PropertyAccessRequest (String prop);

Creates a request object that represents an attempt to read the specified property.

Return Value:

Returns the request object that represents an attempt to read the specified property.

Parameter | Description
prop | The name of the system property to read.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the PropertyAccessRequest object.

Return Value:

Returns PermissionID.PROPERTY.

Remarks:

This method satisfies the ISecurityRequest interface and returns PermissionID.PROPERTY to indicate that instances of the PropertyAccessRequest class are associated with the system property permission.

toString

public String toString ();

Converts the PropertyAccessRequest object to its string representation.

Return Value:

Returns the string representation of the PropertyAccessRequest object.

Fields

ALL
The system property access type that indicates the unrestricted ability to read and modify all system properties.
INDIVIDUAL
The system property access type that indicates the ability to read the contents of a single specified system property.


Class PropertyPermission

public class PropertyPermission implements IPermission,
            IEncodablePermission
{
  // Constructors
  public PropertyPermission();

  // Methods
  public void addAllowedSuffix(String suffix);
  public boolean allowsUnrestrictedAccess();
  public void allowUnrestrictedAccess(boolean flag);
  public void check(Object param);
  public IPermission combine(IPermission other);
  public int compareSet(Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public void excludeProperties(String pattern);
  public String[] getAllowedSuffixes();
  public WildcardExpression getExcludedProperties();
  public WildcardExpression getIncludedProperties();
  public void includeProperties(String pattern);
  public String mapFormat(String format);
  public String mapFormat(String format);
  public void reset();
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to access and manipulate the global system properties. The StandardSecurityManager checks for this permission type when performing the checkPropertiesAccess and checkPropertyAccess operations.

This class implements the IPermission and IEncodablePermission interfaces.

Also see com.ms.security.permissions.PropertyAccessRequest

Constructors

PropertyPermission

public PropertyPermission();

Creates a new PropertyPermission instance.

Remarks:

The new instance does not allow access to any of the system properties. To add property names to the allowed set, you can use the allowUnrestrictedAccess, addAllowedSuffix, and the includeProperties methods.

Methods

addAllowedSuffix

public void addAllowedSuffix(String suffix);

Adds an allowed property suffix to the permission object.

Return Value:

No return value.

Parameter | Description
suffix | The property suffix to be added.

Remarks:

Property suffixes work like this: If you have access to a suffix "X", you have access to any system property "Y" if and only if a second system property named "Y.X" exists that is set to "true."

allowsUnrestrictedAccess

public boolean allowsUnrestrictedAccess();

Determines whether this permission object allows unrestricted access to system properties.

Return Value:

Returns true if this permission object allows unrestricted access to system properties.

allowUnrestrictedAccess

public void allowUnrestrictedAccess(boolean flag);

Turns unrestricted property access on or off, depending on the value of the flag. Unrestricted property access allows you to read all system properties, and to obtain the system properties object and manipulate it.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether access to unrestricted properties should be turned on or off.

check

public void check(Object param);

Determines whether the permission allows the system property access specified by the PropertyAccessRequest parameter.

Parameter | Description
param | The security request parameter. It must be an instance of PropertyAccessRequest.

Remarks:

If the PropertyAccessRequest is requesting ALL access, this check will only succeed if this permission object has unrestricted access to the system properties. Otherwise, the PropertyAccessRequest parameter indicates a request for access to a specific system property by name. In this case, the following rules are used to determine whether the check passes or fails.

  1. If the permission object allows unrestricted access, the check passes.
  2. If the specified property is within the set of explicitly denied properties, the check fails.
  3. If the specified property is within the set of explicitly allowed properties, the check succeeds. Otherwise, the check fails.

Exceptions:

SecurityException if this permission does not allow access to the specified system property.

combine

public IPermission combine(IPermission other);

Creates and returns a new PropertyPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting PropertyPermission.

Parameter | Description
other | The PropertyPermission to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of PropertyPermission.

compareSet

public int compareSet(Object target);

Compares the PropertyPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the PropertyPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the PropertyPermission object.

Return Value:

Returns the PropertyPermission object that is a copy of the current PropertyPermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

excludeProperties

public void excludeProperties(String pattern);

Explicitly excludes system properties from the set of properties that this permission allows access to.

Return Value:

No return value.

Parameter | Description
pattern | The pattern that specifies the system properties that are explicitly prohibited. This pattern can contain wildcard expressions.

Remarks:

Because access to all system properties is prohibited by default, this method is only useful to remove properties from those explicitly included by a wildcard expression.

For example, the following code allows access to all properties beginning with 'java.', except for the property named "java.class.path".

   ...
   PropertyPermission perm = new PropertyPermission()
   eperm.includeProperties("java.*");
   eperm.excludeProperties("java.class.path");
   ...

Note This method does nothing if the permission object already specifies unrestricted access.

See Also: com.ms.util.WildcardExpression

getAllowedSuffixes

public String[] getAllowedSuffixes();

Retrieves the list of property suffixes that the permission object allows access to.

Return Value:

Returns the list of property suffixes that the permission object allows access to.

getExcludedProperties

public WildcardExpression getExcludedProperties();

Retrieves a wildcard expression that represents all the properties that this permission object explicitly denies access to.

Return Value:

Returns the wildcard expression that represents all the properties that this permission object explicitly denies access to.

See Also: com.ms.util.WildcardExpression

getIncludedProperties

public WildcardExpression getIncludedProperties();

Retrieves a wildcard expression that represents all the properties that this permission object allows access to.

Return Value:

Returns the wildcard expression that represents all the properties that this permission object allows access to.

See Also: com.ms.util.WildcardExpression

includeProperties

public void includeProperties(String pattern);

Adds specific properties to the set of properties that the permission allows access to. The properties are specified by a pattern string that can contain wildcard expressions.

Examples:

  includeProperties("java.class.path");
  includeProperties("java.*");

Note This method does nothing if the permission object already specifies unrestricted access.

Return Value:

No return value.

Parameter | Description
pattern | The pattern that specifies the system properties that can be accessed. This pattern can contain wildcard expressions.

See Also: com.ms.util.WildcardExpression

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission object to a state in which it allows access to no system properties.

Return Value:

No return value.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class ReflectionPermission

public class ReflectionPermission implements IPermission,
            IEncodablePermission, IAdjustablePermission
{
  // Fields
  public static int ALL;
  public static int DIFFERENTLOADER;
  public static int NONE;
  public static int SAMELOADER;
  public static int SYSTEMLOADER;

  // Constructors
  public ReflectionPermission();

  // Methods
  public void adjustPermission (String tag, Object adjustment);
  public void check(Object param);
  public IPermission combine (IPermission source2);
  public int compareSet(Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public int getAllowedAccess(int accessType);
  public int getAllowedDeclaredAccess();
  public int getAllowedPublicAccess();
  public ClassLoader getAssociatedLoader();
  public String mapFormat(String format);
  public void reset();
  public void setAllowedDeclaredAccess(int loadertypes);
  public void setAllowedPublicAccess(int loadertypes);
  public void setAssociatedLoader(ClassLoader ldr);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to perform reflection operations. The StandardSecurityManager checks for this permission type when performing the checkMemberAccess operation.

A ReflectionPermission distinguishes between two different types of reflection operations:

Public
Reflective access to a public member of some class. This type of access is specified by the constant java.lang.reflect.Member.PUBLIC.
Declared
Reflective access to any member of a given class. This type of access is specified by the constant java.lang.reflect.Member.DECLARED.

A ReflectionPermission object further distinguishes between types of reflection operations, depending on the type of class being reflected. The types of classes that can be reflected are as follows:

SAMELOADER
A class from the same loader as the class initiating the reflection operation.
DIFFERENTLOADER
A non-system class from a loader other than that of the class that is initiating the reflection operation.
SYSTEMLOADER
A System class.

Also see com.ms.security.permissions.ReflectionRequest

Constructors

ReflectionPermission

public ReflectionPermission();

Creates a new ReflectionPermission instance. The new instance does not allow reflective access to any classes.

Methods

adjustPermission

public void adjustPermission (String tag, Object adjustment);

Adjusts the permission object with some runtime state. The ReflectionPermission only responds to the "classloader" adjustment type. This method expects the adjustment parameter to be a ClassLoader instance. All other adjustment types are ignored. The class loader instance used for the adjustment parameter is the loader that SAMELOADER will refer to after this method adjusts the class loader.

Note The "classloader" adjustment to this permission is equivalent to an explicit setAssociatedLoader call.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type. Every value except "classloader" is ignored.
adjustment | This parameter must be an instance of java.lang.ClassLoader for the "classloader" tag.

check

public void check(Object param);

Determines whether the permission object allows the specified action. The request parameter represents a request to perform a particular action. The type of the parameter depends on the type of the permission object.

Return Value:

No return value.

Parameter | Description
param | The object that represents the action for which permission is being checked.

Exceptions:

SecurityException if the state of the permission object indicates that the action is not allowed.

combine

public IPermission combine (IPermission source2);

Creates and returns a new ReflectionPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting ReflectionPermission object.

Parameter | Description
source2 | The permission object that indicates additional resources to allow access to.

compareSet

public int compareSet(Object target);

Compares the ReflectionPermission instance with a specified permission object

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the ReflectionPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the ReflectionPermission instance.

Return Value:

Returns the copy of the ReflectionPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes a source according to the specified tag. This method implements the IEncodablePermission.decode method.

Return Value:

Returns true if the decoding process is completed successfully; otherwise, returns false.

Parameter | Description
tag | The tag used for the decoding. It is the same tag that was used to encode the data.
data | The stream that contains the encoded permission.

encode

public boolean encode(String tag, OutputStream out);

Encodes a source according to the specified tag. This method implements the IEncodablePermission.encode method.

Return Value:

Returns true if the encoding process is completed successfully; otherwise, returns false.

Parameter | Description
tag | The string that indicates how to encode the data.
out | The stream to write the encoded data to.

getAllowedAccess

public int getAllowedAccess(int accessType);

Retrieves the types of classes that the permission object allows access to, based on a reflective access type.

Return Value:

Returns the types of classes that the permission object allows access to. This will be one of the following: SAMELOADER, DIFFERENTLOADER, SYSTEMLOADER, ALL, or NONE.

Parameter | Description
accessType | The reflective access type. It must be either java.lang.reflect.Member.PUBLIC or java.lang.reflect.Member.DECLARED.

Exceptions:

IllegalArgumentException if the accessType parameter is not equal to java.lang.reflect.Member.PUBLIC or java.lang.reflect.Member.DECLARED.

getAllowedDeclaredAccess

public int getAllowedDeclaredAccess();

Retrieves the types of classes that the permission object allows declared access to.

Return Value:

Returns the types of classes that the permission object allows declared access to. This will be one of the following: SAMELOADER, DIFFERENTLOADER, SYSTEMLOADER, ALL, or NONE.

getAllowedPublicAccess

public int getAllowedPublicAccess();

Retrieves the types of classes that the permission object allows public access to.

Return Value:

Returns the types of classes that the permission object allows public access to. This will be one of the following: SAMELOADER, DIFFERENTLOADER, SYSTEMLOADER, ALL, or NONE.

getAssociatedLoader

public ClassLoader getAssociatedLoader();

Retrieves the class loader associated with this permission object.

Return Value:

Returns the class loader associated with the permission object.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag when given an encoding format. The tag can be used with the encode and decode methods to specify an encoding type. This method implements the IEncodablePermission.mapFormat method.

Return Value:

Returns the tag used to encode the data in the given format. If the specified format is not supported, null is returned.

Parameter | Description
format | The format that the tag is requested for. If format is null, the default format for the class is returned.

reset

public void reset();

Resets the permission object to a state in which it allows no reflection access.

Return Value:

No return value.

setAllowedDeclaredAccess

public void setAllowedDeclaredAccess(int loadertypes);

Sets the types of classes that the permission object allows declared reflective access to. The classes are specified by the loader types.

For example, the following code indicates that the permission should only allow declared reflective access to classes from the same loader.

    ...
    ReflectionPermission perm = new ReflectionPermission();
    perm.setAssociatedLoader( some loader );
    perm.setAllowedDeclaredAccess(ReflectionPermission.SAMELOADER);
    ...

Return Value:

No return value.

Parameter | Description
loadertypes | The types of classes that the permission object will allow declared reflective access to. This should be one of the following types: SAMELOADER, DIFFERENTLOADER, SYSTEMLOADER, ALL, or NONE.

setAllowedPublicAccess

public void setAllowedPublicAccess(int loadertypes);

Sets the types of classes that the permission object allows public reflective access to. The classes are specified by the loader types.

For example, the following code indicates that the permission should allow reflective access to public members of all classes.

    ...
    ReflectionPermission perm = new ReflectionPermission();
    perm.setAllowedPublicAccess(ReflectionPermission.ALL);
    ...

Return Value:

No return value.

Parameter | Description
loadertypes | The types of classes that the permission object allows public reflective access to. This should be one of the following types: SAMELOADER, DIFFERENTLOADER, SYSTEMLOADER, ALL, or NONE.

setAssociatedLoader

public void setAssociatedLoader(ClassLoader ldr);

Sets the class loader that this permission is associated with. The associated class loader should be the class loader that loaded the classes that this permission will be assigned to. The loader access type SAMELOADER refers to the class loader set by this method.

Return Value:

No return value.

Parameter | Description
ldr | The class loader object.

supportedFormats

public String[] supportedFormats();

Retrieves a list of supported formats. This method implements the IEncodablePermission.supportedFormats method.

Return Value:

Returns the supported formats.

toString

public String toString();

Converts the permission object to its string representation.

Return Value:

Returns the string representation of the permission object.

Fields

ALL
A loader type that indicates all classes.
DIFFERENTLOADER
A loader type that refers to any loaders other than the one associated with this permission instance. If no loader has been associated with this permission, this loader type refers to all non-system classes.
NONE
A loader type that indicates no classes.
SAMELOADER
A loader type that refers to the loader that has been associated with this permission object with the setAssociatedLoader method. If no loader has been associated with this permission instance, this loader type has no meaning.
SYSTEMLOADER
A loader type that indicates system classes.


Class ReflectionRequest

public class ReflectionRequest implements ISecurityRequest
{
  // Constructors
  public ReflectionRequest(int type, Class target);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request to use the reflection APIs to gain access to members of a specified class. The type of access can be either to public members or to declared members of the class. ReflectionRequest objects should be used as the security request objects for parameterized security checks involving the reflection permission. The ReflectionPermission.check method expects a ReflectionRequest object as its parameter.

Here is an example that shows how to use a ReflectionRequest object to perform a security check.

  ...
  // Create a ReflectionRequest object that indicates that you want to
  // access the public members of a specific class.

  Class cls = java.lang.String.class;
  ReflectionRequest sreq = new ReflectionRequest(Member.PUBLIC,cls);

  // Check to see that all of your callers have the rights to
  // access the public members of the class.

  PolicyEngine.checkPermission(sreq);
  ...

For more information about checking reflection permissions, see the PolicyEngine class and the ReflectionPermission class.

Constructors

ReflectionRequest

public ReflectionRequest(int type, Class target);

Creates a ReflectionRequest object based on the access type requested and the class instance to reflect.

Parameter | Description
type | The type of reflection access that is requested. This value must be either java.lang.reflect.Member.PUBLIC or java.lang.reflect.Member.DECLARED.
target | The class to examine with the reflection APIs.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the ReflectionRequest object.

Return Value:

Returns PermissionID.REFLECTION.

Remarks:

This method satisfies the ISecurityRequest interface and returns PermissionID.REFLECTION to indicate that instances of the ReflectionRequest class are associated with the reflection permission.

toString

public String toString ();

Converts the ReflectionRequest object to its string representation.

Return Value:

Returns the string representation of the ReflectionRequest object.


Class RegistryPermission

public class RegistryPermission implements IPermission,
            IEncodablePermission
{
  // Fields
  public static final int CREATE;
  public static final int DELETE;
  public static final int OPEN;
  public static final int READ;
  public static final int WRITE;

  // Constructors
  public RegistryPermission ();

  // Methods
  public void check(Object param);
  public IPermission combine(IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public void excludeRule(int access, String pattern);
  public WildcardExpression getExcludedRules(int accessType);
  public WildcardExpression getIncludedRules(int accessType);
  public void includeRule(int access, String pattern);
  public String mapFormat(String format);
  public void reset ();
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to access the registry. The StandardSecurityManager checks for this permission type when performing the checkRegistry operation.

The registry permission distinguishes between five different types of access to registry keys or values, shown in the following list.

OPEN
Keys can be opened (does not apply to values).
READ
Information about a key or value can be read.
WRITE
A key or value can be modified.
DELETE
A key or value can be deleted.
CREATE
A key or value can be created.

The specific key or value allowed for each operation is defined by a pair of include/exclude patterns. Keys are specified by a trailing backslash (\). Absolute registry paths must start with a root key specifier, which is one of the following strings:

"HKCR"
HKEY_CLASSES_ROOT
"HKLM"
HKEY_LOCAL_MACHINE
"HKCU"
HKEY_CURRENT_USER
"HKUR"
HKEY_USERS

For example, "HKCU\\dog\\" specifies a key named "dog" under HKEY_CURRENT_USER. But "HKCU\\dog\\Fido" specifies the value named "Fido" within the key HKEY_CURRENT_USER\dog.

Note In source code, you must type two backslashes to represent the single backslash necessary for specifying a key.

Also see com.ms.security.permissions.RegistryRequest

Constructors

RegistryPermission

public RegistryPermission ();

Creates a new RegistryPermission instance. The new instance will not allow any access to any portion of the registry. Access to specific portions of the registry must be explicitly enabled.

Methods

check

public void check(Object param);

Determines whether the specified registry operation is allowed by the permission object.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of the RegistryRequest class.

Exceptions:

SecurityException if this permission does not allow the specified operation.

combine

public IPermission combine(IPermission source2);

Creates and returns a new RegistryPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting RegistryPermission object.

Parameter | Description
source2 | The other RegistryPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of RegistryPermission.

compareSet

public int compareSet (Object target);

Compares the RegistryPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the RegistryPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the RegistryPermission object.

Return Value:

Returns the copy of the RegistryPermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

excludeRule

public void excludeRule(int access, String pattern);

Adds a rule that explicitly denies the specified access type to the registry keys or values specified by the pattern string. This method is used to modify a previously allowed rule to a more restricted type of access.

Return Value:

No return value.

Parameter | Description
access | The access types being added. Must be one of the following types: OPEN, READ, WRITE, DELETE, or CREATE, or any combination of these types used with the OR operator.
pattern | The registry keys/values to which the specified access type is being added. This parameter must be of the form accepted by a WildcardExpression with the ESCAPED flag enabled.

getExcludedRules

public WildcardExpression getExcludedRules(int accessType);

Returns the wildcard expression representing all the keys or values that are explicitly denied for the specified access type.

Return Value:

Returns the wildcard expression representing all the keys/values that are explicitly denied for the specified access type.

Parameter | Description
accessType | This value must be one of the following: OPEN, READ, WRITE, DELETE, or CREATE.

getIncludedRules

public WildcardExpression getIncludedRules(int accessType);

Retrieves the wildcard expression that represents all the keys or values that are allowed for the specified access type.

Return Value:

Returns the wildcard expression representing all the keys or values that are allowed for the specified access type.

Parameter | Description
accessType | The type of access used to determine the wildcard expression. This value must be one of the following: OPEN, READ, WRITE, DELETE, or CREATE.

includeRule

public void includeRule(int access, String pattern);

Adds a rule that allows the specified access types to the registry keys/values specified by the pattern string.

Return Value:

No return value.

Parameter | Description
access | The access types being added. Must be one of the following types: OPEN, READ, WRITE, DELETE, or CREATE, or any combination of these types used with the OR operator (|).
pattern | The registry keys or values to which the specified access type is being added. This parameter must be of the form accepted by a WildcardExpression with the ESCAPED flag enabled.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset ();

Resets the permission state to empty. This is a state in which the object allows no registry access.

Return Value:

No return value.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.

Fields

CREATE
An access type that indicates that a key or value can be created.
DELETE
An access type that indicates that a key or value can be deleted.
OPEN
An access type that indicates that keys can be opened.
READ
An access type that indicates that information about a key or value can be read.
WRITE
An access type that indicates that a key or value can be modified.


Class RegistryRequest

public class RegistryRequest implements ISecurityRequest
{
  // Fields
  public static final int CREATE;
  public static final int DELETE;
  public static final int OPEN;
  public static final int READ;
  public static final int WRITE;

  // Constructors
  public RegistryRequest (int access, String value);

  // Methods
  public PermissionID getPermissionID();
  public String toString ();
}

This class represents a request for access to a registry key. It should be used as the security request object for a parameterized security check involving registry permissions. The RegistryPermission.check method expects a RegistryRequest object as its parameter.

The following example shows how to use a RegistryRequest object to perform a security check to see if a specific registry key can be accessed.

// Create a ReqistryRequest object that indicates that you want
// to read the registry key "HKLM\Software\stuff".

RegistryRequest sreq =
   new RegistryRequest(RegistryRequest.READ,"HKLM\Software\stuff");

// Check to see that all of your callers have the rights to
// read that registry key.

PolicyEngine.checkPermission(sreq);
...

For more information about checking registry permissions, see the com.ms.security.PolicyEngine class and the RegistryPermission class.

Constructors

RegistryRequest

public RegistryRequest (int access, String value);

Creates a RegistryRequest object based on the specified access type and value.

Parameter | Description
access | The type of access requested. It must be one of the following: OPEN, READ, WRITE, DELETE, or CREATE.
value | The key or value for which access is requested.

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the RegistryRequest object.

This method satisfies the ISecurityRequest interface and returns PermissionID.REGISTRY to indicate that instances of the RegistryRequest class are associated with the registry permission.

Return Value:

Returns PermissionID.REGISTRY.

toString

public String toString ();

Converts the RegistryRequest object to its string representation.

Return Value:

Returns the string representation of the RegistryRequest object.

Fields

CREATE
The registry access type that represents a request to create a key or value.
DELETE
The registry access type that represents a request to delete a key or value.
OPEN
The registry access type that represents an attempt to open a registry key.
READ
The registry access type that represents a request to read or obtain information about a key or value.
WRITE
The registry access type that represents a request to modify a key or value.


Class SecurityPermission

public class SecurityPermission implements IPermission,
            IEncodablePermission
{
  // Methods
  public void check(Object request) throws SecurityException;
  public IPermission combine (IPermission other);
  public int compareSet (Object other);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public String mapFormat(String format);
  public String[] supportedFormats();
}

This class represents a permission that controls access to the JDK security classes (the java.lang.security package). Checks for the security permission are non-parameterized.

This class implements the IPermission and the IEncodablePermission interfaces.

Methods

check

public void check(Object request) throws SecurityException;

Performs a check on the permission object. Because checks for the security permission are non-parameterized, this method always succeeds.

Return Value:

No return value.

Parameter | Description
request | This parameter is ignored.

combine

public IPermission combine (IPermission other);

Creates and returns a new SecurityPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns a new SecurityPermission instance.

Parameter | Description
other | This parameter is ignored, but it must be an instance of the SecurityPermission class.

compareSet

public int compareSet (Object other);

Compares the SecurityPermission instance with a specified permission object.

Return Value:

Returns EQUAL if the specified object is an instance of the SecurityPermission class.

Parameter | Description
other | The permission object that the SecurityPermission instance is compared with. The specified object must be an instance of the SecurityPermission class.

Exceptions:

IllegalArgumentException if the specified Object is not an instance of the SecurityPermission class.

copy

public IPermission copy();

Retrieves a new instance of the SecurityPermission class.

Return Value:

Returns a new SecurityPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.


Class SystemStreamsPermission

public class SystemStreamsPermission implements IPermission,
            IEncodablePermission
{
  // Constructors
  public SystemStreamsPermission();

  // Methods
  public boolean canSetSystemErr();
  public boolean canSetSystemIn();
  public boolean canSetSystemOut();
  public void check (Object param) throws SecurityException;
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public String mapFormat(String format);
  public void reset();
  public void setCanSetSystemErr(boolean allow);
  public void setCanSetSystemIn(boolean allow);
  public void setCanSetSystemOut(boolean allow);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to change the values of the system streams java.lang.System.in, java.lang.System.out, and java.lang.System.err. The StandardSecurityManager checks for this permission type when performing a checkSystemStreams operation. This class implements the IPermission and IEncodablePermission interfaces.

Constructors

SystemStreamsPermission

public SystemStreamsPermission();

Creates a new SystemStreamsPermission instance.

Remarks:

The new instance does not allow access to any of the system streams. Access to a stream must be explicitly turned on by using one of the setCanSetSystemIn, setCanSetSystemOut, and setCanSetSystemErr methods.

Methods

canSetSystemErr

public boolean canSetSystemErr();

Determines whether the permission object allows the System.err stream to be set.

Return Value:

Returns true if the permission object allows the System.err stream to be set; otherwise, returns false.

canSetSystemIn

public boolean canSetSystemIn();

Determines whether the permission object allows the System.in stream to be set.

Return Value:

Returns true if the permission object allows the System.in stream to be set; otherwise, returns false.

canSetSystemOut

public boolean canSetSystemOut();

Determines whether the permission object allows the System.out stream to be set.

Return Value:

Returns true if the permission object allows the System.out stream to be set; otherwise, returns false.

check

public void check (Object param) throws SecurityException;

Determines whether the permission object allows the specified system stream to be set.

Return Value:

No return value.

Parameter Description
param The security request parameter. This parameter must be an instance of java.lang.Integer, whose value is interpreted as follows:
0
Indicates an attempt to set System.in.
1
Indicates an attempt to set System.out.
2
Indicates an attempt to set System.err.

Exceptions:

SecurityException if the permission does not allow the specified operation.

combine

public IPermission combine (IPermission source2);

Creates and returns a new SystemStreamsPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting SystemStreamsPermission object.

Parameter | Description
source2 | The SystemStreamsPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of SystemStreamsPermission.

compareSet

public int compareSet (Object target);

Compares the SystemStreamsPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the SystemStreamsPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the SystemStreamsPermission object.

Return Value:

Returns the copy of the SystemStreamsPermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission object to a state where it does not allow access to any of the system streams.

Return Value:

No return value.

setCanSetSystemErr

public void setCanSetSystemErr(boolean allow);

Sets whether this permission object allows the system stream System.err to be set by classes that possess this permission instance.

Return Value:

No return value.

Parameter | Description
allow | The value that indicates whether the permission allows System.err to be set. This value must be set to true if this permission should allow System.err to be set; otherwise, it should be set to false.

setCanSetSystemIn

public void setCanSetSystemIn(boolean allow);

Sets whether this permission object allows the system stream System.in to be set by classes that possess this permission instance.

Return Value:

No return value.

Parameter | Description
allow | The value that indicates whether the permission allows System.in to be set. This value must be true if this permission should allow System.in to be set; otherwise, it should be false.

setCanSetSystemOut

public void setCanSetSystemOut(boolean allow);

Sets whether this permission object allows the system stream System.out to be set by classes that possess this permission instance.

Return Value:

No return value.

Parameter | Description
allow | The value that indicates whether the permission allows System.out to be set. This value must be true if this permission should allow System.out to be set; otherwise, it should be false.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class ThreadPermission

public class ThreadPermission implements IPermission,
            IEncodablePermission, IAdjustablePermission
{
  // Constructors
  public ThreadPermission();

  // Methods
  public void adjustPermission (String tag, Object adjustment);
  public void check (Object param) throws SecurityException;
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public ThreadGroup getAllowedThreadGroup();
  public boolean isThreadAccessUnrestricted();
  public boolean isThreadGroupAccessUnrestricted();
  public String mapFormat(String format);
  public void reset();
  public void setAllowedThreadGroup(ThreadGroup tg);
  public void setUnrestrictedThreadAccess(boolean f);
  public void setUnrestrictedThreadGroupAccess(boolean flag);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to create and manipulate threads and thread groups. The StandardSecurityManager class checks for this permission type when performing its checkAccess methods.

You can use a ThreadPermission object to allow unrestricted thread or thread group access. Or, you can specify a ThreadGroup instance that defines a subset of the thread group space, within which the ThreadPermission object allows threading operations to take place.

Constructors

ThreadPermission

public ThreadPermission();

Creates a new ThreadPermission instance that does not allow any threading operations.

Methods

adjustPermission

public void adjustPermission (String tag, Object adjustment);

Adjusts the ThreadPermission object with some runtime state.

Return Value:

No return value.

Parameter | Description
tag | The adjustment type. Any value other than "threadgroup" is ignored.
adjustment | This parameter must be an instance of java.lang.ThreadGroup. It indicates a portion of the thread group space.

Remarks:

The ThreadPermission object only responds to the "threadgroup" adjustment type, and it expects the adjustment parameter to be a ThreadGroup object (in that case). All other adjustment types are ignored.

Usually, a ThreadPermission object allows unrestricted thread and thread group access within a specific ThreadGroup. However, this method can be called to allow a loader to grant some loaded code (an applet, for example) a portion of the thread group space in which it can perform threading operations.

Note The "threadgroup" adjustment to a ThreadPermission object is equivalent to explicitly calling the setAllowedThreadGroup method.

check

public void check (Object param) throws SecurityException;

Determines whether the specified threading object can be manipulated.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of Thread or ThreadGroup.

Remarks:

If the specified Object is a Thread, the check takes place as follows.

  1. If the permission allows unrestricted thread access, the check succeeds.
  2. If the Thread exists within the ThreadGroup object associated with this permission or within one of its children, the check succeeds. Otherwise, it fails.

If the specified Object is a ThreadGroup, the check takes place as follows.

  1. If the permission allows unrestricted thread group access, the check succeeds.
  2. If the ThreadGroup is the ThreadGroup object associated with this permission or one of its children, the check succeeds. Otherwise, it fails.

Exceptions:

SecurityException if the permission does not allow access to the specified threading object.

combine

public IPermission combine (IPermission source2);

Creates and returns a new ThreadPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the ThreadPermission object that results from combining.

Parameter | Description
source2 | The other ThreadPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of ThreadPermission.

compareSet

public int compareSet (Object target);

Compares the ThreadPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the ThreadPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the ThreadPermission instance.

Return Value:

Returns the copy of the ThreadPermission instance.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getAllowedThreadGroup

public ThreadGroup getAllowedThreadGroup();

Retrieves the ThreadGroup object that defines the domain in which classes that possess this permission are allowed to perform threading operations.

Return Value:

Returns the thread group that can be manipulated.

isThreadAccessUnrestricted

public boolean isThreadAccessUnrestricted();

Determines whether this permission grants unlimited access to Thread objects.

Return Value:

Returns true if access to Thread objects is unrestricted; otherwise, returns false.

isThreadGroupAccessUnrestricted

public boolean isThreadGroupAccessUnrestricted();

Determines whether this permission grants unlimited access to ThreadGroup objects.

Return Value:

Returns true if access to ThreadGroup objects is unrestricted; otherwise, returns false.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission object to empty, which is a state in which the permission allows no threading operations.

Return Value:

No return value.

setAllowedThreadGroup

public void setAllowedThreadGroup(ThreadGroup tg);

Sets a ThreadGroup that defines the domain in which the permission object allows manipulation of Thread or ThreadGroup objects.

Return Value:

No return value.

Parameter | Description
tg | The thread group that can be manipulated.

Remarks:

Classes that possess this permission can manipulate any threads within this ThreadGroup or within any child ThreadGroup of this ThreadGroup. The permission also allows the manipulation of the specified ThreadGroup or any of its children.

setUnrestrictedThreadAccess

public void setUnrestrictedThreadAccess(boolean f);

Sets the ability to manipulate any Thread object in the system.

Return Value:

No return value.

Parameter | Description
f | The flag that indicates whether to turn unrestricted Thread access on or off. If the value is true, the ability to manipulate all Thread objects is turned on; otherwise, it is turned off.

setUnrestrictedThreadGroupAccess

public void setUnrestrictedThreadGroupAccess(boolean flag);

Sets the ability to manipulate any ThreadGroup object in the system.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether to turn unrestricted ThreadGroup access on or off. If the value is true, the ability to manipulate all ThreadGroup objects is turned on; otherwise, it is turned off.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


Class UIAccessRequest

public class UIAccessRequest implements ISecurityRequest
{
  // Constructors
  public UIAccessRequest (int accessType);

  // Methods
  public PermissionID getPermissionID();
  public boolean isWarningBannerNeeded();
  public String toString ();
}

This class represents objects that indicate a request to use an extended aspect of the user interface APIs. UIAccessRequest objects are intended to be used as the security request objects for parameterized security checks involving the user interface permission. The UIPermission.check method expects a UIAccessRequest object as its parameter.

The following example shows how to use a UIAccessRequest object to check permission to create a top-level window.

  ...
  // Create a UIAccessRequest object that indicates that you
  // want to create top-level windows.

  UIAccessRequest sreq = new UIAccessRequest(UIPermission.ALLOW_TOPLEVELWINDOW);

  // Check to see that all of your callers have the rights to
  // create top-level windows.

  PolicyEngine.checkPermission(sreq);
  ...

For more information about checking user interface permissions, see the PolicyEngine class and the UIPermission class.

Constructors

UIAccessRequest

public UIAccessRequest (int accessType);

Creates a UIAccessRequest object based on a specified access type.

Return Value:

Returns a request object that indicates a request to access the specified UI feature.

Parameter Description
accessType The type of access that is being requested. The value must be one of the following constants from the UIPermission class:

  • ALLOW_CLIPBOARD
  • ALLOW_TOPLEVELWINDOW
  • ALLOW_FILEDIALOG
  • ALLOW_EVENTQUEUEACCESS

Methods

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier for the UIAccessRequest object. This method satisfies the ISecurityRequest interface and returns PermissionID.UI to indicate that instances of the UIAccessRequest class are associated with the user interface permission.

Return Value:

Returns PermissionID.UI.

isWarningBannerNeeded

public boolean isWarningBannerNeeded();

Determines whether top-level windows need warning banners.

Return Value:

Returns true if top-level windows need warning banners; otherwise, returns false.

toString

public String toString ();

Converts the UIAccessRequest object to its string representation.

Return Value:

Returns the string representation of the UIAccessRequest object.


Class UIPermission

public class UIPermission implements IPermission,
            IEncodablePermission
{
  // Fields
  public static final int ALLOW_CLIPBOARD;
  public static final int ALLOW_EVENTQUEUEACCESS;
  public static final int ALLOW_FILEDIALOG;
  public static final int ALLOW_TOPLEVELWINDOW;

  // Constructors
  public UIPermission();

  // Methods
  public void check (Object param);
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public boolean getClipboardAccess();
  public boolean getEventQueueAccessAllowed();
  public boolean getFileDialogsAllowed();
  public boolean getTopLevelWindowCreationAllowed();
  public boolean getWarningBannersRequired();
  public String mapFormat(String format);
  public void reset();
  public void setClipboardAccess(boolean flag);
  public void setEventQueueAccessAllowed(boolean flag);
  public void setFileDialogsAllowed(boolean flag);
  public void setTopLevelWindowCreationAllowed(boolean flag);
  public void setWarningBanners(boolean flag);
  public String[] supportedFormats();
  public String toString();
}

This class represents a permission that controls the ability to use some of the enhanced functionality of the AWT. Specifically, the UI (user interface) permission controls the ability to do the following:

  • Create top-level windows
  • Access the system clipboard
  • Create file dialog boxes
  • Access the AWT event queue

You can also use this permission to determine whether top-level windows require warning banners.

The StandardSecurityManager class checks for this permission type when performing the checkFileDialog, checkSystemClipboardAccess, checkAwtEventQueueAccess, and checkTopLevelWindow operations.

This class implements the IPermission and IEncodablePermission interfaces.

Also see com.ms.security.permissions.UIAccessRequest

Constructors

UIPermission

public UIPermission();

Creates a new UIPermission instance. The new instance will not allow access to any of the extended AWT functionality. Specific features must be explicitly turned on to enable access.

Methods

check

public void check (Object param);

Determines if the permission object allows the specified UI operation.

Return Value:

No return value.

Parameter | Description
param | The security request parameter. It must be an instance of UIAccessRequest.

Exceptions:

SecurityException if this permission does not allow the specified operation.

combine

public IPermission combine (IPermission source2);

Creates and returns a new UIPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects it was constructed from.

Return Value:

Returns the resulting UIPermission object.

Parameter | Description
source2 | The UIPermission object to combine with.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of UIPermission.

compareSet

public int compareSet (Object target);

Compares the UIPermission instance with the specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the UIPermission instance is compared with. This parameter must be an instance of the UIPermission class.

Exceptions:

IllegalArgumentException if the specified Object is not an instance of UIPermission.

copy

public IPermission copy();

Retrieves a copy of this UIPermission object.

Return Value:

Returns the copy of the UIPermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object, and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getClipboardAccess

public boolean getClipboardAccess();

Determines whether the object indicates permission to access the Clipboard.

Return Value:

Returns true if the object indicates permission to access the Clipboard; otherwise, returns false.

getEventQueueAccessAllowed

public boolean getEventQueueAccessAllowed();

Determines whether the permission object indicates the ability to access the AWT event queue.

Return Value:

Returns true if the permission object indicates the ability to access the AWT event queue.

getFileDialogsAllowed

public boolean getFileDialogsAllowed();

Determines whether the permission object indicates the ability to create file dialog boxes.

Return Value:

Returns true if the permission object indicates the ability to create file dialog boxes; otherwise, returns false.

getTopLevelWindowCreationAllowed

public boolean getTopLevelWindowCreationAllowed();

Determines whether the permission object indicates permission to create top-level windows.

Return Value:

Returns true if the permission object indicates permission to create top-level windows; otherwise, returns false.

getWarningBannersRequired

public boolean getWarningBannersRequired();

Determines whether the permission object indicates that top-level windows require warning banners.

Return Value:

Returns true if the permission object indicates that top-level windows require warning banners; otherwise, returns false.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

reset

public void reset();

Resets the permission object to a state in which it allows no access to any of the special UI behaviors.

Return Value:

No return value.

setClipboardAccess

public void setClipboardAccess(boolean flag);

Sets the ability to access the system clipboard. If flag is set to true, the permission object will indicate that access to the Clipboard is allowed; otherwise, it will indicate that access to the Clipboard is not allowed.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether access to the Clipboard should be allowed.

setEventQueueAccessAllowed

public void setEventQueueAccessAllowed(boolean flag);

Sets the ability to access the AWT event queue. If flag is set to true, the permission object will indicate that access to the AWT event queue is allowed; otherwise, it will indicate that access to the AWT event queue is not allowed.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether access to the AWT event queue should be allowed.

setFileDialogsAllowed

public void setFileDialogsAllowed(boolean flag);

Sets the ability to use file dialog boxes. If flag is set to true, the permission object will indicate that top-level windows require warning banners; otherwise, it will indicate that top-level windows do not require warning banners.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether top-level windows should require warning banners.

setTopLevelWindowCreationAllowed

public void setTopLevelWindowCreationAllowed(boolean flag);

Sets the ability to create a top-level window. If flag is set to true, the permission object will indicate that top-level window creation is allowed; otherwise, it will indicate that top level window creation is not allowed.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether top-level window creation should be allowed.

setWarningBanners

public void setWarningBanners(boolean flag);

Sets the ability to display warning banners. If flag is set to true, the permission object will indicate that top-level windows require warning banners; otherwise, it will indicate that top-level windows do not require warning banners.

Return Value:

No return value.

Parameter | Description
flag | The flag that indicates whether top-level windows should require warning banners.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString();

Converts the permission object to a textual representation.

Return Value:

Returns the string representation of the permission object.

Fields

ALLOW_CLIPBOARD
Flag that indicates a request for access to the Clipboard.
ALLOW_EVENTQUEUEACCESS
Flag that indicates a request for access to the AWT event queue.
ALLOW_FILEDIALOG
Flag that indicates a request for access to file dialog boxes.
ALLOW_TOPLEVELWINDOW
Flag that indicates a request for the ability to create top level windows.


Class UserFileIOAccess

public class UserFileIOAccess implements ISecurityRequest
{
  // Fields
  public static final int READ;
  public static final int READWRITE;
  public static final int WRITE;

  // Constructors
  public UserFileIOAccess(int accessType);

  // Methods
  public int getAccessFlags();
  public PermissionID getPermissionID();
  public String toString ();
  public static boolean validAccessType(int acc);
}

This class represents a request to perform a user-directed file I/O operation. UserFileIOAccess instances are intended to be used as the security request objects for parameterized security checks involving the user-directed file I/O permission. The UserFileIOPermission.check method expects a UserFileIOAccess object as its parameter.

The following example shows how to use a UserFileIOAccess object to check permission for user-directed file I/O operations.

  ...
  // Create a UserFileIOAccess object that indicates that you
  // want to ask the user to choose a file to open for reading.

  UserFileIOAccess sreq = new UserFileIOAccess(UserFileIOAccess.READ);

  // Check to see that all of your callers have the rights to
  // initiate user-directed file operations for reading.

  PolicyEngine.checkPermission(sreq);
  ...

For more information about checking file I/O permissions, see the PolicyEngine class and the UserFileIOPermission class.

Constructors

UserFileIOAccess

public UserFileIOAccess(int accessType);

Creates a new UserFileIOAccess object that represents the specified access types.

Parameter | Description
accessType | The requested access type. The value must be READ, WRITE, or READWRITE.

Methods

getAccessFlags

public int getAccessFlags();

Retrieves the access flags represented by the UserFileIOAccess object.

Return Value:

Returns the access flags represented by the UserFileIOAccess object.

getPermissionID

public PermissionID getPermissionID();

Retrieves the permission identifier associated with the UserFileIOAccess object. This method satisfies the ISecurityRequest interface and returns PermissionID.USERFILEIO to indicate that instances of the UserFileIOAccess class are associated with the user-directed file I/O permission.

Return Value:

Returns PermissionID.USERFILEIO.

toString

public String toString ();

Converts the UserFileIOAccess object to its string representation.

Return Value:

Returns the string representation of the UserFileIOAccess object.

validAccessType

public static boolean validAccessType(int acc);

Determines whether the access flags in the specified integer are valid UserFileIOAccess flags.

Return Value:

Returns true if the access type is valid; otherwise, returns false.

Parameter | Description
acc | The access type that is checked for validity.

Fields

READ
The value indicating that a file needs to be opened for reading.
READWRITE
The value indicating that a file needs to be opened for both reading and writing.
WRITE
The value indicating that a file needs to be opened for writing.


Class UserFileIOPermission

public class UserFileIOPermission implements IPermission,
            IEncodablePermission
{
  // Constructors
  public UserFileIOPermission();
  public UserFileIOPermission(int accessType);

  // Methods
  public boolean canRead ();
  public boolean canWrite ();
  public void check(Object request) throws SecurityException;
  public IPermission combine (IPermission source2);
  public int compareSet (Object target);
  public IPermission copy();
  public boolean decode(String tag, InputStream data);
  public boolean encode(String tag, OutputStream out);
  public int getAccessFlags();
  public String mapFormat(String format);
  public void setAccessFlags(int type);
  public String[] supportedFormats();
  public String toString ();
}

This class represents a permission that controls the ability to perform user-directed file I/O operations using the UserFileDialog class.

Also see com.ms.security.permissions.UserFileIOAccess

Constructors

UserFileIOPermission

public UserFileIOPermission();

Creates a new UserFileIOPermission object that represents the specified access types.

UserFileIOPermission

public UserFileIOPermission(int accessType);

Creates a new UserFileIOPermission instance that allows the user to have access to specific types of file I/O.

Parameter | Description
accessType | The access flag. This value must be READ, WRITE, or READWRITE.

Methods

canRead

public boolean canRead ();

Determines whether the object allows user-directed file I/O for reading files.

Return Value:

Returns true if the object has permission to read; otherwise, returns false.

canWrite

public boolean canWrite ();

Determines whether the object allows user-directed file I/O for writing files.

Return Value:

Returns true if the object has permission to write; otherwise, returns false.

check

public void check(Object request) throws SecurityException;

Determines whether the permission object allows the specified user-directed file I/O operation.

Return Value:

No return value.

Parameter | Description
request | The security request parameter. It must be an instance of the UserFileIOAccess class.

Exceptions:

SecurityException if this permission does not allow the specified operation.

combine

public IPermission combine (IPermission source2);

Creates and returns a new UserFileIOPermission object that is a combination of the current permission object and the specified permission object. The new object allows access to exactly those resources allowed by either one of the permission objects that it was constructed from.

Return Value:

Returns the resulting UserFileIOPermission object.

Parameter | Description
source2 | The UserFileIOPermission object to combine with the current one.

Exceptions:

IllegalArgumentException if the specified object to combine with is not an instance of UserFileIOPermission.

compareSet

public int compareSet (Object target);

Compares the UserFileIOPermission instance with a specified permission object.

Return Value:

Returns one of the following constants:

  • DISJOINT
  • EMPTY
  • OVERLAP
  • EQUAL
  • SUBSET
  • SUPERSET
  • EMPTY_SUBSET
  • EMPTY_SUPERSET

Parameter | Description
target | The permission object that the UserFileIOPermission instance is compared with.

copy

public IPermission copy();

Retrieves a copy of the UserFileIOPermission object.

Return Value:

Returns the copy of the UserFileIOPermission object.

decode

public boolean decode(String tag, InputStream data);

Decodes the contents of the specified data stream into this permission object. The tag parameter specifies the type of data in the stream.

Return Value:

Returns true if the decoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
data | The raw data to construct the object from. The type of data is specified by the tag parameter.

encode

public boolean encode(String tag, OutputStream out);

Encodes the contents of this permission object, and sends the encoded data to the specified stream. The tag parameter specifies the type of encoding that should be used.

Return Value:

Returns true if the encoding operation succeeded; otherwise, returns false.

Parameter | Description
tag | The encoding type identifier.
out | The output stream to send the encoded data to.

getAccessFlags

public int getAccessFlags();

Retrieves the access types allowed by the permission object.

Return Value:

Returns the access flag represented by the permission object, which will be READ, WRITE, or READWRITE.

mapFormat

public String mapFormat(String format);

Retrieves a permission-specific tag, given an encoding format. The tag is then used with the encode and decode methods to specify an encoding type.

Return Value:

Returns the permission-specific tag that corresponds to the specified format.

Parameter | Description
format | The encoding format to retrieve the tag for.

setAccessFlags

public void setAccessFlags(int type);

Sets the types of user-directed file I/O access that the permission object should allow.

Return Value:

No return value.

Parameter | Description
type | The access flag. This value must be READ, WRITE, or READWRITE.

supportedFormats

public String[] supportedFormats();

Retrieves the encoding formats that the permission type supports.

Return Value:

Returns an array of the supported format identifiers.

toString

public String toString ();

Retrieves a textual representation of the permission object.

Return Value:

Returns the string representation of the permission object.


About com.ms.security.auditing

Provides an interface that allows an auditor to determine how a security request should be displayed.

Interfaces

Interface ISecurityAuditInfo
This interface provides information to a security auditor about an audited security request.

Hierarchy

ISecurityAuditInfo


Interface ISecurityAuditInfo

public interface ISecurityAuditInfo
{
  // Methods
  String[] getAuditDetails ();
  String getAuditIdentifier ();
}

This interface provides information to a security auditor about an audited security request. It is implemented by request objects that are passed to any of the parameterized security checks of com.ms.security.PolicyEngine. If the system is configured to audit the request, the auditor uses the information from this interface to determine how to display the request.

Methods

getAuditDetails

String[] getAuditDetails ();

Retrieves strings that describe the parameters of the request. If a localized message for the request is available, the retrieved strings will be used to fill in any placeholders in the message.

Return Value:

Returns an array of strings that describe the request. If there are no parameters to describe, this method returns null.

getAuditIdentifier

String getAuditIdentifier ();

Retrieves a string that identifies the type of the audit event.

Return Value:

Returns a string that identifies the audit event.

Remarks:

The string retrieved will have property or package-like conventions. For example, "com.xyz.database.query.invalid" is a valid return string for this method. An auditor could use the returned string to select a localized format string for displaying the event or for determining types of events to log.


About com.ms.service

In this topic

* Overview

* The Jntsvc Tool

* Example

* Classes

* Hierarchy

Packages | Packages | Next
Package com.ms.service | Packages | Next

About com.ms.service

This package enables you to write a Microsoft® Windows NT® system service in Java. (System services do not work under Microsoft® Windows® 95.) For more information about Windows NT system services, refer to the Microsoft® Platform SDK.

Overview

To create and use a Windows NT service using this package, you must perform the following steps:

  • Create your own service class by deriving it from the Service class.
  • Implement either a default constructor with no parameters or a constructor with a single String[] parameter. This constructor will be used to instantiate the service, and it should perform initialization during ServiceMain.
  • Implement your own versions of service callback methods (the methods that start with handle) to handle the various system service requests.
  • Use the query methods (the methods that begin with can) to determine which controls are accepted by a service (instead of testing the flags returned from getControlsAccepted).
  • Use a built-in assassin to terminate a service that exceeds a time-out period specified by the wait hint value in status updates.
  • Use the jntsvc tool to generate a self-contained, self-installing and uninstalling, redistributable executable for the service.

The Microsoft SDK for Java includes several improvements in the com.ms.service package that were not in version 1.5. The following list describes these improvements.

  1. Multiple services can be run within the same process. (Version 1.5 allowed only one service in a process.)
  2. A new tool, jntsvc, generates self-contained executables for ease of distribution. A generated executable can install or uninstall itself by using the /install or /uninstall options. (Version 1.5 required several binaries to be present, along with a separate install program.)
  3. The service can be started in command line mode, which is useful when starting the service from a debugger. (Version 1.5 required developers to define their own entry point to instantiate the service, and they had to invent a way to simulate control events.)
  4. Arguments can optionally be applied to the service.

The Jntsvc Tool

The jntsvc tool generates a service executable. It is similar in usage and purpose to the jexegen tool. The use of the command file and specification of the class files in combination with the /base and /r options are identical to those used with jexegen. The following command line should be used to generate the executable.

  jntsvc /svcmain:classname [/base:dir] [/out:filename] [/r]
     [/r-] [/v] [@commandfile] files

For detailed information on how to generate a service executable using the jntsvc tool, see the jntsvc section of the Tools Quick Reference.

After you have generated the executable, use the following command line to install, uninstall, or run the executable.

  "executable name" [options] [arguments to service]

The following table briefly describes the available options.
/install | Installs the service.
/uninstall | Uninstalls the service.
/cmd:service name Runs service service name in command line mode. This is useful when starting and controlling a service under a debugger. Messages that are normally sent to the event log are sent to the console. Service events can be simulated by entering the following commands in the console window.
STOP | Sends a SERVICE_CONTROL_STOP event to the service.
PAUSE | Sends a SERVICE_CONTROL_PAUSE event to the service.
CONTINUE | Sends a SERVICE_CONTROL_CONTINUE event to the service.
SHUTDOWN | Sends a SERVICE_CONTROL_SHUTDOWN event to the service.
INTERROGATE | Sends a SERVICE_CONTROL_INTERROGATE event to the service.
/username:user name | Specifies the account for the service to run as. The default value is "LocalSystem". This option cannot be specified for multiple-service executables.
/password:password | Specifies the password of the user name.

Important Note: As of version 2.5, the service information is contained within the generated executable. Therefore, the registry keys under HKLM\System\CurrentControlSet\Services that were used for version 1.5 services are no longer recognized. In version 1.5, certain parameter values were specified when the svcsetup was run. However, with version 2.5, to change the values of these parameters you must regenerate the executable. The only exceptions to this rule are the password and the username parameters, which are now options that you can specify on the generated executable.

Example

The following command line generates an executable for the test service included with the SDK for Java.

jntsvc /svcmain:TestService /eventsource:TestService
   /base:c:\..\bin\jntsvc TestService.class

Classes

Class Service
This class is a base class for creating Microsoft® Windows NT® system services in Java.
Class ServiceStatus
This class contains information about the state of a service.

Hierarchy

Object
  |
  +--Service
  |
  +--ServiceStatus (Cloneable)


Class Service

public abstract class Service
{
  // Fields
  public static final int ACCEPT_PAUSE_CONTINUE;
  public static final int ACCEPT_SHUTDOWN;
  public static final int ACCEPT_STOP;
  public static final int CONTINUE_PENDING;
  protected static boolean disableassassin;
  public PrintStream err;
  protected static final int ERROR_SERVICE_SPECIFIC_ERROR;
  protected static final int NO_ERROR;
  public PrintStream out;
  public static final int PAUSE_PENDING;
  public static final int PAUSED;
  public static final int RUNNING;
  public static final int START_PENDING;
  public static final int STOP_PENDING;
  public static final int STOPPED;

  // Constructors
  protected Service( );

  // Methods
  public synchronized boolean canPause( );
  public synchronized boolean canShutdown( );
  public synchronized boolean canStop( );
  protected synchronized void CheckPoint( );
  protected synchronized void CheckPoint( int waithint );
  protected static void disableAllAssassins ();
  protected void disableAssassin( );
  protected static void enableAllAssassins ();
  protected void enableAssassin( );
  protected void getAssassinTimeout( long ms );
  public synchronized int getCheckPoint( );
  public synchronized int getControlsAccepted( );
  public synchronized int getCurrentState( );
  public synchronized final ServiceStatus getServiceStatus( );
  public final ServiceStatus getServiceStatusDirect( );
  public synchronized int getWaitHint( );
  protected boolean handleContinue( );
  protected boolean handleInterrogate( );
  protected boolean handlePause( );
  protected boolean handleShutdown( );
  protected boolean handleStop( );
  protected boolean handleUnrecognizedEvent (int event);
  protected boolean isAssassinActive( );
  protected static void preventAssassins ();
  protected void setAssassinTimeout( long ms );
  public static boolean setAutoDumpErr( boolean autodump );
  public static boolean setAutoDumpOut( boolean autodump );
  protected synchronized void setContinuing( int waithint );
  protected synchronized void setPaused( );
  protected synchronized void setPausing( int waithint );
  protected synchronized void setRunning( int controls );
  protected synchronized void setRunning( );
  public boolean setServiceAutoDumpErr( boolean autodump );
  public boolean setServiceAutoDumpOut( boolean autodump );
  protected synchronized final boolean setServiceStatus (
        ServiceStatus newstatus);
  protected final boolean setServiceStatusDirect(
        ServiceStatus newstatus );
  protected synchronized void setStopped( );
  protected synchronized void setStopping( int waithint );
  protected void StopServiceEventHandler (int waithint);
}

This class is a base class for creating Microsoft® Windows NT® system services in Java.

Caution By default, the service assassin is turned on for services. It must be turned off by using the disableAssassin method. For more information, see the enableAssassin method.

Constructors

Service

protected Service( );

Constructs a new service.

Caution The service being created must send a status update within 30 seconds or disable the assassin; otherwise, the assassin will kill the service.

Methods

canPause

public synchronized boolean canPause( );

Indicates whether the service can be paused.

Return Value:

Returns true if the service can be paused (that is, if getControlsAccepted returns ACCEPT_PAUSE_CONTINUE); otherwise, returns false.

canShutdown

public synchronized boolean canShutdown( );

Indicates whether the service should be notified when the system shuts down.

Return Value:

Returns true if the service can accept shutdown requests (that is, if getControlsAccepted returns ACCEPT_SHUTDOWN); otherwise, returns false.

canStop

public synchronized boolean canStop( );

Indicates whether the service can be stopped.

Return Value:

Returns true if the service can be stopped (that is, if getControlsAccepted returns ACCEPT_STOP); otherwise, returns false.

CheckPoint

protected synchronized void CheckPoint( );

Increments the current checkpoint value.

Return Value:

No return value.

Remarks:

During a pending operation, the service should call the CheckPoint method to indicate that the service has progressed toward changing the state from pending to start, stop, continue, or pause.

CheckPoint

protected synchronized void CheckPoint( int waithint );

Sets the checkpoint to a specified value.

Return Value:

No return value.

Parameter | Description
waithint | The estimated number of milliseconds until the next state.

disableAllAssassins

protected static void disableAllAssassins ();

Disables the assassins for each service in the process.

Return Value:

No return value.

disableAssassin

protected void disableAssassin( );

Disables the service assassin. If the assassin is disabled, the service must always be able to respond to stop and shutdown requests, because a service cannot be shut down through the task manager. If it is unknown whether the service will always be able to do so, it is best advised to leave the assassin enabled. If the assassin is killing the service too soon, use the setAssassinTimeout to set its default timeout.

Return Value:

No return value.

See Also: enableAssassin, isAssassinActive

enableAllAssassins

protected static void enableAllAssassins ();

Restores the assassins for each service in the process to their normal state. This method globally re-enables assassins, regardless of their individual settings.

Return Value:

No return value.

enableAssassin

protected void enableAssassin( );

Enables the assassin. The assassin will observe the state of the service and will terminate it in the following cases:

  • A control request is received and the service does not respond within the default time-out.
  • A call to setServiceStatus changes the state of the service to a state unrelated to a previous state change request. This means that if a stop request is received and the service proceeds to set the state to RUNNING, the service is terminated. However, if the service sets its state to STOPPED or STOP_PENDING, the service will terminate in the first case, or it will re-start its time-out in the second case.
  • A setServiceStatus call changes the state of the service to any PENDING state and the service does not make a setServiceStatus call to the corresponding state within the WaitHint (or if WaitHint is not specified), within the assassin's default time-out.

See Also: disableAssassin, isAssassinActive, setAssassinTimeout, STOPPED, START_PENDING, STOP_PENDING, RUNNING, CONTINUE_PENDING, PAUSE_PENDING, PAUSED

getAssassinTimeout

protected void getAssassinTimeout( long ms );

Obtains the default time for which the assassin will wait for any state change before terminating a service. The time-out initially defaults to 30 seconds.

Return Value:

Returns the time, in milliseconds, that the assassin will wait for a state change before terminating the service.

getCheckPoint

public synchronized int getCheckPoint( );

Determines the service checkpoint.

Return Value:

Returns the current checkpoint value.

getControlsAccepted

public synchronized int getControlsAccepted( );

Indicates the control codes that the service will accept and process.

Return Value:

Returns flags that indicate which controls the service will accept.

getCurrentState

public synchronized int getCurrentState( );

Determines the service state.

Return Value:

Returns the system's current state.

getServiceStatus

public synchronized final ServiceStatus getServiceStatus( );

Determines the service status.

Return Value:

Returns a copy of the service status, which is a ServiceStatus object.

getServiceStatusDirect

public final ServiceStatus getServiceStatusDirect( );

Determines the service status. This operation is not synchronized with other status-changing operations.

Return Value:

Returns a copy of the service status, which is a ServiceStatus object.

getWaitHint

public synchronized int getWaitHint( );

Determines the wait hint.

Return Value:

Returns the service wait hint.

Remarks:

The wait hint value specifies the number of milliseconds the service is likely to remain in the current pending state. If the service exceeds this value, the service will be terminated if the assassin is enabled.

handleContinue

protected boolean handleContinue( );

Handles the continue request.

Return Value:

Returns false.

Remarks:

Override this method in your derived service class if you want your service to handle continue events.

handleInterrogate

protected boolean handleInterrogate( );

Handles the interrogate request.

Return Value:

Returns false.

Remarks:

Override this method in your derived service class if you want your service to handle interrogate events.

handlePause

protected boolean handlePause( );

Handles the pause request.

Return Value:

Returns false.

Remarks:

Override this method in your derived service class if you want your service to handle pause events.

handleShutdown

protected boolean handleShutdown( );

Handles the shutdown request.

Return Value:

Returns false.

Remarks:

Override this method in your derived service class if you want your service to handle shutdown events. By default, this method makes a call to handleStop.

handleStop

protected boolean handleStop( );

Handles the stop request.

Return Value:

Returns false.

Remarks:

Override this method in your derived service class if you want your service to handle stop events. By default, if stop control requests are accepted, it will call the setStopped method and return false.

handleUnrecognizedEvent

protected boolean handleUnrecognizedEvent (int event);

Handles an unrecognized event code from the service control manager. Future versions of Windows NT may define additional events; this method provides a way for services to respond to these events.

Return Value:

Returns false.

isAssassinActive

protected boolean isAssassinActive( );

Indicates whether the assassin is currently active.

Return Value:

Returns true if the assassin is active; otherwise, returns false.

See Also: enableAssassin, disableAssassin

preventAssassins

protected static void preventAssassins ();

Prevents assassins from being created. For this method to be effective, each service should call this method from its static initializer.

Return Value:

No return value.

setAssassinTimeout

protected void setAssassinTimeout( long ms );

Sets the time for which the assassin will wait for any state change before terminating a service.

Return Value:

No return value.

Parameter | Description
ms | The time, in milliseconds, for the assassin to wait for a state change before terminating the service.

setAutoDumpErr

public static boolean setAutoDumpErr( boolean autodump );

Determines whether each line written to System.err is automatically written to the event log or whether the service will manually flush the stream to log events.

Note This method changes the state of System.err if it has not been changed since the first service was instantiated. The status of err, the output stream for each service, can be changed with setServiceAutoDumpErr.

Return Value:

Returns the previous auto-flush state.

Parameter | Description
autodump | Set to true to automatically flush to the Windows NT event log whenever a new line is written. Set to false to enable writing to the error log. In this case, the stream can be manually flushed by calling System.err.flush, which will write any text printed to the stream since the last flush to the event log as a single event.

setAutoDumpOut

public static boolean setAutoDumpOut( boolean autodump );

Determines whether each line written to System.out is automatically written to the event log or whether the service will manually flush the stream to log events.

Note This method changes the state of System.out if it has not been changed since the first service was instantiated. The status of out, the output stream for each service, can be changed by using setServiceAutoDumpOut.

Return Value:

Returns the previous auto-flush state.

Parameter | Description
autodump | Set to true to automatically flush to the Windows NT event log whenever a new line is written. Set to false to enable the writing of multiline error messages to the information log. In this case, the stream can be manually flushed by calling System.out.flush, which will write any text printed to the stream since the last flush to the event log as a single event.

setContinuing

protected synchronized void setContinuing( int waithint );

Sets the service to CONTINUE_PENDING.

Return Value:

No return value.

Parameter | Description
waithint | The estimated number of milliseconds it takes for the service to reach the RUNNING state.

setPaused

protected synchronized void setPaused( );

Sets the service to the PAUSED state.

Return Value:

No return value.

setPausing

protected synchronized void setPausing( int waithint );

Sets the service to PAUSE_PENDING and sets the wait hint to waithint.

Return Value:

No return value.

Parameter | Description
waithint | The estimated number of milliseconds it takes for the service to reach the PAUSED state.

setRunning

protected synchronized void setRunning( int controls );

Sets the service to RUNNING and sets the ControlsAccepted field in the ServiceStatus object to a specified value indicating the control capabilities of the service.

Return Value:

No return value.

Parameter | Description
controls | The control capabilities that ControlsAccepted is set to.

See Also: com.ms.service.ServiceStatus.ControlsAccepted

setRunning

protected synchronized void setRunning( );

Sets the service to RUNNING.

Return Value:

No return value.

setServiceAutoDumpErr

public boolean setServiceAutoDumpErr( boolean autodump );

Determines whether each line written to err is automatically written to the event log or whether the service will manually flush the stream to log events.

Return Value:

Returns the previous auto-flush state.

Parameter | Description
autodump | Set to true to automatically flush to the Windows NT event log whenever a new line is written. Set to false to enable the writing of multiline error messages. In this case, the stream can be manually flushed by calling err.flush, which will write any text printed to the stream since the last flush to the event log as a single event.

setServiceAutoDumpOut

public boolean setServiceAutoDumpOut( boolean autodump );

Determines whether each line written to out is automatically written to the event log or whether the service will manually flush the stream to log events.

Return Value:

Returns the previous auto-flush state.

Parameter | Description
autodump | Set to true to automatically flush to the Windows NT event log whenever a new line is written. Set to false to enable the writing of multiline error messages. In this case, the stream can be manually flushed by calling out.flush, which will write any text printed to the stream since the last flush to the event log as a single event.

setServiceStatus

protected synchronized final boolean setServiceStatus (
        ServiceStatus newstatus);

Changes the value of the service, based on a ServiceStatus object.

Return Value:

Returns true if the status was updated; returns false if the newstatus parameter is not correct or the status could not be updated.

Parameter | Description
newstatus | The value that the service status is set to. The state in newstatus is copied to the current status.

setServiceStatusDirect

protected final boolean setServiceStatusDirect( ServiceStatus newstatus );

Changes the value of the service, based on a ServiceStatus object. This method should be externally synchronized with other status-changing operations, if necessary.

Caution This method is not synchronized with the other status get/set methods. This method provides the service with a direct way to internally update the assassin. It allows the assassin to identify deadlock conditions on internally-initiated state changes. External state changes through Service Control Manager events will always update the assassin. Use getServiceStatusDirect to obtain the status without synchronizing.

Return Value:

Returns true if the status was updated; returns false if the newstatus parameter is not correct or the status could not be updated.

Parameter | Description
newstatus | The value that the service status is set to. The state in newstatus is copied to the current status.

setStopped

protected synchronized void setStopped( );

Sets the service to STOPPED.

Return Value:

No return value.

setStopping

protected synchronized void setStopping( int waithint );

Sets the service to STOP_PENDING and the wait hint to waithint.

Return Value:

No return value.

Parameter | Description
waithint | The estimated number of milliseconds it takes for the service to reach the STOPPED state.

StopServiceEventHandler

protected void StopServiceEventHandler (int waithint);

Internally stops the service. Sets the service to STOPPED. No more control commands will be dispatched after this method is called.

Note This method is provided only for backward compatibility with services developed using SDK 1.5. The preferred way to indicate a stopped service is by using setStopped. Version 1.5 reported a STOP_PENDING status and activated the assassin with the given waithint; a STOPPED status would automatically be reported when all non-daemon threads terminated. Because multiple services are supported, this version simply reports a STOPPED status and does not activate the assassin.

Return Value:

No return value

Parameter | Description
waithint | This parameter is not used.

Fields

ACCEPT_PAUSE_CONTINUE
Indicates that the service accepts pause and continue requests.
ACCEPT_SHUTDOWN
Indicates that the service accepts shutdown requests.
ACCEPT_STOP
Indicates that the service accepts stop requests.
CONTINUE_PENDING
Indicates that the service is changing its state from pause to run.
disableassassin
When true, prevents the assassin from being activated. The assassin ensures that the service actually stops when instructed to do so. This deactivates the assassins for each service in the process.

Note Each service has its own assassin, which can be disabled by calling disableAssassin. All assassins can be globally disabled by calling disableAllAssassins.

err
An error output stream for the service. Data written to the stream is automatically redirected to the event log as error events using the event source specified to jntsvc. Each line printed to the stream results in a new event. Multiple lines can be written by synchronizing on this object and using setServiceAutoDumpErr to temporarily turn off auto-logging, as shown in the following example:

  synchronized (err)
  {
    boolean oldautodump = setServiceAutoDumpErr(false);
    err.println("Line 1");
    err.println("Line 2");
    setServiceAutoDumpErr(oldautodump);
    err.flush();
  }
ERROR_SERVICE_SPECIFIC_ERROR
Service-specific error reported. This is set in ServiceStatus.Win32ExitCode to indicate that an error has occurred.
NO_ERROR
No error reported. This is set in ServiceStatus.Win32ExitCode to indicate that the service terminated correctly.
out
A standard output stream for the service. Data written to the stream is automatically redirected to the event log using the event source specified to the jntsvc tool. Each line printed to the stream results in a new event. Multiple lines can be written by synchronizing on this object and using setServiceAutoDumpOut to temporarily turn off auto-logging, as shown in the following example.

  synchronized (out)
  {
    boolean oldautodump = setServiceAutoDumpOut(false);
    out.println("Line 1");
    out.println("Line 2");
    setServiceAutoDumpOut(oldautodump);
    out.flush();
  }
PAUSE_PENDING
Indicates that the service is changing its state from run to pause.
PAUSED
Indicates that the service is paused.
RUNNING
Indicates that the service is running.
START_PENDING
Indicates that the service is starting.
STOP_PENDING
Indicates that the service is stopping.
STOPPED
Indicates that the service has stopped.


Class ServiceStatus

public final class ServiceStatus implements Cloneable
{
  // Fields
  public int CheckPoint;
  public int ControlsAccepted;
  public int CurrentState;
  public int ServiceSpecificExitCode;
  public int WaitHint;
  public int Win32ExitCode;
}

This class contains information about the state of a service. For more information about this class, see the Microsoft® Win32® SERVICE_STATUS documentation.

Fields

CheckPoint
A value that the service increments periodically to report its progress during a lengthy start, stop, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up. The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, or continue operation pending.
ControlsAccepted
The control codes that the service will accept and process. This can be a combination of ACCEPT_STOP, ACCEPT_PAUSE_CONTINUE, or ACCEPT_SHUTDOWN.
CurrentState
The current state of the service. This can be one of the following values:
Value | Meaning
STOPPED | The service is not running.
START_PENDING | The service is starting.
STOP_PENDING | The service is stopping.
RUNNING | The service is running.
CONTINUE_PENDING | The service continue is pending.
PAUSE_PENDING | The service pause is pending.
PAUSED | The service is paused.
ServiceSpecificExitCode
A service-specific error code that the service returns when an error occurs while the service is starting or stopping. This value is ignored unless the Win32ExitCode field is set to ERROR_SERVICE_SPECIFIC_ERROR.
WaitHint
An estimate of the amount of time, in milliseconds, that the service expects a pending start, stop, or continue operation to take before the service makes its next call to the Service.setServiceStatus method with either an incremented CheckPoint value or a change in CurrentState. If the amount of time specified by WaitHint passes, and CheckPoint has not been incremented or CurrentState has not changed, the service control manager or service control program can assume that an error has occurred.
Win32ExitCode
A Win32 error code that the service uses to report an error that occurs when it is starting or stopping. To return an error code specific to the service, the service must set this value to ERROR_SERVICE_SPECIFIC_ERROR to indicate that the ServiceSpecificExitCode field contains the error code. The service should set this value to NO_ERROR when it is running and on normal termination.


About com.ms.util

This package includes a variety of classes and interfaces for utilities such as version management, sorting, wildcard expression parsing, maintaining integer ranges, event logging, and timer services.

Classes

Class ArraySort
This class sorts an Object array using a Comparison object.
Class EventLog
This class implements an event log.
Class FileVersionInformation
This class creates file version information for a given file.
Class HTMLTokenizer
This class parses an HTML version 3.2 document.
Class IncludeExcludeIntRanges
This class maintains a set of integers specified by a pair of IntRanges objects.
Class IncludeExcludeWildcards
This class maintains a set of strings specified by a pair of WildcardExpression objects.
Class IntRanges
This class maintains a list of integer ranges.
Class MultiComparison
This class provides a comparison based on an array of other comparisons.
Class Queue
This class provides a queue, implemented in an array.
Class SetComparer
This class compares sets that cannot be subtracted or otherwise have no "inverse" operator.
Class Sort
This class implements an abstract sorting engine.
Class StringComparison
This class provides a simple comparison, similar to that done by String.compareTo.
Class SystemVersionManager
This class provides methods that set and retrieve system version properties.
Class Task
This class schedules and manages the execution of runnable objects in the global task manager.
Class TaskManager
This class schedules or manages the execution of runnable objects.
Class ThreadLocalStorage
This class allows applications to store a per-thread reference to a Java object.
Class Timer
This class implements a timer event source.
Class TimerEvent
This class identifies the expiration of a Timer.
Class UnsignedIntRanges
This class shifts unsigned numbers to the range of signed numbers.
Class VectorSort
This class sorts the specified Vector object using the specified Comparison.
Class WildcardExpression
This class matches simple wildcard expressions, such as *.txt or report?.doc commonly recognized by users on most platforms.

Interfaces

Interface Comparison
This interface is designed for implementing comparisons of two objects (usually used in conjunction with a VectorSort or ArraySort object).
Interface IIntRangeComparator
This interface supplies a hook for sorting auxiliary data associated with elements of an IntRanges object.
Interface IWildcardExpressionComparator
This interface is used to compare subexpressions in WildcardExpression.compare.
Interface ProvideSetComparisonInfo
This interface provides set rules for comparisons.
Interface SetComparison
This interface compares two sets.
Interface TimerListener
This interface enables timer event notifications to be received.

Hierarchy

Object
  |
  +--Sort
  |  |
  |  +--ArraySort
  |  |
  |  +--VectorSort
  |
  +--EventLog
  |
  +--HTMLTokenizer
  |
  +--IncludeExcludeIntRanges (SetComparison, ProvideSetComparisonInfo)
  |
  +--IncludeExcludeWildcards (ProvideSetComparisonInfo, SetComparison)
  |
  +--IntRanges (Cloneable, SetComparison)
  |  |
  |  +--UnsignedIntRanges
  |
  +--MultiComparison (Comparison)
  |
  +--Queue (java.util.Enumeration, Cloneable)
  |
  +--SetComparer
  |
  +--StringComparison (Comparison)
  |
  +--SystemVersionManager (Runnable)
  |
  +--Task
  |
  +--TaskManager (Runnable)
  |
  +--ThreadLocalStorage
  |
  +--Timer
  |
  +--TimerEvent
  |
  +--WildcardExpression (java.io.FilenameFilter, Cloneable, SetComparison)

Properties
  |
  +--FileVersionInformation

Comparison
IIntRangeComparator
IWildcardExpressionComparator
ProvideSetComparisonInfo
SetComparison
TimerListener


Class ArraySort

public class ArraySort extends Sort
{
  // Methods
  protected int compare(int p, int q);
  static public void sort(Object array[], Comparison comparison);
  static public void sort(Object array[], Comparison comparison,
        int first, int size);
  protected void swap(int p, int q);
}

This class sorts an Object array using a Comparison object.

Sort
  |
  +--ArraySort

Methods

compare

protected int compare(int p, int q);

Compares two elements in the array using the Comparison object.

Return Value:

Returns the result of the comparison.

Parameter | Description
p | The index of the first operand of the comparison.
q | The index of the second operand of the comparison.

Overrides:

compare(int,int) in Sort.

sort

static public void sort(Object array[], Comparison comparison);

Sorts the specified Object array using a Comparison object.

Return Value:

No return value.

Parameter | Description
array | The Object array to sort.
comparison | The Comparison object to use.

sort

static public void sort(Object array[], Comparison comparison, int first,
        int size);

Sorts a subrange of the specified Object array using a Comparison object.

Return Value:

No return value.

Parameter | Description
array | The Object array to sort.
comparison | The Comparison to use.
first | The beginning element of the subrange.
size | The number of elements in the subrange.

swap

protected void swap(int p, int q);

Swaps two elements in the array.

Return Value:

No return value.

Parameter | Description
p | The index of the first operand of the swap operation.
q | The index of the second operand of the swap operation.

Overrides:

swap(int,int) in Sort.


Class EventLog

public class EventLog
{
  // Fields
  public static final short AUDIT_FAILURE;
  public static final short AUDIT_SUCCESS;
  public static final short ERROR;
  public static final short INFORMATION;
  public static final short SUCCESS;
  public static final short WARNING;

  // Constructors
  public EventLog (String source);
  public EventLog (String server, String source);

  // Methods
  protected void finalize ();
  public void reportEvent (short type, short cat, int id,
        String[] msg, byte[] data);
  public void reportEvent (short type, short cat, int id,
        String msg, byte[] data);
  public void reportEvent (short type, short cat, int id,
        String[] msgs);
  public void reportEvent (short type, short cat, int id,
        String msg);
  public void reportEvent (short type, short cat, int id);
}

This class implements an event log. It is based directly upon the Microsoft® Win32® event log APIs, RegisterEventSource, ReportEvent, and DeregisterEventSource. For more information on implementing and using event logs, see the Win32 documentation.

Constructors

EventLog

public EventLog (String source);

Creates an EventLog object given the name of the source. This constructor calls the Win32 RegisterEventSource API.

Parameter | Description
source | The name of the source referenced by the EventLog object. The source name must be a subkey of a logfile entry under the EventLog key in the registry. Its value can be null.

EventLog

public EventLog (String server, String source);

Creates an EventLog object given the name of the source and the name of the server. This constructor calls the Win32 RegisterEventSource API.

Parameter | Description
server | The Universal Naming Convention (UNC) name of the server that this operation is to be performed on.
source | The name of the source referenced by the EventLog object. The source name must be a subkey of a logfile entry under the EventLog key in the registry. Its value can be null.

Methods

finalize

protected void finalize ();

De-registers the event source when the garbage collector detects there are no more references to this object. This method calls the Win32 DeregisterEventSource function.

Return Value:

No return value.

reportEvent

public void reportEvent (short type, short cat, int id, String[] msg,
        byte[] data);

Writes an entry at the end of the event log, providing associated strings and binary data.

Return Value:

No return value.

Parameter | Description
type The type of event being logged. The parameter can be one of the following types:
  • ERROR
  • WARNING
  • INFORMATION
  • AUDIT_SUCCESS
  • AUDIT_FAILURE
cat | The event category. This is source-specific information; the category can have any value.
id | The event identifier, which specifies the message that goes with this event as an entry in the message file associated with the event source.
msgs | An array of strings that are merged into the message before the message is displayed to the user.
data | The binary data associated with the report.

reportEvent

public void reportEvent (short type, short cat, int id, String msg,
        byte[] data);

Writes an entry at the end of the event log, providing an associated string and binary data.

Return Value:

No return value.

Parameter | Description
type The type of event being logged. The parameter can be one of the following types:
  • ERROR
  • WARNING
  • INFORMATION
  • AUDIT_SUCCESS
  • AUDIT_FAILURE
cat | The event category. This is source-specific information; the category can have any value.
id | The event identifier, specifies the message that goes with this event as an entry in the message file associated with the event source.
msg | A string that is merged into the message before the message is displayed to the user.
data | The binary data associated with the report.

reportEvent

public void reportEvent (short type, short cat, int id, String[] msgs);

Writes an entry at the end of the event log, providing associated strings.

Return Value:

No return value.

Parameter | Description
type The type of event being logged. The parameter can be one of the following types:
  • ERROR
  • WARNING
  • INFORMATION
  • AUDIT_SUCCESS
  • AUDIT_FAILURE
cat | The event category. This is source-specific information; the category can have any value.
id | The event identifier, which specifies the message that goes with this event as an entry in the message file associated with the event source.
msgs | An array of strings that are merged into the message before the message is displayed to the user.

reportEvent

public void reportEvent (short type, short cat, int id, String msg);

Writes an entry at the end of the event log, providing an associated string.

Return Value:

No return value.

Parameter | Description
type The type of event being logged. The parameter can be one of the following types:
  • ERROR
  • WARNING
  • INFORMATION
  • AUDIT_SUCCESS
  • AUDIT_FAILURE
cat | The event category. This is source-specific information; the category can have any value.
id | The event identifier, which specifies the message that goes with this event as an entry in the message file associated with the event source.
msgs | A string that is merged into the message before the message is displayed to the user.

reportEvent

public void reportEvent (short type, short cat, int id);

Writes an entry at the end of the event log.

Return Value:

No return value.

Parameter | Description
type The type of event being logged. The parameter can be one of the following types:
  • ERROR
  • WARNING
  • INFORMATION
  • AUDIT_SUCCESS
  • AUDIT_FAILURE
cat | The event category. This is source-specific information; the category can have any value.
id | The event identifier, which specifies the message that goes with this event as an entry in the message file associated with the event source.

Fields

AUDIT_FAILURE
Indicates a failure audit event.
AUDIT_SUCCESS
Indicates a success audit event.
ERROR
Indicates an error event.
INFORMATION
Indicates an information event.
SUCCESS
Indicates a success event.
WARNING
Indicates a warning event.


Class FileVersionInformation

public class FileVersionInformation extends Properties
{
  // Constructors
  public FileVersionInformation (String filename);
  public FileVersionInformation (File file);
}

This class creates file version information for a given file.

Properties
  |
  +--FileVersionInformation

Constructors

FileVersionInformation

public FileVersionInformation (String filename);

Creates a Properties object that contains file version information.

Parameter | Description
filename | The name of the file to retrieve file version information from. The filename does not need to be absolute.

FileVersionInformation

public FileVersionInformation (File file);

Creates a Properties object that contains file version information.

Parameter | Description
file | The File object that represents the filename.


Class HTMLTokenizer

public class HTMLTokenizer
{
  // Fields
  public Hashtable attrs;
  public String tag;
  public String text;
  public static final int TT_BEGIN_TAG;
  public static final int TT_COMMENT;
  public static final int TT_END_TAG;
  public static final int TT_TEXT;
  public int type;

  // Constructors
  public HTMLTokenizer (InputStream isin);

  // Methods
  public boolean hasMoreTokens ();
  public void mark (int readLimit) throws IOException;
  public int nextToken () throws ParseException, IOException;
  public void reset () throws IOException;
  public String toString ();
}

This class parses an HTML version 3.2 document. The parser does not interpret any HTML tags, except for comments and the <PRE> tag.

Constructors

HTMLTokenizer

public HTMLTokenizer (InputStream isin);

Creates an HTMLTokenizer object when passed to an input stream.

Parameter | Description
isin | The input stream to tokenize.

Methods

hasMoreTokens

public boolean hasMoreTokens ();

Indicates if the HTMLTokenizer object contains more tokens.

Return Value:

Returns true if there are more tokens; otherwise, returns false.

mark

public void mark (int readLimit) throws IOException;

Marks the parser's current position in the input stream.

Return Value:

No return value.

Parameter | Description
readLimit | The number of bytes that can be read before this mark is invalidated.

Exceptions:

IOException if the tokenized input stream cannot set the requested mark.

See Also: java.lang.InputStream.mark

nextToken

public int nextToken () throws ParseException, IOException;

Parses the next token from the input stream. The white space that follows the token and the first character of the next token is consumed.

Return Value:

Returns one the following token types:

  • TT_TEXT
  • TT_BEGIN_TAG
  • TT_END_TAG
  • TT_COMMENT

Exceptions:

NoSuchElementException if a null token is received.

ParseException if no tag is found after a less than (<) symbol or a tag does not have a matching greater than (>) symbol.

reset

public void reset () throws IOException;

Resets the input to the last marked position.

Return Value:

No return value.

Exceptions:

IOException if the tokenized input stream cannot set the requested mark.

See Also: java.lang.InputStream.reset

toString

public String toString ();

Retrieves a string representation of the HTMLTokenizer object.

Return Value:

Returns a string containing the tag types, tags, attributes, and text of the current token in the HTML file.

Fields

attrs
The attributes of a tag. They are valid for these token types: TT_BEGIN_TAG and TT_END_TAG.
tag
The tag.
Comments:
If this is the closing end of a tag, it will not have the leading slash (/) character. This tag is valid for these token types: TT_BEGIN_TAG and TT_END_TAG.
text
Plain text. They are valid for these token types: TT_TEXT and TT_COMMENT.
TT_BEGIN_TAG
A token type representing a beginning tag (for example, <H1>).
TT_COMMENT
A token type representing a comment.
TT_END_TAG
A token type representing an ending tag (for example, </H1>).
TT_TEXT
A token type representing the token text.
type
The last token type read. It can be one of the following:
  • TT_TEXT
  • TT_BEGIN_TAG
  • TT_END_TAG
  • TT_COMMENT


Class IncludeExcludeIntRanges

public class IncludeExcludeIntRanges implements SetComparison,
            ProvideSetComparisonInfo
{
  // Constructors
  public IncludeExcludeIntRanges (IntRanges include,
        IntRanges exclude);
  public IncludeExcludeIntRanges ( );

  // Methods
  public Object combineSetRules (Object o1, Object o2);
  public int compareSet (Object other);
  public int compareSetRules (Object o1, Object o2);
  public boolean contains (int n);
  public void excludeRange (int s, int e);
  public void excludeRanges (IntRanges ranges);
  public IntRanges getExcludedRanges ();
  public IntRanges getIncludedRanges ();
  public Object getSetRule (int rule);
  public String getStringForSetRule (Object o);
  public void includeRange (int s, int e);
  public void includeRanges (IntRanges ranges);
  public Object intersectSetRules (Object o1, Object o2);
  public void invalidate ();
  public boolean isEmptySetRule (Object o);
  public String toString ();
  public void validate ();
}

This class maintains a set of integers specified by a pair of IntRanges objects. The first IntRanges object specifies a set of integers that are included in the set, and the second specifies integers that are excluded from the set.

Constructors

IncludeExcludeIntRanges

public IncludeExcludeIntRanges (IntRanges include, IntRanges exclude);

Constructs a new IncludeExcludeIntRanges object given an IntRanges object matching the included integers and an IntRanges object matching the excluded integers.

Parameter | Description
include | The integers that are included in the set.
exclude | The integers that are excluded from the set.

IncludeExcludeIntRanges

public IncludeExcludeIntRanges ( );

Constructs an empty IncludeExcludeIntRanges object.

Methods

combineSetRules

public Object combineSetRules (Object o1, Object o2);

Combines two set rule objects.

Return Value:

Returns an object containing the combined set rules.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

compareSet

public int compareSet (Object other);

Compares the current IncludeExcludeIntRanges object with another.

Return Value:

Returns a SetComparison.compareSet result code

Parameter | Description
other | The object with which to compare this object.

compareSetRules

public int compareSetRules (Object o1, Object o2);

Compares two objects retrieved from getRule.

Return Value:

Returns a SetComparison.compareSet result code.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

contains

public boolean contains (int n);

Determines if n is a member of the set.

Return Value:

Returns true if n is in the set.

Parameter | Description
n | The integer to test for membership.

excludeRange

public void excludeRange (int s, int e);

Excludes a range of integers in the set.

Return Value:

No return value.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.

excludeRanges

public void excludeRanges (IntRanges ranges);

Excludes a set of integers in the set.

Return Value:

No return value.

Parameter | Description
ranges | An IntRanges object specifying the integers to exclude.

getExcludedRanges

public IntRanges getExcludedRanges ();

Retrieves the set of all excluded ranges.

Return Value:

Returns a set of ranges.

getIncludedRanges

public IntRanges getIncludedRanges ();

Retrieves the set of all included ranges.

Return Value:

Returns a set of ranges.

getSetRule

public Object getSetRule (int rule);

Obtains an object representing the specified rule that can be used internally by SetComparer.

Return Value:

Returns the set rule object.

Parameter | Description
rule | The rule that specifies the object to return.

getStringForSetRule

public String getStringForSetRule (Object o);

Retrieves a String representation of a given set rule.

Return Value:

Returns the set rule String.

Parameter | Description
o | The object containing the set rule.

includeRange

public void includeRange (int s, int e);

Includes a range of integers in the set.

Return Value:

No return value.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.

includeRanges

public void includeRanges (IntRanges ranges);

Includes a set of integers in the set.

Return Value:

No return value.

Parameter | Description
ranges | An IntRanges object specifying the integers to include.

intersectSetRules

public Object intersectSetRules (Object o1, Object o2);

Determines the intersection of two set rule objects.

Return Value:

Returns an object containing the intersection of the set rules.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

invalidate

public void invalidate ();

Ensures that the set is in a valid state.

Remarks:

The set is automatically invalidated when additional expressions are included or excluded, and is automatically validated by other operators when necessary. If the set is already known to be in a valid state, this method does nothing. Validation is relatively expensive, so invoking this method in advance may speed up other operations that require validations.

isEmptySetRule

public boolean isEmptySetRule (Object o);

Determines if the set rule is empty or not.

Return Value:

Returns true if the set rule is empty; otherwise, returns false.

Parameter | Description
o | The object containing the set rule.

toString

public String toString ();

Retrieves a string representation of the object.

Return Value:

Returns a String showing the IntRanges object's included and excluded sets.

validate

public void validate ();

Forces the next operation that requires the set to be valid to validate the set. The set can be manually placed in a valid state by invoking validate.


Class IncludeExcludeWildcards

public class IncludeExcludeWildcards implements
            ProvideSetComparisonInfo, SetComparison
{
  // Constructors
  public IncludeExcludeWildcards (WildcardExpression include,
        WildcardExpression exclude);

  // Methods
  public Object combineSetRules (Object o1, Object o2);
  public int compareSet (Object other);
  public int compareSetRules (Object o1, Object o2);
  public synchronized void exclude (WildcardExpression expr);
  public WildcardExpression getExcludeExpression ();
  public WildcardExpression getIncludeExpression ();
  public Object getSetRule (int rule);
  public String getStringForSetRule (Object o);
  public synchronized void include (WildcardExpression expr);
  public Object intersectSetRules (Object o1, Object o2);
  public synchronized void invalidate ();
  public boolean isEmptySetRule (Object o);
  public boolean match (String s);
  public String toString ();
  public synchronized void validate ();
}

This class maintains a set of strings specified by a pair of WildcardExpression objects. The first expression specifies a set of strings that are included in the set, and the second specifies strings that are excluded from the set. Because WildcardExpressions cannot be subtracted, this class provides a way of emulating subtraction.

Constructors

IncludeExcludeWildcards

public IncludeExcludeWildcards (WildcardExpression include,
        WildcardExpression exclude);

Constructs a new IncludeExcludeWildcards object given a WildcardExpression matching the included strings and a WildcardExpression matching the excluded strings.

Parameter | Description
include | The expression strings that are included in the set.
exclude | The expression strings that are excluded from the set.

Methods

combineSetRules

public Object combineSetRules (Object o1, Object o2);

Combines two set rule objects

Return Value:

Returns an object containing the combined set rules.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

compareSet

public int compareSet (Object other);

Compares this IncludeExcludeWildcards object against another IncludeExcludeWildcards object.

Return Value:

Returns a SetComparison.compareSet result code.

Parameter | Description
other | The object with which to compare this object.

compareSetRules

public int compareSetRules (Object o1, Object o2);

Compares two objects retrieved from getRule.

Return Value:

Returns a SetComparison.compareSet result code.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

exclude

public synchronized void exclude (WildcardExpression expr);

Adds an expression matching the strings that should be excluded in the set.

Return Value:

No return value.

Parameter | Description
expr | A WildcardExpression specifying strings that should be excluded.

getExcludeExpression

public WildcardExpression getExcludeExpression ();

Retrieves the WildcardExpression object that specifies the strings that are excluded from the set.

Return Value:

Returns the WildcardExpression object that specifies the strings that are excluded from the set. If the IncludeExcludeWildcards object was created with a null exclude parameter and the exclude method has not been called, the method returns null.

See Also: exclude

getIncludeExpression

public WildcardExpression getIncludeExpression ();

Retrieves the WildcardExpression object that specifies the strings that are included in the set.

Return Value:

Returns the WildcardExpression object that specifies the strings that are included in the set. If the IncludeExcludeWildcards object was created with a null include parameter and the include method has not been called, the method returns null.

See Also: include

getSetRule

public Object getSetRule (int rule);

Obtains an object representing the specified rule that can be used internally by SetComparer.

Return Value:

Returns the set rule object.

Parameter | Description
rule | The rule that specifies the object to return.

getStringForSetRule

public String getStringForSetRule (Object o);

Retrieves a String representation of a given set rule.

Return Value:

Returns the set rule String.

Parameter | Description
o | The object containing the set rule.

include

public synchronized void include (WildcardExpression expr);

Adds an expression matching the strings that should be included in the set.

Return Value:

No return value.

Parameter | Description
expr | A WildcardExpression specifying strings that should be included.

intersectSetRules

public Object intersectSetRules (Object o1, Object o2);

Determines the intersection of two set rule objects.

Return Value:

Returns an object containing the intersection of the set rules.

Parameter | Description
o1 | The object containing the first set rule.
o2 | The object containing the second set rule.

invalidate

public synchronized void invalidate ();

Forces the next operation that requires the set to be valid to validate the set. The set can be manually placed in a valid state by invoking validate.

isEmptySetRule

public boolean isEmptySetRule (Object o);

Determines if the set rule is empty or not.

Return Value:

Returns true if the set rule is empty; otherwise, returns false.

Parameter | Description
o | The object containing the set rule.

match

public boolean match (String s);

Determines if s is a member of the set.

Return Value:

Returns true if s is in the set.

Parameter | Description
s | The String to test for membership.

toString

public String toString ();

Retrieves a string representation of the IncludeExcludeWildcards object.

Return Value:

Returns a string containing both the include and exclude WildcardExpression objects.

validate

public synchronized void validate ();

Ensures that the set is in a valid state.

Remarks:

The set is automatically invalidated when additional expressions are included or excluded, and is automatically validated by other operators when necessary. If the set is already known to be in a valid state, this method does nothing. Validation is relatively expensive, so invoking this method in advance may speed up other operations that require validations.


Class IntRanges

public class IntRanges implements Cloneable, SetComparison
{
  // Constructors
  public IntRanges ();
  public IntRanges (String str);
  public IntRanges (String str, String delims);

  // Methods
  public synchronized void addRange (int s, int e);
  public synchronized void addRanges (IntRanges r);
  public synchronized void addSingleton (int n);
  public StringBuffer appendToStringBuffer (StringBuffer sb);
  protected Object clone ();
  public int compare (IntRanges other);
  public int compare (IntRanges other, IIntRangeComparator judge);
  public int compareSet (Object other);
  public static String ComparisonResulttoString (int cmp);
  public synchronized void condense (IIntRangeComparator judge);
  public void condense ();
  public boolean contains (int find);
  public synchronized boolean contains (int s, int e);
  public synchronized IntRanges copy ();
  public int getRangeEnd (int idx);
  public synchronized int[] getRanges ();
  public int getRangeStart (int idx);
  public synchronized int indexOf (int find, int fromRange);
  public int indexOf (int find);
  public IntRanges intersect (IntRanges other,
        IIntRangeComparator judge);
  public IntRanges intersect (IntRanges other);
  public static int invertComparisonResult (int cmp);
  public boolean isEmpty ();
  public synchronized boolean lock (Object key);
  public synchronized void parse (String str, String delims);
  public void parse (String str);
  public boolean removeRange (int rs, int re);
  public void removeRange (int i, IIntRangeComparator hook);
  public void removeRange (int i);
  public synchronized boolean removeRange (int s, int e,
        IIntRangeComparator hook);
  public synchronized void removeRanges (int i, int count,
        IIntRangeComparator hook);
  public void removeRanges (int i, int count);
  public boolean removeSingleton (int n);
  public boolean removeSingleton (int n, IIntRangeComparator hook);
  public synchronized void setRanges (int[] array);
  public int size ();
  public synchronized void sort (IIntRangeComparator judge);
  public void sort ();
  public String toString ();
  public synchronized boolean unlock (Object key);
}

This class maintains a list of integer ranges. Readers and writers of this list should be externally synchronized.

Constructors

IntRanges

public IntRanges ();

Constructs an empty set of ranges as an IntArrayOutputStream object.

IntRanges

public IntRanges (String str);

Constructs a set of ranges from the given string.

Parameter | Description
str | A string containing ranges of integers, where the bounds of each range are separated by a dash (-), and separate ranges are delimited by commas. A range of a single integer can be entered by including just the single integer, separated by delimiters. For example: 1-5,9-11,44,13-120.

IntRanges

public IntRanges (String str, String delims);

Constructs a set of ranges from the given string with specified delimiters.

Parameter | Description
str | A string containing ranges of integers, where the bounds of each range are separated by a dash (-). A range of a single integer can be entered by including just the single integer, separated by delimiters.
delims | The character or characters that separate the ranges.

Methods

addRange

public synchronized void addRange (int s, int e);

Adds a range to the IntRange object.

Return Value:

No return value.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.

addRanges

public synchronized void addRanges (IntRanges r);

Adds another set of ranges to this object's set of ranges.

Return Value:

No return value.

Parameter | Description
r | Another IntRanges object to add to this IntRanges object.

addSingleton

public synchronized void addSingleton (int n);

Adds a range of a single integer to the IntRange object.

Parameter | Description
n | The integer range. For example, if n is 43, a range of 43-43 is added.

appendToStringBuffer

public StringBuffer appendToStringBuffer (StringBuffer sb);

Appends a string representation of the integer ranges to a given string buffer. Used by toString.

Return Value:

Returns a string buffer containing the concatenated strings.

Parameter | Description
sb | The string buffer to append the set of integer range pairs to.

clone

protected Object clone ();

Creates a copy of the set of ranges.

Return Value:

Returns an identical object to this object.

compare

public int compare (IntRanges other);

Compares this set of ranges to another.

Return Value:

Returns the following:

OVERLAP
the sets of integers are not equal but have a common set of integers.
DISJOINT
the sets of integers have no integers in common
SUBSET
the second set of integers includes all of the integers in the first set, plus some integers that are not in the first set.
EQUAL
the sets of integers are identical
SUPERSET
the first set of integers includes all of the integers in the second set, plus some integers that are not in the second set.

Parameter | Description
other | The set of ranges to compare with.

compare

public int compare (IntRanges other, IIntRangeComparator judge);

Compares this set of ranges to another.

Return Value:

Returns the following:

OVERLAP
the sets of integers are not equal, but have a common set of integers.
DISJOINT
the sets of integers have no integers in common
SUBSET
the second set of integers includes all of the integers in the first set, plus some integers that are not in the first set.
EQUAL
the sets of integers are identical
SUPERSET
the first set of integers includes all of the integers in the second set, plus some integers that are not in the second set.
EMPTY
both sets of integers are empty.
EMPTY_SUBSET
pairs1 is empty and pairs2 is not empty.
EMPTY_SUPERSET
pairs2 is empty and pairs1 is not empty.

Parameter | Description
other | The set of ranges to compare with.
judge | A helper interface for the comparison.

compareSet

public int compareSet (Object other);

Compares this set of ranges to another.

Return Value:

Returns SetComparison.DISJOINT if other is not an instance of IntRanges, or else a SetComparison.compareSet result:

SetComparison.OVERLAP
The sets of integers are not equal but have a common set of integers.
SetComparison.DISJOINT
The sets of integers have no integers in common.
SetComparison.SUBSET
other includes all the integers in this set, plus some integers that are not in this set.
SetComparison.EQUAL
The sets of integers are identical.
SetComparison.SUPERSET
This set of integers includes all of the integers in other, plus some integers that are not in other.
SetComparison.EMPTY
Both sets of integers are empty.
SetComparison.EMPTY_SUBSET
This set is empty and other is not empty.
SetComparison.EMPTY_SUPERSET
other is empty and this set is not empty.

Parameter | Description
other | The set of ranges to compare with.

ComparisonResulttoString

public static String ComparisonResulttoString (int cmp);

Converts comparison result flags to a string format.

Return Value:

Returns the result string as follows:

  • "empty" (EMPTY)
  • "equal" (EQUAL)
  • "notequal" (DISJOINT)
  • "overlap" (OVERLAP)
  • "inclusive subset" (SUBSET)
  • "inclusive superset" (SUPERSET)
  • "empty subset" (EMPTY_SUBSET)
  • "empty superset" (EMPTY_SUPERSET)

Parameter | Description
cmp | A comparison result from the compare method.

condense

public synchronized void condense (IIntRangeComparator judge);

Merges overlapping ranges. This method assumes the ranges have already been sorted.

Return Value:

No return value.

Parameter | Description
judge | The interface to help compare equal integer ranges while sorting. This parameter value can be null.

condense

public void condense ();

Merges overlapping ranges. This method assumes the ranges have already been sorted.

Return Value:

No return value.

contains

public boolean contains (int find);

Searches from the beginning of a range for a given number.

Return Value:

Returns true if the number was found; otherwise, returns false.

Parameter | Description
find | The number to search for.

contains

public synchronized boolean contains (int s, int e);

Searches from the beginning of a range for a given range of numbers.

Return Value:

Returns true if the entire search range was found; otherwise, returns false.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.

copy

public synchronized IntRanges copy ();

Creates a copy of the set of ranges.

Return Value:

Returns an identical object to this object.

getRangeEnd

public int getRangeEnd (int idx);

Retrieves the end of a range at a specified index.

Return Value:

Returns the last integer of the range pair.

Parameter | Description
idx | The index of the range pair.

getRanges

public synchronized int[] getRanges ();

Retrieves the integer range pairs as an integer array.

Return Value:

Returns the integer ranges.

getRangeStart

public int getRangeStart (int idx);

Retrieves the start of a range at a specified index.

Return Value:

Returns the first integer of the range pair.

Parameter | Description
idx | The index of the range pair.

indexOf

public synchronized int indexOf (int find, int fromRange);

Searches from a starting index for a range pair containing a given a number.

Return Value:

Returns the index of the range pair that includes the number if found; otherwise, returns -1.

Parameter | Description
find | The number to search for.
fromRange | The index of the range pair to start the search from.

indexOf

public int indexOf (int find);

Searches from the beginning for a range pair containing a given number.

Return Value:

Returns the index of the range pair that includes the number (if found); otherwise, returns -1.

Parameter | Description
find | The number to search for.

intersect

public IntRanges intersect (IntRanges other, IIntRangeComparator judge);

Constructs a new IntRanges object with the set of integers that are common to both this object and another object.

Return Value:

Returns an IntRanges object for the intersection of this object and other.

Parameter | Description
other | The other IntRanges object to find an intersection with.
judge | The hook interface to notify using IIntRangeComparator.intersectRanges of intersecting ranges that will be added to the new IntRanges object.

intersect

public IntRanges intersect (IntRanges other);

Constructs a new IntRanges object with the set of integers that are common to both this object and another object.

Return Value:

Returns an IntRanges object for the intersection of this object and other.

Parameter | Description
other | The other IntRanges object to find an intersection with.

invertComparisonResult

public static int invertComparisonResult (int cmp);

Inverts comparison results.

Return Value:

Returns the inverted comparison result.

Parameter Description
cmp Any comparison result of the compare method, which is inverted as follows:
  • SUBSET returns SUPERSET.
  • SUPERSET returns SUBSET.
  • EMPTY_SET returns EMPTY_SUPERSET.
  • EMPTY_SUPERSET returns EMPTY_SUBSET.
  • any other result is not affected and is simply returned. Note that EQUAL and DISJOINT are not inverted by this function.

isEmpty

public boolean isEmpty ();

Determines if the IntRanges object is empty.

Return Value:

Returns true if the object contains no ranges; otherwise, returns false.

lock

public synchronized boolean lock (Object key);

Assigns a key and locks the IntRanges object.

Return Value:

Returns true if successful; returns false if the object is already locked.

Parameter | Description
key | The key object to be used for unlocking the object.

Exceptions:

NullPointerException if the key is null.

parse

public synchronized void parse (String str, String delims);

Parses the ranges in the string, separated with specified delimiters. This method tokenizes using StringTokenizer.

Return Value:

No return value.

Parameter | Description
str | The string to be parsed.
delims | The delimiters.

parse

public void parse (String str);

Parses comma-delimited ranges in the string.

Return Value:

No return value.

Parameter | Description
str | A string containing ranges of integers, where the bounds of each range are separated by a dash (-). A range of a single integer can be entered by including just the single integer, separated by delimiters.

removeRange

public boolean removeRange (int rs, int re);

Removes a range of integers from the IntRange object.

Return Value:

Returns true if any integers in the range were removed; returns false if the set contains no integers in the range.

Parameter | Description
rs | The lower limit of the range.
re | The upper limit of the range.

removeRange

public void removeRange (int i, IIntRangeComparator hook);

Removes a single range specified by index from the IntRange object.

Return Value:

No return value.

Parameter | Description
i | The index of the range to remove.
hook | The interface to notify through IIntRangeComparator.shiftRanges that the ranges were deleted.

removeRange

public void removeRange (int i);

Removes a single range specified by index from the IntRange object.

Return Value:

No return value.

Parameter | Description
i | The index of the range to remove.

removeRange

public synchronized boolean removeRange (int s, int e,
        IIntRangeComparator hook);

Removes a range of integers from the IntRange object.

Return Value:

Returns true if any integers in the range were removed; returns false if the set contains no integers in the range.

Parameter | Description
rs | The lower limit of the range.
re | The upper limit of the range.
hook | The interface to notify through IIntRangeComparator.shiftRanges that the ranges were deleted or IIntRangeComparator.splitRange that a range was split.

removeRanges

public synchronized void removeRanges (int i, int count,
        IIntRangeComparator hook);

Removes ranges specified by index from the IntRange object.

Return Value:

No return value.

Parameter | Description
i | The index of the range to remove.
count | The number ranges to remove.
hook | The interface to notify through IIntRangeComparator.shiftRanges that the ranges were deleted.

removeRanges

public void removeRanges (int i, int count);

Removes ranges specified by index from the IntRange object.

Return Value:

No return value.

Parameter | Description
i | the index of the range to remove.
count | the number ranges to remove.

removeSingleton

public boolean removeSingleton (int n);

Removes a single integer from the IntRange object.

Return Value:

Returns true if the integer was removed returns false if the integer was not found in the set.

Parameter | Description
n | The integer to remove.

removeSingleton

public boolean removeSingleton (int n, IIntRangeComparator hook);

Removes a single integer from the IntRange object.

Return Value:

Returns true if the integer was removed. This method returns false if the integer was not found in the set.

Parameter | Description
n | The integer to remove.
hook | The interface to notify through IIntRangeComparator.shiftRanges that ranges were deleted or IIntRangeComparator.splitRange that a range was split.

setRanges

public synchronized void setRanges (int[] array);

Sets the integer ranges from an existing integer array.

Return Value:

No return value.

Parameter | Description
array | The array of integer ranges. Each range is specified by two adjacent integers in this array.

size

public int size ();

Retrieves the size of the IntRanges object.

Return Value:

Returns the number of elements in the object.

sort

public synchronized void sort (IIntRangeComparator judge);

Sorts the ranges by the first element in each range pair.

Return Value:

No return value.

Parameter | Description
judge | The interface to help compare equal ranges while sorting. This parameter value can be null.

sort

public void sort ();

Sorts the ranges by left endpoints.

Return Value:

No return value.

toString

public String toString ();

Retrieves a string representation of the IntRanges object.

Return Value:

Returns a string containing "{" followed by the set of integer range pairs, followed by "}".

unlock

public synchronized boolean unlock (Object key);

Unlocks the IntRanges using a previously-assigned key.

Return Value:

Returns true if the object is successfully unlocked; otherwise, returns false.

Parameter | Description
key | The key object previously assigned to lock the object.

Exceptions:

NullPointerException if the key is null.


Class MultiComparison

public final class MultiComparison implements Comparison
{
  // Constructors
  public MultiComparison(Comparison comparisons[]);
  public MultiComparison(Comparison comparisonA,
        Comparison comparisonB);

  // Methods
  public int compare(Object p, Object q);
}

This class provides a comparison based on an array of other comparisons. It enables you to specify a group of comparisons to be applied in priority order. The constructor takes an array of Comparison objects. When requested to perform a comparison of two objects through the compare method, the first comparison in the array is applied; if that comparison finds they are equal, the next comparison is called. This continues until either a comparison finds the objects to be different, or all comparisons have been called.

Constructors

MultiComparison

public MultiComparison(Comparison comparisons[]);

Constructs a new MultiComparison object with the specified comparison array.

Parameter | Description
comparisons | An array of Comparison objects.

MultiComparison

public MultiComparison(Comparison comparisonA, Comparison comparisonB);

Constructs a new MultiComparison object with the specified comparisons.

Parameter | Description
comparisonA | The first Comparison object in the comparison array.
comparisonB | The second Comparison object in the comparison array.

Methods

compare

public int compare(Object p, Object q);

Compares the two objects according to the comparison array. The comparison terminates when one of the comparisons in the array determines that the objects are different.

Return Value:

Returns the result of the comparison.

Parameter | Description
p | The first object to compare.
q | The second object to compare.


Class Queue

public class Queue implements java.util.Enumeration, Cloneable
{
  // Constructors
  public Queue ();
  public Queue (int initialcapacity);
  public Queue (int initialcapacity, int growthfactor);

  // Methods
  public synchronized void addElement (Object newelt);
  public int capacity ();
  protected Object clone () throws CloneNotSupportedException;
  public synchronized Queue copy ();
  public synchronized Object elementFromHead (int idx);
  public synchronized Object elementFromTail (int idx);
  public synchronized boolean hasMoreElements ();
  public synchronized Object nextElement ();
  public synchronized Object pop ();
  public synchronized void removeAllElements ();
  public synchronized int setCapacity (int newcapacity);
  public synchronized int size ();
  public String toString ();
}

This class provides a queue, implemented in an array.

Constructors

Queue

public Queue ();

This class constructs a queue with an initial capacity of 32 elements. When the queue is full, its size doubles.

Queue

public Queue (int initialcapacity);

Constructs a queue with the given initial capacity. When the queue is full, the capacity doubles in size.

Parameter | Description
initialcapacity | The size of the queue to construct (the number of elements it will hold).

Queue

public Queue (int initialcapacity, int growthfactor);

Constructs a queue with the given initial capacity and growth factor.

Parameter | Description
initialcapacity | The initial size of the queue.
growthfactor | The factor to grow by when the queue is full. If the growth factor is 1, the queue will drop elements at its head as needed.

Methods

addElement

public synchronized void addElement (Object newelt);

Adds an element to the tail of the queue.

Return Value:

No return value.

Parameter | Description
newelt | The new element to add to the queue.

Remarks:

The queue will grow, as necessary, by the factor provided when the queue was constructed. Null is a valid element to add.

capacity

public int capacity ();

Obtains the maximum number of objects that the queue can contain without resizing.

Return Value:

Returns the maximum capacity (in objects) of the queue.

clone

protected Object clone () throws CloneNotSupportedException;

Creates a copy of the object.

Return Value:

Returns a copy of the Queue object.

Exceptions:

CloneNotSupportedException if the object cannot be copied.

copy

public synchronized Queue copy ();

Duplicates the queue.

Return Value:

Returns a copy of the Queue object.

elementFromHead

public synchronized Object elementFromHead (int idx);

Retrieves an element relative to the head of the queue.

Return Value:

Returns the requested object.

Parameter | Description
idx | The offset from the first item in the queue.

elementFromTail

public synchronized Object elementFromTail (int idx);

Retrieves an element relative to the tail of the queue.

Return Value:

Returns the requested object.

Parameter | Description
idx | The offset from the last item in the queue.

hasMoreElements

public synchronized boolean hasMoreElements ();

Determines if the queue is empty.

Return Value:

Returns true if there are more elements in the queue; otherwise, returns false.

nextElement

public synchronized Object nextElement ();

Removes an object from the head of the queue.

Return Value:

Returns true if the object was successfully removed; otherwise, returns false.

Exceptions:

NoSuchElementException if the queue is empty.

pop

public synchronized Object pop ();

Retrieves the element last added to the queue.

Return Value:

Returns the requested object.

removeAllElements

public synchronized void removeAllElements ();

Empties the queue.

Return Value:

No return value.

setCapacity

public synchronized int setCapacity (int newcapacity);

Changes the queue's capacity.

Return Value:

Returns the actual final capacity assigned to the queue.

Parameter | Description
newcapacity | The new number of elements in the queue.

size

public synchronized int size ();

Obtains the number of elements in the queue.

Return Value:

Returns the size of the queue (in elements).

toString

public String toString ();

Retrieves a string representation of the Queue object.

Return Value:

Returns a string.


Class SetComparer

public final class SetComparer
{
  // Methods
  public static int compareSets (ProvideSetComparisonInfo set1,
        ProvideSetComparisonInfo set2);
}

This class compares sets that cannot be subtracted or otherwise have no "inverse" operator. The pseudo-set implements ProvideSetComparisonInfo and consists of two sets that together dictate membership.

The include set defines an enclosing set for all possible members of the set, and the exclude set defines members of the enclosing set that are removed.

Three basic operations are supported on the two sets using this class.

  • intersection: Produces a set with only the common members of two sets.
  • union: Produces a set with all the members of two sets.
  • comparison: Compares two sets and returns a SetComparison result.

The compareSets operator method makes the assumption that the union is relatively inexpensive to compute and intersection is relatively expensive. The include set is assumed to be an inclusive superset of the exclude set (otherwise, incorrect results might be returned). Because comparison is typically expensive, this invariant is not checked.

Methods

compareSets

public static int compareSets (ProvideSetComparisonInfo set1,
        ProvideSetComparisonInfo set2);

Compares two set rules.

Return Value:

Returns a SetComparison.compareSet return code.

Parameter | Description
set1 | A set rule.
set2 | A set rule.


Class Sort

public abstract class Sort
{
  // Constructors
  protected Sort();
  protected void doSort(int lo, int size);

  // Methods
  protected int compare(int p, int q);
  protected void swap(int p, int q);
}

This class implements an abstract sorting engine. The Sort class is a base class for implementing container-specific sorts. For examples of subclasses of Sort, see com.ms.util.VectorSort or com.ms.util.ArraySort.

Constructors

Sort

protected Sort();

Constructs an instance of Sort.

doSort

protected void doSort(int lo, int size);

Sorts a range of elements.

Return Value:

No return value.

Parameter | Description
lo | The index of the first element to be sorted.
size | The number of elements to be sorted.

Methods

compare

protected int compare(int p, int q);

Called when the sorting engine must compare two elements. Subclasses override this method in a container-specific manner.

Return Value:

Returns an integer describing the relationship of the elements.

If Sort returns less than 0, place element p before element q in the sort.

If Sort returns greater than 0, place element p after element q.

If Sort returns 0, elements p and q are equivalent.

Parameter | Description
p | The index of the first operand of the comparison.
q | The index of the second operand of the comparison.

swap

protected void swap(int p, int q);

Called when the sorting engine must swap two elements. Subclasses override this method in a container-specific manner.

Return Value:

No return value.

Parameter | Description
p | The index of the first operand of the swap operation.
q | The index of the second operand of the swap operation.


Class StringComparison

public final class StringComparison implements Comparison
{
  // Constructors
  public static final Comparison ascending = new StringComparison(
        1);
  public static final Comparison descending = new StringComparison(
        -1);

  // Methods
  public int compare(Object p, Object q);
}

This class provides a simple comparison, similar to that done by String.compareTo.

For example, given an array of strings like the following:

  String strings[] = new String[4];
  strings[0]="my";
  strings[1]="dog";
  strings[2]="has";
  strings[3]="fleas";

A sort could be performed with the following code:

ArraySort.sort(strings, StringComparison.ascending);

Constructors

StringComparison

public static final Comparison ascending = new StringComparison(1);

Specifies an ascending string comparison. This compares according to String.compareTo.

StringComparison

public static final Comparison descending = new StringComparison(-1);

Specifies a descending string comparison. This compares according to the inverse of String.compareTo.

Methods

compare

public int compare(Object p, Object q);

Compares the two objects.

Return Value:

Returns the result of the comparison.

Parameter | Description
p | The first operand of the comparison.
q | The second operand of the comparison.

Remarks:

If both objects are instances of the String class, String.compareTo is called. If neither object is a String object, zero is returned. If one of the objects is a String, it is treated as lexicographically preceding the non-String object.


Class SystemVersionManager

public class SystemVersionManager implements Runnable
{
  // Methods
  public static Properties createVersion (int major, int minor, int
        buildnum, int buildinc, String description);
  public static Enumeration enumerate ();
  public static Properties getPackageVersion (String pkgname);
  public static Properties getSystemComponentVersion (
        String compname);
  public static Properties getVMVersion ();
  public void run ();
}

This class provides methods that set and retrieve system version properties. Typically, this class is not called directly. Rather, it is used by implementing a VersionManager class that is derived from it. For a standard implementation of a VersionManager class, refer to the Samples\Version directory in the Microsoft SDK for Java. This class can be added, without editing, directly to your distributed packages. In doing so, applications can check the version information of the system components and your distributed classes. The VersionManager sample class works on any virtual machine, but the SystemVersionManager class is provided specifically for use with the Microsoft Win32 VM for Java.

When VersionManager methods are called, the VersionManager object first calls the SystemVersionManager methods to return system information. If the SystemVersionManager class returns nothing or does not exist, and the applet or application runs on the Microsoft VM, the sample implementation of the VersionManager class returns the information for the 3.0 release of Internet Explorer (since Internet Explorer 3.0 was the only version not to include SystemVersionManager). The package information retrieved by the VersionManager works in any virtual machine. The system information, of course, only works on the Microsoft VM.

You can request a package by name by using the getPackageVersion method. This method searches for the information in a Version (*.Version) class in the requested package or a superpackage. The version information is in a Properties object. All version objects have the following keys:

  • MajorVersion
  • MinorVersion
  • BuildNumber
  • BuildIncrement
  • Description

All values are stored as instances of Strings. You can also use getSystemComponentVersion to request information about the following system components:

  • VM
  • Classes
  • TrustedClasses

The following is an example of using the VersionManager class to retrieve the version of the Microsoft Virtual Machine for Java:

// vmver.java

import java.util.Properties;
import java.util.Enumeration;

public class vmver
{
    public static void main (String[] args)
    {
        try
        {
            Properties props = VersionManager.getSystemComponentVersion("VM");
            if (props == null)
            {
                System.out.println("Not a Microsoft VM.");
            }
            else
            {
                Enumeration e = props.keys();
                while (e.hasMoreElements())
                {
                    String prop = (String)e.nextElement();
                    System.out.println(prop+": "+props.get(prop));
                }
            }
        }
        catch (Throwable e)
        {
            System.out.println("unexpected error:");
            e.printStackTrace();
        }
    }
}

Methods

createVersion

public static Properties createVersion (int major, int minor, int buildnum,
        int buildinc, String description);

Creates a version object.

Return Value:

Returns a Property object that contains the version properties.

Parameter | Description
major | The major version number.
minor | The minor version number.
buildnum | The build number.
buildinc | The incremental build number.
description | The string description of the version.

Remarks:

A typical example of this method is the following internal call to createVersion, which creates a version object for system classes before incremental build 1155.

createVersion(4, 79, 0, 1154, "Microsoft(R) System
Classes, 3.0 Prerelease")

enumerate

public static Enumeration enumerate ();

Retrieves the default system components that are provided with the version information.

Return Value:

Returns an Enumeration object that contains the following String objects:

String
Description
VM
The VM version
Classes
The version of the system classes
TrustedClasses
The version of the classes in the TrustedLib path

getPackageVersion

public static Properties getPackageVersion (String pkgname);

Retrieves the version information for the specified package.

Return Value:

Returns a Properties object that contains the package version data.

Parameter | Description
pkgname | The name of the package.

getSystemComponentVersion

public static Properties getSystemComponentVersion (String compname);

Retrieves the component version information.

Return Value:

Returns a Properties object that contains the version information.

Parameter | Description
compname | The system component name, which can be one of the components returned by the enumerate method.

getVMVersion

public static Properties getVMVersion ();

Retrieves version data for the virtual machine (VM).

Return Value:

Returns a Properties object that contains the VM version data.

run

public void run ();

Runs when the thread originating in SystemVersionManager getSystemComponentVersion is started.

Return Value:

No return value.

Remarks:

This method retrieves the value of the ClassesBuild string in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Java VM registry key.


Class Task

public class Task
{
  // Methods
  public static boolean cancel(int id);
  public static int schedule(Runnable runnable);
  public static int schedule(Runnable runnable, long when);
  public static int schedule(Runnable runnable, long when,
        boolean lightweight);
}

This class schedules and manages the execution of runnable objects in the global task manager.

Methods

cancel

public static boolean cancel(int id);

Cancels a pending runnable object.

Return Value:

Returns true if the runnable object was cancelled successfully; returns false if the task was already run or had never been scheduled.

Parameter | Description
id | An integer that identifies the task.

schedule

public static int schedule(Runnable runnable);

Schedules a runnable object to run immediately in the global task manager as a lightweight task.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object scheduled to run.

schedule

public static int schedule(Runnable runnable, long when);

Schedules a runnable object to run in the global task manager at the specified time as a lightweight task.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object that is run.
when | The time at which the object is run.

schedule

public static int schedule(Runnable runnable, long when,
        boolean lightweight);

Schedules a runnable object to run in the global task manager at the specified time and optionally as a lightweight task or not.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object that runs.
when | The time at which the object runs.
lightweight | Set to true to run the task as a lightweight task; false, otherwise.


Class TaskManager

public class TaskManager implements Runnable
{
  // Constructors
  public TaskManager(ThreadGroup threadGroup);
  public TaskManager(ThreadGroup threadGroup,
        boolean runTasksAsDaemons);

  // Methods
  public synchronized boolean cancel(int id);
  public static TaskManager global();
  public void run();
  public int schedule(Runnable runnable);
  public int schedule(Runnable runnable, long when);
  public synchronized int schedule(Runnable runnable, long when,
        boolean lightweight);
}

This class schedules or manages the execution of runnable objects.

Constructors

TaskManager

public TaskManager(ThreadGroup threadGroup);

Constructs a new TaskManager object.

Parameter | Description
threadGroup | The thread group that the task manager creates threads in.

TaskManager

public TaskManager(ThreadGroup threadGroup, boolean runTasksAsDaemons);

Constructs a new TaskManager object.

Parameter | Description
threadGroup | The thread group that the task manager creates threads in.
runTasksAsDaemons | Set to true if the tasks in this task manager are to run on daemon threads; otherwise, set to false.

Methods

cancel

public synchronized boolean cancel(int id);

Cancels a pending runnable object.

Return Value:

Returns true if the runnable object was cancelled successfully; returns false if the task was already run or had never been scheduled.

Parameter | Description
id | An integer that identifies the task.

global

public static TaskManager global();

Retrieves the global task manager.

Return Value:

Returns the global TaskManager object.

run

public void run();

Called when the thread is started.

Return Value:

No return value.

schedule

public int schedule(Runnable runnable);

Schedules a runnable object to run immediately.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object that is run.

schedule

public int schedule(Runnable runnable, long when);

Schedules a runnable object to run at a specified time.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object that is run.
long | The time at which the object is to start.

schedule

public synchronized int schedule(Runnable runnable, long when,
        boolean lightweight);

Schedules a runnable object to run at a specified time.

Return Value:

Returns a non-zero integer that identifies the task.

Parameter | Description
runnable | The object that is run.
when | The time at which the object is run.
lightweight | Set to true to run the task as a lightweight task.


Class ThreadLocalStorage

public class ThreadLocalStorage
{
  // Constructors
  public ThreadLocalStorage();

  // Methods
  protected void finalize();
  public Object get();
  public void release();
  public void set(Object obj);
}

This class allows applications to store a per-thread reference to a Java object.

Constructors

ThreadLocalStorage

public ThreadLocalStorage();

Creates a new per-thread storage object for application use.

Methods

finalize

protected void finalize();

Performs cleanup tasks before garbage collection.

Return Value:

No return value

get

public Object get();

Retrieves the per-thread object stored in this storage object.

Return Value:

Returns the per-thread object stored in this storage object.

release

public void release();

Destroys the storage object. The finalize method will perform this task for you, but because storage objects are scarce resources, you should use this method to release them in a timely manner.

Return Value:

No return value.

set

public void set(Object obj);

Stores a specified per-thread object in the storage object.

Return Value:

No return value.

Parameter | Description
obj | The new object to store.


Class Timer

public class Timer
{
  // Constructors
  public Timer(long p);
  public Timer(long p, int id);
  public Timer(long p, boolean r);
  public Timer(long p, int id, boolean r);
  public Timer(TimerListener defaultListener, long p);
  public Timer(TimerListener defaultListener, long p, int id);
  public Timer(TimerListener defaultListener, long p, boolean r);
  public Timer(TimerListener defaultListener, long p, int id,
        boolean r);
  public Timer(TaskManager tm, long p);
  public Timer(TaskManager tm, long p, int id);
  public Timer(TaskManager tm, long p, boolean r);
  public Timer(TaskManager tm, long p, int id, boolean r);
  public Timer(TaskManager tm, TimerListener defaultListener,
        long p);
  public Timer(TaskManager tm, TimerListener defaultListener,
        long p, int id);
  public Timer(TaskManager tm, TimerListener defaultListener,
        long p, boolean r);
  public Timer(TaskManager tm, TimerListener defaultListener,
        long p, int id, boolean r);

  // Methods
  public void addTimerListener(TimerListener listener);
  public long getPeriod();
  public boolean getRepeat();
  public int getUserID();
  public boolean isRunning();
  public void removeTimerListener(TimerListener listener);
  public void start();
  public void stop();
}

This class implements a timer event source.

Constructors

Timer

public Timer(long p);

Constructs a one-shot timer with the specified period (in milliseconds).

Parameter | Description
p | The initial period of the timer.

Timer

public Timer(long p, int id);

Constructs a one-shot timer with a specific period (in milliseconds) and that includes a user-defined identifier.

Parameter | Description
p | The initial period of the timer.
id | The user-defined identifier of the timer.

Timer

public Timer(long p, boolean r);

Constructs a one-shot or repeating timer with the specified period (in milliseconds).

Parameter | Description
p | The initial period of the timer.
r | Set to true if the timer is a repeating timer or false if it is a one-shot timer.

Timer

public Timer(long p, int id, boolean r);

Constructs a one-shot or repeating timer with the specified period (in milliseconds).

Parameter | Description
p | The initial period of the timer.
id | The user-defined identifier for the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Timer

public Timer(TimerListener defaultListener, long p);

Constructs a one-shot timer with the specified period (in milliseconds) and that includes a default listener.

Parameter | Description
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.

Timer

public Timer(TimerListener defaultListener, long p, int id);

Constructs a one-shot timer with the specified period (in milliseconds) and listener.

Parameter | Description
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.
id | The user-defined identifier of the timer.

Timer

public Timer(TimerListener defaultListener, long p, boolean r);

Constructs a one-shot or repeating timer with the specified period (in milliseconds) and that includes a default listener.

Parameter | Description
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Timer

public Timer(TimerListener defaultListener, long p, int id, boolean r);

Constructs a one-shot or repeating timer with the specified period (in milliseconds) and a default listener.

Parameter | Description
defaultListener | An initial listener to add to the timer.
id | A user-defined identifier for the listener.
p | The initial period of the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Timer

public Timer(TaskManager tm, long p);

Constructs a one-shot timer with the specified period.

Parameter | Description
tm | The TaskManager that is to service this Timer.
p | The initial period of the timer (in milliseconds).

Timer

public Timer(TaskManager tm, long p, int id);

Constructs a one-shot timer with a specific period and that includes a user-defined identifier.

Parameter | Description
tm | The TaskManager that is to service this Timer.
p | The initial period of the timer (in milliseconds).
id | The user-defined identifier of the timer.

Timer

public Timer(TaskManager tm, long p, boolean r);

Constructs a one-shot or repeating timer with the specified period.

Parameter | Description
tm | The task manager that is to service this timer.
p | The initial period of the timer (in milliseconds).
r | Set to true if the timer is a repeating timer or false if it is a one-shot timer.

Timer

public Timer(TaskManager tm, long p, int id, boolean r);

Constructs a one-shot or repeating timer with the specified period.

Parameter | Description
tm | The task manager that is to service this timer.
p | The initial period of the timer (in milliseconds).
id | The user-defined identifier for the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Timer

public Timer(TaskManager tm, TimerListener defaultListener, long p);

Constructs a one-shot timer with the specified period and that includes a default listener.

Parameter | Description
tm | The task manager that is to service this timer.
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.

Timer

public Timer(TaskManager tm, TimerListener defaultListener, long p, int id);

Constructs a one-shot timer with the specified period and listener.

Parameter | Description
tm | The task manager that is to service this timer.
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.
id | The user-defined identifier of the timer.

Timer

public Timer(TaskManager tm, TimerListener defaultListener, long p, boolean
        r);

Constructs a one-shot or repeating timer with the specified period and that includes a default listener.

Parameter | Description
tm | The task manager that is to service this timer.
defaultListener | The initial listener to add to the timer.
p | The initial period of the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Timer

public Timer(TaskManager tm, TimerListener defaultListener, long p, int id,
        boolean r);

Constructs a one-shot or repeating timer with the specified period and a default listener.

Parameter | Description
tm | The task manager that is to service this timer.
defaultListener | An initial listener to add to the timer.
id | A user-defined identifier for the listener.
p | The initial period of the timer.
r | Set to true if the timer is a repeating timer; set to false if it is a one-shot timer.

Methods

addTimerListener

public void addTimerListener(TimerListener listener);

Adds a listener to the timer.

Return Value:

No return value.

Parameter | Description
listener | The listener that is added to the timer.

getPeriod

public long getPeriod();

Retrieves the timer period.

Return Value:

Returns the number of milliseconds that must elapse before the timer fires.

getRepeat

public boolean getRepeat();

Retrieves the timer repeat flag.

Return Value:

Returns true if the timer is a repeating timer; otherwise, returns false.

getUserID

public int getUserID();

Retrieves the timer's user-defined identifier.

Return Value:

Returns the integer identifier of the timer.

isRunning

public boolean isRunning();

Queries the Timer to see if it is running.

Return Value:

Returns true if the timer is running; otherwise, returns false.

removeTimerListener

public void removeTimerListener(TimerListener listener);

Removes a listener from the timer.

Return Value:

No return value.

Parameter | Description
listener | The listener that is removed.

Remarks:

This method prevents future listener timer events from being generated. However, timer events that have already been generated can be delivered to listeners.

start

public void start();

Starts the timer. If the timer is already running, calls to this method are ignored.

Return Value:

No return value.

stop

public void stop();

Stops the timer. If the timer is not running, calls to this method are ignored.

Return Value:

No return value.

Remarks:

This method prevents future listener timer events from being generated. However, timer events that have already been generated can be delivered to listeners.


Class TimerEvent

public class TimerEvent
{
  // Methods
  public Object getSource();
  public long getTime();
  public int getUserID();
  public String toString();
}

This class identifies the expiration of a Timer.

Methods

getSource

public Object getSource();

Retrieves the event source.

Return Value:

Returns the source object for the event.

getTime

public long getTime();

Retrieves the time at which the timer expires.

Return Value:

Returns the time at which the timer expires.

getUserID

public int getUserID();

Retrieves the timer's user-defined identifier.

Return Value:

Returns the integer identifier of the timer.

toString

public String toString();

Retrieves a string object that describes the timer event.

Return Value:

Returns a string object that describes the timer event.


Class UnsignedIntRanges

public class UnsignedIntRanges extends IntRanges
{
  // Constructors
  public UnsignedIntRanges ();
  public UnsignedIntRanges (String str);
  public UnsignedIntRanges (String str, String delims);

  // Methods
  public synchronized void addRange (int s, int e);
  public synchronized void addRanges (IntRanges r);
  public synchronized void addSingleton (int n);
  public StringBuffer appendToStringBuffer (StringBuffer sb);
  public boolean contains (int find);
  public int getRangeEnd (int idx);
  public int getRangeStart (int idx);
  public int indexOf (int find, int fromRange);
  public int indexOf (int find);
  public UnsignedIntRanges intersect (UnsignedIntRanges other,
        IIntRangeComparator judge);
  public IntRanges intersect (IntRanges other, IIntRangeComparator judge);
  public UnsignedIntRanges intersect (UnsignedIntRanges other);
  public boolean removeRange (int s, int e,
        IIntRangeComparator hook);
}

This class shifts unsigned numbers to the range of signed numbers. Those familiar with the IntRanges class should be aware that IntRanges.getRanges and IntRanges.setRanges are not converted by this derived class.

IntRanges
  |
  +--UnsignedIntRanges

Constructors

UnsignedIntRanges

public UnsignedIntRanges ();

Creates an UnsignedIntRanges object.

UnsignedIntRanges

public UnsignedIntRanges (String str);

Constructs a set of ranges from the given string. This method simply calls the superclass.

Parameter Description
str A string containing ranges of unsigned integers (in hexadecimal), where the bounds of each range are separated by a dash (-), and separate ranges are delimited by commas.

A range of a single unsigned integer can be entered by including just the single unsigned integer, separated by delimiters.

UnsignedIntRanges

public UnsignedIntRanges (String str, String delims);

Constructs a set of ranges from the given string with specified delimiters. This method simply calls the superclass.

Parameter | Description
str A string containing ranges of unsigned integers (in hexadecimal), where the bounds of each range are separated by a dash (-).

A range of a single unsigned integer can be entered by including just the single unsigned integer, separated by delimiters.

delims | The character or characters separating ranges.

Methods

addRange

public synchronized void addRange (int s, int e);

Adds a range of unsigned integers to the UnsignedIntRanges object.

Return Value:

No return value.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.

Overrides:

addRange(int,int) in IntRanges.

addRanges

public synchronized void addRanges (IntRanges r);

Adds a set of ranges to this set of ranges.

Return Value:

No return value.

Parameter | Description
r | An IntRanges object to add to this UnsignedIntRanges object.

Overrides:

addRanges(IntRanges) in IntRanges.

addSingleton

public synchronized void addSingleton (int n);

Adds a range of a single, unsigned integer to the UnsignedIntRanges object.

Return Value:

No return value.

Parameter | Description
n | The integer range.

Overrides:

addSingleton(int) in IntRanges.

appendToStringBuffer

public StringBuffer appendToStringBuffer (StringBuffer sb);

Appends a string representation of the unsigned integer ranges to a given string buffer. The unsigned integers are represented in hexadecimal.

Return Value:

Returns a string buffer containing the concatenated strings.

Parameter | Description
sb | The StringBuffer to append the set of unsigned integer range pairs to.

Overrides:

appendToStringBuffer(StringBuffer) in IntRanges.

contains

public boolean contains (int find);

Searches from the beginning for a given number.

Return Value:

Returns true if the number was found; otherwise, returns false.

Parameter | Description
find | The number to search for.

Overrides:

contains(int) in IntRanges.

getRangeEnd

public int getRangeEnd (int idx);

Retrieves the end of a range at a specified index.

Return Value:

Returns the last integer of the range pair.

Parameter | Description
idx | The index of the range pair.

Overrides:

getRangeEnd(int) in IntRanges.

getRangeStart

public int getRangeStart (int idx);

Retrieves the start of a range at a specified index.

Return Value:

Returns the first integer of the range pair.

Parameter | Description
idx | The index of the range pair.

Overrides:

getRangeStart(int) in IntRanges.

indexOf

public int indexOf (int find, int fromRange);

Searches from a starting index for a range pair containing a given a number.

Return Value:

Returns the index of the range pair that includes the number, if found; otherwise, returns -1.

Parameter | Description
find | The number to search for.
fromRange | The index of the range pair to start the search from.

Overrides:

indexOf(int,int) in IntRanges.

indexOf

public int indexOf (int find);

Searches from the beginning for a range pair containing a given a number.

Return Value:

Returns the index of the range pair that includes the number, if found; otherwise, returns -1.

Parameter | Description
find | The number to search for.

Overrides:

indexOf(int) in IntRanges.

intersect

public UnsignedIntRanges intersect (UnsignedIntRanges other,
        IIntRangeComparator judge);

Constructs a new UnsignedIntRanges object with the set of unsigned integers that are common to both this object and another object.

Return Value:

Returns an UnsignedIntRanges object for the intersection of this object and other.

Parameter | Description
other | The other UnsignedIntRanges object to find an intersection with.
judge | The hook interface to notify through IIntRangeComparator.intersectRanges of intersecting ranges that will be added to the new UnsignedIntRanges object.

intersect

public IntRanges intersect (IntRanges other, IIntRangeComparator judge);

Constructs a new IntRanges object with the set of integers that are common to both this object and another object.

Return Value:

Returns an IntRanges object for the intersection of this object and the IntRanges object contained in the other parameter.

Parameter | Description
other | The other IntRanges object to find an intersection with.
judge | The hook interface to notify through IIntRangeComparator.intersectRanges of intersecting ranges that will be added to the new IntRanges object.

intersect

public UnsignedIntRanges intersect (UnsignedIntRanges other);

Retrieves the intersection of this set of unsigned integer ranges with another.

Return Value:

Returns the intersection as a set of unsigned integer ranges.

Parameter | Description
other | The set of unsigned integer ranges to compare.

removeRange

public boolean removeRange (int s, int e, IIntRangeComparator hook);

Removes a range of integers from the UnsignedIntRanges object.

Return Value:

Returns true if any integers in the range were removed; otherwise false if the set contains no integers in the range.

Parameter | Description
s | The lower limit of the range.
e | The upper limit of the range.
hook | The interface to notify through IIntRangeComparator.shiftRanges that the ranges were deleted or IIntRangeComparator.splitRange that a range was split.


Class VectorSort

public class VectorSort extends Sort
{
  // Methods
  protected int compare(int p, int q);
  static public void sort(Vector vector, Comparison comparison);
  static public void sort(Vector vector, Comparison comparison, int
        first, int size);
  protected void swap(int p, int q);
}

This class sorts the specified Vector object using the specified Comparison.

Sort
  |
  +--VectorSort

Methods

compare

protected int compare(int p, int q);

Compares two elements in the vector using the Comparison object.

Return Value:

Returns the result of the comparison.

Parameter | Description
p | The index of the first operand of the comparison.
q | The index of the second operand of the comparison.

Overrides:

compare(int,int) in Sort.

sort

static public void sort(Vector vector, Comparison comparison);

Sorts the specified Vector object using the specified Comparison object.

Return Value:

No return value.

Parameter | Description
vector | The Vector object to be sorted.
comparison | The Comparison object to use.

sort

static public void sort(Vector vector, Comparison comparison, int first,
        int size);

Sorts a subrange of the specified Vector object using the specified Comparison object.

Return Value:

No return value.

Parameter | Description
vector | The Vector object to be sorted.
comparison | The Comparison object to use.
first | The index of the beginning element of the subrange to sort.
size | The number of elements of the subrange to sort.

swap

protected void swap(int p, int q);

Swaps two elements in the vector.

Return Value:

No return value.

Parameter | Description
p | The index of the first operand of the swap operation.
q | The index of the second operand of the swap operation.

Overrides:

swap(int,int) in Sort.


Class WildcardExpression

public class WildcardExpression implements
            java.io.FilenameFilter, Cloneable, SetComparison
{
  // Fields
  public static int CASE_SENSITIVE;
  public static final int COMPARE_FL_ALL;
  public static final int COMPARE_FL_REJECT;
  public static final int COMPARE_FL_STOP1;
  public static final int COMPARE_FL_STOP2;
  public static int ESCAPED;
  public static int EXACT;
  public static int NO_DELIMITERS;
  public static int NO_WILDCARDS;

  // Constructors
  public WildcardExpression ();
  public WildcardExpression (String expr);
  public WildcardExpression (String expr, int flags);

  // Methods
  public boolean accept (java.io.File dir, String name);
  public synchronized void append (WildcardExpression other);
  public synchronized void append (WildcardExpression[] list);
  public synchronized void append (String expr, int flags);
  public void append (String expr);
  protected Object clone ();
  public int compare (WildcardExpression other,
        IWildcardExpressionComparator judge,
        boolean requireEquality);
  public int compare (WildcardExpression other);
  public int compare (WildcardExpression other,
        IWildcardExpressionComparator judge);
  public int compareSet (Object other);
  public static String ComparisonResulttoString (int cmp);
  public synchronized void compile (String expr, int flags);
  public void compile (String expr);
  public WildcardExpression condense ();
  public synchronized WildcardExpression condense (
        IWildcardExpressionComparator judge);
  public WildcardExpression copy ();
  public boolean equals (Object obj);
  public WildcardExpression[] getSubexpressions ();
  public WildcardExpression intersect (WildcardExpression other,
        IWildcardExpressionComparator judge);
  public WildcardExpression intersect (WildcardExpression other);
  public static int InvertComparisonResult (int cmp);
  public boolean isCaseSensitive ();
  public boolean isEmpty ();
  public boolean match (String s);
  public int matchex (String s);
  public static int matchOne (WildcardExpression[] exprs, int ofs,
        int len, String s);
  public static int matchOne (WildcardExpression[] exprs, String s);
  public int resume (String s);
  public WildcardExpression selectSubexpressions (
        WildcardExpression other, int[] criteria,
        IWildcardExpressionComparator judge);
  public WildcardExpression selectSubexpressions (
        WildcardExpression other, int[] criteria);
  public void setCaseInsensitive ();
  public String toString ();
  public String toString (boolean escaped);
}

This class matches simple wildcard expressions, such as *.txt or report?.doc commonly recognized by users on most platforms. The nonterminals "*" and "?" can be combined any number of times in any conceivable manner. Multiple expressions can be matched by separating the expressions with a semicolon; for example, "*.txt;*.doc" will match Strings ending with .txt or .doc. The special expression tokens can be matched by escaping them with '\'; for example, "clear\*sky" will match the string "clear*sky", but not "clearbluesky". Expressions can be case-sensitive or case-insensitive; this is selected when the expression is constructed.

This is very similar to DOS wildcards, but is in no way confined to filenames. The expression '*' will match a path in any subdirectory, and "*.*" does not match a file with no extension. For example, unlike DOS, "c:\\windows\\*" will match "c:\\windows\\system\\blue.vxd" and "*.*" will not match "notes".

WildcardExpression implements FilenameFilter, so it can readily be used with FileDialog, File.list, or ClientStore.listFiles.

The equals method has been overridden to special-case equality with strings. When invoked with a string, it will perform a match instead of comparing the pattern string. This allows it to be more easily used in a container, such as Vector, to find an expression matching a string. To find a matching expression in a string array, use the matchOne method.

While this may have its uses, the preferred method of matching a string against a series of expressions is to combine the expressions into a single expression using the append operator. The matchex function will return the sub-expression number of the first matching expression, and the resume function will continue searching for matching expressions. The use of matchex and resume should be externally synchronized, if there is the possibility that match, matchex, or resume may be used on the same expression simultaneously from another thread. For example:

 WildcardExpression expr = new WildcardExpression();
 expr.append("*.java");
 expr.append("*.txt");
 expr.append("*.doc");
 expr.append("c:\\docs\\*");
 // Resulting expression: "*.java;*.txt;*.doc;c:\\docs\\*"

 String filename = "c:\\docs\\foo.txt";
 synchronized (expr)
 {
     int exprnum;
     exprnum = expr.matchex(filename);   // returns 1
     exprnum = expr.resume(filename);    // returns 3
     exprnum = expr.resume(filename);    // returns -1
 }

Case-sensitive and case-insensitive expressions cannot be combined.

There are three ways to construct expressions:

  1. Use one of the constructors to create a set of subexpressions from a string delimited by ';'.
  2. Use the append methods to add subexpressions to an existing expression (which can be an empty expression). The new pattern string can optionally have ';' delimiters ignored. Both single WildcardExpression objects and arrays of WildcardExpression objects can be appended to existing expressions.
  3. Use the compile methods, which replace an existing expression with a new one using the same semantics as the constructors.

To improve performance, nothing in this class is synchronized. The typical use is that an expression is compiled once by the constructor. The compile and append methods are the only operators that change the state of the expression. Callers are responsible for synchronizing these operations with callers of the other methods. Note that matchex and resume also change state of the expression but not the expression itself. These operations also may need to be synchronized, but not with the others.

WildcardExpressions are not immutable, so security-critical code should be careful to pass copies of the expression to less-trusted code using the copy method. Some of the contents of the copy will be shared with the original until one of them changes.

Constructors

WildcardExpression

public WildcardExpression ();

Creates an empty expression. (An expression must be compiled before matches can be made.)

See Also: compile

WildcardExpression

public WildcardExpression (String expr);

Creates an expression that follows the typical wildcard convention.

Parameter | Description
expr | The expression evaluate.

WildcardExpression

public WildcardExpression (String expr, int flags);

Creates a case-sensitive expression from a string and allows for escaped wildcards.

Parameter | Description
expr | The expression to compile.
flags Combination of one or more of the following flags:
  • CASE_SENSITIVE
  • NO_DELIMITERS
  • ESCAPED

See Also: compile

Methods

accept

public boolean accept (java.io.File dir, String name);

Determines if a filename is valid.

Return Value:

Returns true if name matches a real path; otherwise, returns false.

Parameter | Description
dir | The directory that contains the file.
name | The name of the file.

append

public synchronized void append (WildcardExpression other);

Appends another expression to this expression.

Return Value:

No return value

Parameter | Description
other | The expression to append.

Exceptions:

IllegalArgumentException if the expressions are incompatible.

append

public synchronized void append (WildcardExpression[] list);

Adds a list of expressions to the expression. If any expressions fail to be added, the original expression is not affected.

Parameter | Description
list | The list of expressions to add.

append

public synchronized void append (String expr, int flags);

Appends another expression to this expression.

Parameter | Description
expr | The expression to append.
flags Combination of one or more of the following flags for controlling constructing of the expression:
  • NO_WILDCARDS
  • NO_DELIMITERS
  • ESCAPED

Note that CASE_SENSITIVE is not valid. The case-sensitivity of matching the new pattern is controlled by the existing case-sensitivity of the expression.

Exceptions:

IllegalArgumentException if the expression is invalid.

append

public void append (String expr);

Appends another expression to this expression.

Return Value:

No return value

Parameter | Description
expr | The expression to append.

Exceptions:

IllegalArgumentException if the expression is invalid.

clone

protected Object clone ();

Creates a copy of the this object.

Return Value:

Returns the cloned copy.

compare

public int compare (WildcardExpression other, IWildcardExpressionComparator
        judge, boolean requireEquality);

Compares the set of strings matched by this expression to the set matched by another. This variant of this method should be used for continued expressions.

Return Value:

Returns one of the SetComparison field values to indicate the relationship between the sets.

Parameter | Description
other | The object containing the other set of strings.
judge | Used for deciding what to do with two expressions.
requireEquality | Set to true if the comparator should time-out if it becomes impossible for an EQUAL result to be returned.

Exceptions:

IllegalArgumentException if the expressions cannot be compared.

compare

public int compare (WildcardExpression other);

Compares the set of strings matched by this expression to the set matched by another.

Return Value:

Returns one of the SetComparison field values to indicate the relationship between the sets. The result reflects the action of matching non-continuable expressions.

Parameter | Description
other | The object containing the other set of strings.

Exceptions:

IllegalArgumentException if the expressions cannot be compared.

compare

public int compare (WildcardExpression other, IWildcardExpressionComparator
        judge);

Compares the set of strings matched by this expression to the set matched by another. This variant of this method should be used for continued expressions.

Return Value:

Returns one of the SetComparison field values to indicate the relationship between the sets.

Parameter | Description
other | The object containing the other set of strings.
judge | Used for deciding what to do with two expressions.

Exceptions:

IllegalArgumentException if the expressions cannot be compared.

compareSet

public int compareSet (Object other);

Compares the set of strings matched by this expression to the set matched by another.

Return Value:

Returns one of the SetComparison field values to indicate the relationship between the sets. If other is not a WildcardExpression object, returns DISJOINT. The result reflects the action of matching non-continuable expressions.

Parameter | Description
other | The object containing the other set of strings.

Exceptions:

IllegalArgumentException if the expressions cannot be compared.

ComparisonResulttoString

public static String ComparisonResulttoString (int cmp);

Converts comparison result flags to a string format.

Return Value:

Returns the result string as follows:

  • "equal" (SetComparison.EQUAL)
  • "notequal" (SetComparison.DISJOINT)
  • "overlap" (SetComparison.OVERLAP)
  • "subset" (SetComparison.SUBSET)
  • "superset" (SetComparison.SUPERSET)

Parameter | Description
cmp | A comparison result from the compare method.

compile

public synchronized void compile (String expr, int flags);

Compiles the expression for faster evaluation. The previously compiled expression is lost when this method is called.

Return Value:

No return value.

Parameter | Description
expr | The expression to compile.
flags Combination of one or more of the following flags:
  • NO_WILDCARDS
  • CASE_SENSITIVE
  • NO_DELIMITERS
  • ESCAPED

See Also: match

compile

public void compile (String expr);

Compiles the expression for faster evaluation with default values.

Return Value:

No return value.

Parameter | Description
expr | The expression to compile.

Remarks:

The previously compiled expression is lost when this method is called. Case-sensitive matching and the evaluation of escaped wildcards are disabled for the compilation.

See Also: match

condense

public WildcardExpression condense ();

Removes redundant subexpressions. The new subexpressions may match overlapping sets of strings, but will not be equal or entirely match the set of strings of any other subexpressions.

Return Value:

Returns a new WildcardExpression object containing the unique expressions of the expression. If there are no redundant expressions, the original expression is returned.

condense

public synchronized WildcardExpression condense (
        IWildcardExpressionComparator judge);

Removes redundant subexpressions. The new subexpressions may match overlapping sets of strings, but will not be equal or entirely match the set of strings of any other subexpressions.

Return Value:

Returns a new WildcardExpression object containing the unique expressions of the expression. If there are no redundant expressions, the original expression is returned.

Parameter | Description
judge | Used for comparing any auxiliary data that may be associated with each subexpression.

copy

public WildcardExpression copy ();

Retrieves a copy of the currently compiled expression.

Return Value:

Returns a copy of the expression.

equals

public boolean equals (Object obj);

Determines if this object is equivalent to another object.

Return Value:

Returns true if obj is equivalent or matched by this object; otherwise, returns false.

Parameter | Description
obj | A String to match against this expression or a WildcardExpression to compare for equivalence.

getSubexpressions

public WildcardExpression[] getSubexpressions ();

Splits the expression into its subexpressions.

Return Value:

Returns an array of expressions that make up the subexpressions.

intersect

public WildcardExpression intersect (WildcardExpression other,
        IWildcardExpressionComparator judge);

Constructs an expression that matches any strings that this and another expression both match.

Return Value:

Returns an expression that is the intersection of the two expressions.

Parameter | Description
other | The other expression.
judge | A helper interface.

Remarks:

If either expression contains redundant subexpressions, the resulting expression will also contain redundant intersections. Calling condense beforehand on both expressions may improve the efficiency of this operation. Redundant expressions may be returned even if the source expressions contain no redundant expressions.

intersect

public WildcardExpression intersect (WildcardExpression other);

Constructs an expression that matches any strings that this and another expression both match.

Return Value:

Returns an expression that is the intersection of the two expressions.

Parameter | Description
other | The other expression.

InvertComparisonResult

public static int InvertComparisonResult (int cmp);

Inverts comparison results.

Return Value:

Returns the inverted comparison result.

Parameter Description
cmp Any comparison result of the compare method, which is inverted as follows:
  • SUBSET returns SUPERSET.
  • SUPERSET returns SUBSET.
  • any other result is not affected and is simply returned. Note that EQUAL and DISJOINT are not inverted by this function.

isCaseSensitive

public boolean isCaseSensitive ();

Determines if the expression is case-sensitive.

isEmpty

public boolean isEmpty ();

Determines if the expression has an expression compiled into it. An empty expression cannot be used for matching.

Return Value:

Returns true if the expression does not contain a compiled expression; otherwise, returns false.

match

public boolean match (String s);

Evaluates the expression on a string.

Return Value:

Returns true if the expression accepts the string.

Parameter | Description
s | The string to evaluate the expression on.

matchex

public int matchex (String s);

Evaluates the expression on a string.

Return Value:

Returns the subexpression number if the expression accepts the string; returns -1 if the string was not accepted.

Parameter | Description
s | The string to evaluate the expression on.

matchOne

public static int matchOne (WildcardExpression[] exprs, int ofs, int len,
        String s);

Evaluates a list of expressions on a string.

Return Value:

Returns the index of the expression that matched; returns -1 if no match occurred.

Parameter | Description
exprs | A list of expressions.
ofs | The offset into the list to begin matching
len | The number of elements to match against.
s | The string to evaluate the expressions on.

matchOne

public static int matchOne (WildcardExpression[] exprs, String s);

Evaluates a list of expressions on a string.

Return Value:

Returns the index of the expression that matched; returns -1 if no match occurred.

Parameter | Description
exprs | A list of expressions.
s | The string to evaluate the expressions on.

resume

public int resume (String s);

Resumes a previous match that stopped at a subexpression.

Return Value:

Returns the subexpression number if the expression accepts the string; returns -1 if the string was not accepted.

Parameter | Description
s | The string to evaluate the expression on.

selectSubexpressions

public WildcardExpression selectSubexpressions (WildcardExpression other,
        int[] criteria, IWildcardExpressionComparator judge);

Constructs a new expression containing expressions from this expression that have any of the specified comparison results against any subexpressions of the target expression.

Return Value:

Returns the original expression if all are selected; returns a new expression containing only the subexpressions of this expression that meet the selection criteria.

Parameter | Description
other | The target expression to compare against.
criteria | The selection criteria determining inclusion in the returned expression.
judge | An IWildcardExpressionComparator hook interface to compare any extra data associated with the subexpressions.

selectSubexpressions

public WildcardExpression selectSubexpressions (WildcardExpression other,
        int[] criteria);

Constructs a new expression containing expressions from this expression that have any of the specified comparison results against any subexpressions of the target expression.

Return Value:

Returns the original expression if all are selected; returns a new expression containing only the subexpressions of this expression that meet the selection criteria.

Parameter | Description
other | The other target expression to compare against.
criteriaThe | selection criteria determining inclusion in the returned expression.

setCaseInsensitive

public void setCaseInsensitive ();

Destructively changes the expression to perform case-insensitive matching. This change cannot be reversed.

toString

public String toString ();

Reconstructs the original expression in extended, non-escaped form. Case-insensitive expressions are reconstructed in lowercase.

Return Value:

Returns the original expression.

toString

public String toString (boolean escaped);

Reconstructs the original expression, optionally in escaped form. Case-insensitive expressions are reconstructed in lowercase.

Return Value:

Returns the original expression.

Parameter | Description
escaped | True if string is to include escape characters; false, otherwise.

Fields

CASE_SENSITIVE
Specifies that the resulting expression should perform case-sensitive matching.
COMPARE_FL_ALL
A IWildCardExpressionComparator result flag, used in conjunction with COMPARE_XXX, by IWildcardExpressionComparator.compareSubexpressions. Combines flags COMPARE_FL_REJECT, COMPARE_FL_STOP1, and COMPARE_FL_STOP2.
COMPARE_FL_REJECT
A Comparison result flag, used by IWildcardExpressionComparator.compareSubexpressions to stop the comparison.
COMPARE_FL_STOP1
A SetComparison result flag, used by IWildcardExpressionComparator.compareSubexpressions to disregard further elements of the first expression because they will not be considered during matching.
COMPARE_FL_STOP2
A SetComparison result flag, used in conjunction with COMPARE_XXX, by IWildcardExpressionComparator.compareSubexpressions to disregard further elements of the second expression because they will not be considered during matching.
ESCAPED
Specifies that the added string contains escaped expression characters. For example, "\*" will match a '*'.
EXACT
Specifies that the added string will be matched "as is," with no interpretation of delimiters or wildcards.
NO_DELIMITERS
Specifies that the string being added or compiled into the expression should be added as a single subexpression. Subexpression delimiters within the added string will be ignored.
NO_WILDCARDS
Specifies that wildcard characters in the added string will be ignored.


Interface Comparison

public interface Comparison
{
  // Methods
  public int compare(Object p, Object q);
}

This interface is designed for implementing comparisons of two objects (usually used in conjunction with a VectorSort or ArraySort object).

Methods

compare

public int compare(Object p, Object q);

Compares two Objects.

Return Value:

Returns less than 0 if p is less than or comes before q, 0 if p equals q, or greater than 0 if p is greater than or comes after q.

Parameter | Description
p | The Object to compare with q.
q | The Object to compare with p.


Interface IIntRangeComparator

public interface IIntRangeComparator
{
  // Fields
  static final int ORDER_AFTER;
  static final int ORDER_BEFORE;
  static final int ORDER_EQUAL;

  // Methods
  int compareRanges (IntRanges ranges1, int i1, IntRanges ranges2,
        int i2);
  void intersectRanges (IntRanges ranges1, int i1,
        IntRanges ranges2, int i2, int isectexprnum);
  boolean mergeRanges (IntRanges ranges, int i1, int i2);
  int orderRanges (IntRanges ranges, int i1, int i2);
  void shiftRanges (IntRanges ranges, int start, int count,
        int shiftcount);
  void splitRange (IntRanges ranges, int i);
  void swapRanges (IntRanges ranges, int i1, int i2);
}

This interface supplies a hook for sorting auxiliary data associated with elements of an IntRanges object. The hook is used to help compare equal ranges during a condensing operation, while sorting and merging ranges.

Methods

compareRanges

int compareRanges (IntRanges ranges1, int i1, IntRanges ranges2, int i2);

Compares ranges. This method is called by IntRanges.compare.

Return Value:

Returns one of the following values:

OVERLAP
The sets of integers are not equal but have a common set of integers.
DISJOINT
The sets of integers have no integers in common.
SUBSET
The second set of integers includes all of the integers in the first set, plus some integers that are not in the first set.
EQUAL
The sets of integers are identical.
SUPERSET
The first set of integers includes all of the integers in the second set, plus some integers that are not in the second set.

Parameter | Description
ranges1 | The first set of ranges to compare.
i1 | The index in ranges1 of the first range to compare.
ranges2 | The second set of ranges to compare.
i2 | The index in ranges2 of the second range to compare.

intersectRanges

void intersectRanges (IntRanges ranges1, int i1, IntRanges ranges2, int i2,
        int isectexprnum);

Called by IntRanges.intersect to intersect any extra data associated with two ranges.

Return Value:

No return value.

Parameter | Description
ranges1 | The first set of ranges to intersect.
i1 | The index into the first set of ranges.
ranges2 | The second set of ranges to intersect.
i2 | The index into the second set of ranges.
isectexprnum | The intersection expression.

mergeRanges

boolean mergeRanges (IntRanges ranges, int i1, int i2);

Determines if two overlapping ranges can be merged into a single range. This method is called by IntRanges.condense. If the ranges can be merged, they should be merged into the range and true should be returned.

Return Value:

Returns true if the ranges can be merged; otherwise, returns false.

Parameter | Description
ranges | The IntRanges object to merge into.
i1 | The index of first range to merge.
i2 | The index of second range to merge into the first range.

orderRanges

int orderRanges (IntRanges ranges, int i1, int i2);

Compares equal ranges. This method is called by IntRanges.sort.

Return Value:

Returns an integer indicating how to interpret two equal ranges. This can be on of the following values:

ORDER_BEFORE
i1 should be placed before i2.
ORDER_EQUAL
i1 and i2 are equal.
ORDER_AFTER
i1 should be placed after i2.

Parameter | Description
ranges | The set of integer ranges to order.
i1 | The index of first range.
i2 | The index of second range.

shiftRanges

void shiftRanges (IntRanges ranges, int start, int count, int shiftcount);

Moves the ranges backward.

Return Value:

No return value.

Parameter | Description
ranges | The IntRanges object containing the ranges to shift.
start | The starting index of the ranges to move.
count | The number of ranges to move.
shiftcount | The number of ranges to shift backward; if -1, the ranges should be discarded.

splitRange

void splitRange (IntRanges ranges, int i);

Splits a range. This method is called by IntRanges.removeRanges when a range needs to be split to remove elements in the middle of a range. During removal, this will be called, at most, one time.

Return Value:

No return value.

Parameter | Description
ranges | The range to be split.
i | The index at which to split.

swapRanges

void swapRanges (IntRanges ranges, int i1, int i2);

Swaps ranges. This method is called by IntRanges.sort.

Return Value:

No return value.

Parameter | Description
ranges | The IntRanges object in which to swap.
i1 | The index of the first range to swap.
i2 | The index of the second range to swap.

Fields

ORDER_AFTER
Returned by orderRanges to indicate that the one set of ranges is to be ordered after another set of ranges.
ORDER_BEFORE
Returned by orderRanges to indicate that the one set of ranges is to be ordered before another set of ranges.
ORDER_EQUAL
Returned by orderRanges to indicate that the one set of ranges is equal to another set of ranges.


Interface IWildcardExpressionComparator

public interface IWildcardExpressionComparator
{
  // Methods
  int compareSubexpressions (WildcardExpression expr1,
        int exprnum1, WildcardExpression expr2, int exprnum2, int
        cmpresult);
  void deleteSubexpression (WildcardExpression expr, int exprnum);
  void intersectSubexpressions (WildcardExpression expr1,
        int exprnum1, WildcardExpression expr2, int exprnum2, int
        cmpresult);
}

This interface is used to compare subexpressions in WildcardExpression.compare.

Methods

compareSubexpressions

int compareSubexpressions (WildcardExpression expr1, int exprnum1,
        WildcardExpression expr2, int exprnum2, int cmpresult);

Compares two subexpressions of different expressions.

Return Value:

Returns a SetComparison result code that is valid with WildcardExpression. This can be one of the following:

  • EQUAL
  • DISJOINT
  • SUBSET
  • OVERLAP
  • SUPERSET

Parameter | Description
expr1 | The first expression operand.
exprnum1 | The subexpression of expr1 to compare.
expr2 | The second expression operand.
exprnum2 | The subexpression of expr2 to compare.
cmpresult The result of comparing the given subexpressions (a SetComparison result code).

The cmpresult value must be computed before calling this function. The subexpressions are compared, and passed to this method as cmpresult. The return value of compareSubexpressions is possibly completely independent of cmpresult. The return value is the result of comparing any extra elements that clients of WildcardExpression may have associated with each subexpression.

deleteSubexpression

void deleteSubexpression (WildcardExpression expr, int exprnum);

Called by condense when redundant expressions need to be deleted.

Return Value:

No return value.

Parameter | Description
expr | The expression from which to delete the subexpression.
exprnum | The expression number, which is the original expression index, before any deletions have occurred. The new expression numbers will take effect after condense has completed.

intersectSubexpressions

void intersectSubexpressions (WildcardExpression expr1, int exprnum1,
        WildcardExpression expr2, int exprnum2, int cmpresult);

Called by WildcardExpression.intersect to find the intersection of any data associated with two subexpressions. The resulting data should be retained for the final intersected expression.

Return Value:

No return value.

Parameter | Description
expr1 | The first expression operand.
exprnum1 | The subexpression of expr1 to compare.
expr2 | The second expression operand.
exprnum2 | The subexpression of expr2 to compare.
cmpresult | The result of comparing the given subexpressions.


Interface ProvideSetComparisonInfo

public interface ProvideSetComparisonInfo
{
  // Fields
  static final int EXCLUDE;
  static final int INCLUDE;

  // Methods
  Object combineSetRules (Object o1, Object o2);
  int compareSetRules (Object o1, Object o2);
  Object getSetRule (int rule);
  String getStringForSetRule (Object o);
  Object intersectSetRules (Object o1, Object o2);
  boolean isEmptySetRule (Object o);
}

This interface provides set rules for comparisons. A set rule is an opaque value that defines a group of members from one or more sets. The rules can be manipulated using the operators on this interface. Rules are manipulated as Objects. Clients of this interface should not attempt to interpret the value of any objects returned from the methods.

Methods

combineSetRules

Object combineSetRules (Object o1, Object o2);

Computes the union of two objects retrieved from getSetRule or objects derived through other methods on this interface.

Return Value:

Returns a new set rule representing the union of the two rules, o1 and o2.

Parameter | Description
o1 | The first set rule.
o2 | The second set rule.

compareSetRules

int compareSetRules (Object o1, Object o2);

Compares two objects retrieved from getSetRule or objects derived through other methods on this interface.

Return Value:

Returns a SetComparison.compareSet return code.

Parameter | Description
o1 | The first set rule to compare.
o2 | The second set rule to compare.

getSetRule

Object getSetRule (int rule);

Obtains an object representing the specified rule that can be used internally by SetComparer.

Return Value:

Returns the object specifying the rule. The object is treated as an opaque value and is provided to the other operators on this interface to obtain further information.

Parameter | Description
rule | The rule, which can be either INCLUDE or EXCLUDE.

getStringForSetRule

String getStringForSetRule (Object o);

Retrieves a string representation of a given rule.

Return Value:

Returns the String representing the rule.

Parameter | Description
o | The given rule.

intersectSetRules

Object intersectSetRules (Object o1, Object o2);

Computes the intersection of two objects retrieved from getSetRule or objects derived through other methods on this interface.

Return Value:

Returns a new set rule representing the intersection of the two rules, o1 and o2.

Parameter | Description
o1 | The first set rule.
o2 | The second set rule.

isEmptySetRule

boolean isEmptySetRule (Object o);

Determines if the given set rule is empty.

Return Value:

Returns true if the object is empty; otherwise, returns false.

Parameter | Description
o | The given set rule.

Fields

EXCLUDE
Indicates the set rule specifying members that are excluded from the set.
INCLUDE
Indicates the set rule specifying members that are included in the set.


Interface SetComparison

public interface SetComparison
{
  // Fields
  static final int DISJOINT;
  static final int EMPTY;
  static final int EMPTY_SUBSET;
  static final int EMPTY_SUPERSET;
  static final int EQUAL;
  static final int OVERLAP;
  static final int SUBSET;
  static final int SUPERSET;

  // Methods
  int compareSet (Object other);
}

This interface compares two sets. It has only one method, which compares the sets, and a number of fields that are used to report the result of the set comparison.

Methods

compareSet

int compareSet (Object other);

Compares this set against another, and returns one of the previous results.

Return Value:

Returns one of the field values of this interface.

Parameter | Description
other | The set to compare this set against.

Fields

DISJOINT
The sets are disjoint.
EMPTY
Both sets are empty sets.
EMPTY_SUBSET
This set is empty, and the other set is not empty.
EMPTY_SUPERSET
This set is not empty, and the other set is empty.
EQUAL
The sets are identical.
OVERLAP
The sets overlap.
SUBSET
This set is a subset of the other set, and is not equal to the other set.
SUPERSET
This set is a superset of the other set, and is not equal to the other set.


Interface TimerListener

public interface TimerListener
{
  // Methods
  public void timeTriggered(TimerEvent te);
}

This interface enables timer event notifications to be received.

Methods

timeTriggered

public void timeTriggered(TimerEvent te);

Called when a timer event has expired.

Return Value:

No return value

Parameter | Description
te | A TimerEvent that describes the event.


About com.ms.util.InputMethod

In this topic

* Level 2 IME Support

* Level 3 IME Support

* Classes

* Interfaces

* Hierarchy

Packages | Packages | Next
Package com.ms.util.InputMethod | Packages | Next

About com.ms.util.InputMethod

The com.ms.util.InputMethod package provides Java classes and interfaces that support Input Method messaging and access to native system Input Method Editors (IMEs).

The Microsoft® Input Method Editor for Java APIs are designed to work with both Java and native system IMEs on any system where the Microsoft Win32 VM for Java is installed.

Level 2 IME Support

Currently, only level 2 IME support, where the user can type in text via a composition window, is provided for AFC components (components derived from com.ms.ui.UIComponent, or that implement the IUIComponent interface).

Level 3 IME Support

Level 3 IME support, where an IME is completely managed by an application, exists for components derived from java.awt.Component. The architecture of the com.ms.util.InputMethod package allows IMEs to work with components that are originally not IME-aware.

Input Method Editors generate InputMethodMessage-derived messages (such as IMECompositionMessage and IMENotifyMessage) when states change in the IME. These messages are passed to the InputMethodCallback.handleIMEMessage method. If the currently focused (AWT-derived) component implements the InputMethodMessageListener interface, these IME messages are passed to that component. The component can render its own custom IME user interface (handleIMEMessage returns true), or pass the message on to the InputMethodListener (handleIMEMessage returns false), which can then draw a default IME user interface.

The JavaIME accelerator key switching behavior is as follows: Ctrl+Alt will switch from JavaIME1, JavaIME2, ..., no IME, and back to JavaIME1, IME2, and so on.

Classes

Class IMECompositionMessage
This class implements Input Method (IME) Composition messages.
Class IMENotifyMessage
This class provides message objects that notify an Input Method Editor (IME) object to perform an action with one of the various windows associated with it.
Class InputMethodMessage
This class provides a base from which input method editor (IME) message classes can be derived.

Interfaces

Interface InputManagerListener
This interface receives messages from a system input and distributes those messages to designated Input Method Editors (IMEs) and other Components.
Interface InputMethodCallback
This interface enables InputMethodListener objects to return composed characters and Input Method Editor (IME) messages.
Interface InputMethodListener
This class must be implemented by Input Method Editors (IMEs) to be used with Java applications.
Interface InputMethodMessageListener
This interface is implemented by classes derived from java.awt.Component to handle Input Method Editor (IME) messages.

Hierarchy

Object
  |
  +--InputMethodMessage
     |
     +--IMECompositionMessage
     |
     +--IMENotifyMessage

InputManagerListener
InputMethodCallback
InputMethodListener
InputMethodMessageListener


Class IMECompositionMessage

public class IMECompositionMessage extends InputMethodMessage
{
  // Fields
  public final static int CHANGE_COMPOSITION;
  public final static int END_COMPOSITION;
  public final static int START_COMPOSITION;
  public final static int UNKNOWN;

  // Constructors
  public IMECompositionMessage( int id );
  public IMECompositionMessage( int id, int keyCode, int keyChar,
        String compStr );

  // Methods
  public String getComposition();
  public int getID();
  public int getKeyChar();
  public int getkeyCode();
  public void setComposition( String compStr );
  public void setKeyChar( int keyChar );
  public void setKeyCode( int keyCode );
  public String toString();
}

This class implements Input Method (IME) Composition messages.

InputMethodMessage
  |
  +--IMECompositionMessage

Constructors

IMECompositionMessage

public IMECompositionMessage( int id );

Creates an Input Method Composition message.

Parameter Description
id The message identifier, which can be one of the following:
START_COMPOSITION
END_COMPOSITION
CHANGE_COMPOSITION
UNKNOWN

IMECompositionMessage

public IMECompositionMessage( int id, int keyCode, int keyChar,
        String compStr );

Creates an Input Method Composition message that has a specific key code, key character, and composition string.

Parameter | Description
id The message identifier, which can be one of the following:
START_COMPOSITION
END_COMPOSITION
CHANGE_COMPOSITION
UNKNOWN
keyCode | The message key code.
keyChar | The message key character.
compStr | The message composition string.

Methods

getComposition

public String getComposition();

Retrieves the composition string from an IMECompositionMessage object.

Return Value:

Returns the message composition string (which can be null if a string hasn't been specified for the object).

getID

public int getID();

Retrieves the message identifier from an IMECompositionMessage object.

Return Value:

Returns the message identifier, which can be one of the following:
START_COMPOSITION END_COMPOSITION CHANGE_COMPOSITION UNKNOWN

or 0 if id hasn't been specified for the message.

getKeyChar

public int getKeyChar();

Retrieves the key character from an IMECompositionMessage object.

Return Value:

Returns the message key character (which can be 0 if keyChar hasn't been specified for the message).

See Also: setKeyChar

getkeyCode

public int getkeyCode();

Retrieves the key code from an IMECompositionMessage object.

Return Value:

Returns the message key code (which can be 0 if keyCode hasn't been specified for the message).

See Also: setkeyCode

setComposition

public void setComposition( String compStr );

Sets the IMECompositionMessage object composition string.

Return Value:

No return value.

Parameter | Description
compStr | The message composition string.

setKeyChar

public void setKeyChar( int keyChar );

Sets the IMECompositionMessage key character.

Return Value:

No return value.

Parameter | Description
keyChar | The character that is set.

setKeyCode

public void setKeyCode( int keyCode );

Sets the IMECompositionMessage key code.

Return Value:

No return value.

Parameter | Description
keyCode | The char that is set.

toString

public String toString();

Translates the IMECompositionMessage object to text form.

Return Value:

Returns a description of the IMECompositionMessage . For example, if the IMECompositionMessage is a START_COMPOSITION message, the text "IMECompositionMessage, START_COMPOSITION keyCode=keyCode keyChar=keyChar composition=compositionString" is returned.

Fields

CHANGE_COMPOSITION
A message used to alert a Component that a composition has changed.
END_COMPOSITION
A message used to alert a Component object that a composition is finished.
START_COMPOSITION
A message used to alert a Component object that a composition has started.
UNKNOWN
An unknown composition message.


Class IMENotifyMessage

public class IMENotifyMessage extends InputMethodMessage
{
  // Fields
  public final static int CHANGE_CANDIDATE;
  public final static int CLOSE_CANDIDATE;
  public final static int CLOSE_STATUS_WINDOW;
  public final static int OPEN_CANDIDATE;
  public final static int OPEN_STATUS_WINDOW;
  public final static int UNKNOWN;

  // Constructors
  public IMENotifyMessage( int id );

  // Methods
  public String[] getCandidateList();
  public int getID();
  public String toString();
}

This class provides message objects that notify an Input Method Editor (IME) object to perform an action with one of the various windows associated with it.

InputMethodMessage
  |
  +--IMENotifyMessage

Constructors

IMENotifyMessage

public IMENotifyMessage( int id );

Creates an Input Method Notify Message that includes a specific flag.

Parameter Description
id The flag used to create the message. This flag may be one of the following:
CLOSE_STATUS_WINDOW CLOSE_CANDIDATE UNKNOWN
OPEN_STATUS_WINDOW OPEN_CANDIDATE
CHANGE_CANDIDATE

Methods

getCandidateList

public String[] getCandidateList();

Retrieves a list of candidate windows.

Return Value:

Returns an array of strings that list the associated candidates.

getID

public int getID();

Retrieves the IMENotifyMessage messege identifier.

Return Value:

Returns the message identifier. This may be one of the following:
CLOSE_STATUS_WINDOW CLOSE_CANDIDATE UNKNOWN
OPEN_STATUS_WINDOW OPEN_CANDIDATE
CHANGE_CANDIDATE

toString

public String toString();

Translates the IMENotifyMessage object to text form.

Return Value:

Returns a description of the IMENotifyMessage. For example, if the IMENotifyMessage is a CLOSE_CANDIDATE message, the text "IMENotifyMessage, CLOSE_CANDIDATE" is returned.

Fields

CHANGE_CANDIDATE
An IME message used to change the IME Candidate window.
CLOSE_CANDIDATE
An IME message used to close the Candidate window associated with an IME.
CLOSE_STATUS_WINDOW
An IME message used to close an IME Status window.
OPEN_CANDIDATE
An IME message used to open a Candidate window associated with an IME.
OPEN_STATUS_WINDOW
An IME message used to open a Status window associated with the IME.
UNKNOWN
An unknown IME message.


Class InputMethodMessage

public abstract class InputMethodMessage
{
  // Constructors
  public InputMethodMessage();
}

This class provides a base from which input method editor (IME) message classes can be derived.

Constructors

InputMethodMessage

public InputMethodMessage();

Creates an input method message.

See Also: com.ms.util.InputMethod.IMENotifyMessage, com.ms.util.InputMethod.IMECompositionMessage


Interface InputManagerListener

public interface InputManagerListener
{
  // Fields
  public static final int ALT;
  public static final int CONTROL;
  public static final int DOWN;
  public static final int LBUTTON;
  public static final int MBUTTON;
  public static final int RBUTTON;
  public static final int SHIFT;
  public static final int UP;
  public static final int UPDOWN;

  // Methods
  public InputMethodListener getCurrentInputMethod() ;
  public InputMethodListener getCurrentInputMethod() ;
  public InputMethodListener getInputMethod(int idx);
  public int getNumberInputMethods();
  public boolean handledKey( InputMethodCallback imeCallback,
        long when, int keyCode, int keyChar, int state ) ;
  public void removeInputMethod(InputMethodListener ime);
  public void setInputMethod(InputMethodListener ime);
}

This interface receives messages from a system input and distributes those messages to designated Input Method Editors (IMEs) and other Components. This interface must be implemented by any object designated as the system Input Method Manager (IMM).

Also see com.ms.util.InputMethod.InputMethodListener, com.ms.util.InputMethod.InputMethodCallback

Methods

getCurrentInputMethod

public InputMethodListener getCurrentInputMethod() ;

Retrieves the current IME from an Input Method Manager-maintained list.

Return Value:

Returns the current InputMethodListener.

getCurrentInputMethod

public InputMethodListener getCurrentInputMethod() ;

Retrieves the current IME from an Input Method Manager-maintained list.

Return Value:

Returns the InputMethodListener at a specific index interface.

getInputMethod

public InputMethodListener getInputMethod(int idx);

Retrieves an IME from an Input Method Manager-maintained list.

Return Value:

Returns the InputMethodListener at a specific index interface.

Parameter | Description
idx | An index of an IME on the list.

getNumberInputMethods

public int getNumberInputMethods();

Retrieves the current number of registered Input Methods in an Input Method Manager-maintained list.

Return Value:

Returns the number of input methods on the list.

handledKey

public boolean handledKey( InputMethodCallback imeCallback, long when,
        int keyCode, int keyChar, int state ) ;

Called by an IME class that handles the keystrokes from the native system.

Return Value:

Returns true if InputManagerListener processes the keystroke; otherwise, returns false.

Parameter | Description
imeCallback | The InputMethodCallback object that receives keystrokes from the native system.
when | The time that the composed character is generated at.
keyCode | The ASCII key code of the character.
keyChar | The key character of the composed character.
state | The state when the event occurred.

removeInputMethod

public void removeInputMethod(InputMethodListener ime);

Removes a registered IME from the IMM-maintained list.

Return Value:

No return value.

Parameter | Description
ime | The IME removed from the list.

setInputMethod

public void setInputMethod(InputMethodListener ime);

Sets the given InputMethodListener object as the current IME.

Return Value:

No return value.

Parameter | Description
ime | The IME object to set the current input method as. If ime is null, all IMEs are deactivated, and the standard system keyboard input is used.

Fields

ALT
Indicates that the Alt key was depressed when this message was generated.
CONTROL
Indicates that the CTRL key was depressed when this message was generated.
DOWN
Indicates that either a key or mouse button was depressed.
LBUTTON
Indicates that the left mouse button was depressed when this message was generated.
MBUTTON
Indicates that the third mouse button was depressed when this message was generated.
RBUTTON
Indicates that the second (right) mouse button was depressed when this message was generated.
SHIFT
Indicates that the Shift key was depressed when this message was generated.
UP
Indicates that either a key or mouse button was released.
UPDOWN
Indicates that either a key or mouse button was depressed and released.


Interface InputMethodCallback

public interface InputMethodCallback
{
  // Methods
  public void handleIMEChar( long when, char keyChar, int state ) ;
  public void handleIMEMessage( InputMethodMessage IMEMessage ) ;
}

This interface enables InputMethodListener objects to return composed characters and Input Method Editor (IME) messages. This interface is used by both Java IMEs and native system IMEs.

Methods

handleIMEChar

public void handleIMEChar( long when, char keyChar, int state ) ;

Enables any class that implements InputMethodListener to return a composed character. The character is added to the internal input queue as if this is a character that the user typed. This method allows an InputMethodListener to pass back a composed character that is generated by a serious of keystrokes.

For example, in a Japanese IME, you can type "ka" to send a Katakana character that doesn't exist in a standard English keyboard.

Return Value:

No return value.

Parameter | Description
when | The time that the composed character is generated at.
keyChar | The key character of the composed character.
state | The state when the event occurred.

handleIMEMessage

public void handleIMEMessage( InputMethodMessage IMEMessage ) ;

Enables any class that implements InputMethodListener to handle IME-related messages.

Return Value:

No return value.

Parameter | Description
IMEMessage | The IME-related message (extended from InputMethodMessage). Two examples are IMENotifyMessage and IMECompositionMessage.


Interface InputMethodListener

public interface InputMethodListener
{
  // Methods
  public void activate() ;
  public void deactivate() ;
  public String getName() ;
  public boolean handledKey( InputMethodCallback imeCallback,
        long when, int keyCode, int keyChar, int state) ;
  public void handleIMEMessage( InputMethodMessage IMEMessage ) ;
  public void paint(Graphics g) ;
  public void setFont( Font font ) ;
  public void setPos(int x, int y) ;
  public void setVisibleComponent(Component c) ;
  public void setVisibleComponent( IUIComponent c) ;
  public Dimension size(Graphics g) ;
}

This class must be implemented by Input Method Editors (IMEs) to be used with Java applications.

Methods

activate

public void activate() ;

Activates the IME. You must call this method to activate the IME because the IME will never receive focus and be activated by using focus methods.

Return Value:

No return value.

Remarks:

Currently, this method is not implemented.

deactivate

public void deactivate() ;

Deactivates the IME. You must call this method to deactivate the IME because the IME will never receive or lose focus and be deactivated by using focus methods.

Return Value:

No return value.

Remarks:

Currently, this method is not implemented.

getName

public String getName() ;

Retrieves the localized name of the IME. The IME should call Locale.getDefault() to determine the current locale, and return the localized name according to the locale. However, if the IME does not have a name corresponding to the current locale, it should return a language-netural name of the IME, generally in English.

Return Value:

Returns the localized name of the IME.

handledKey

public boolean handledKey( InputMethodCallback imeCallback, long when,
        int keyCode, int keyChar, int state) ;

Called by the InputManagerListener. The InputManagerListener passes the keystroke to the InputMethodListener object by calling this method.

If the InputMethodListener object accepts the keystroke, it returns true and the keystroke never returns to the internal input queue. If the return value is false, this keystroke is returned to the internal input queue.

Return Value:

Returns true if InputMethodListener processes the keystroke; otherwise, returns false.

Parameter | Description
imeCallback | The InputMethodCallback object that receives keystrokes from the native system.
when | The time that the composed character is generated.
keyCode | The ASCII key code of the character.
keyChar | The key character of the composed character.
state | The state when the event occurred.

handleIMEMessage

public void handleIMEMessage( InputMethodMessage IMEMessage ) ;

Handles an IME Message. The IME will first send any IME messages generated by itself to InputMethodCallback. handleIMEMessage. This gives the application a chance to handle IME messages (to reposition the IME windows, for example).

However, if the handleIMEMessage method in the application which implements the InputMethodMessageListener returns false, the InputMethodCallback will forward these IME messages back into this method. In this way the InputMethodListener can listen to these messages and repaint the default IME user interface.

Return Value:

No return value

Parameter | Description
IMEMessage | The InputMethodMessage that is processed.

paint

public void paint(Graphics g) ;

Paints the object on a specific graphic object.

Return Value:

No return value.

Parameter | Description
g | The Graphics object used to paint.

Remarks:

Currently, this method is not implemented.

setFont

public void setFont( Font font ) ;

Sets the font used in composition window.

Return Value:

No return value.

Parameter | Description
font | The Font used in the composition window.

setPos

public void setPos(int x, int y) ;

Displays the IME composition window on the visible canvas in terms of (x,y) coordinates. When the IME is attached to a component, the position of the composition window will be set in the client area of the component.

Return Value:

No return value.

Parameter | Description
x | The x coordinate of the position of the IME composition window.
y | The y coordinate of the position of the IME composition window.

Remarks:

Currently, this method is not implemented.

setVisibleComponent

public void setVisibleComponent(Component c) ;

Sets the component c as the component where the IME is seen on the screen. This component does not have to be an independent window, but it can be attached to the input window.

Return Value:

No return value.

Parameter | Description
c | The component that displays the IME on the screen.

setVisibleComponent

public void setVisibleComponent( IUIComponent c) ;

Sets the component c as the component where the IME is seen on the screen. This component does not have to be an independent window, but it can be attached to the input window.

Return Value:

No return value.

Parameter | Description
c | The component that displays the IME on the screen.

size

public Dimension size(Graphics g) ;

Retrieves the current size of the area required to draw the IME, using the given graphics object. This method enables the caller to set text fonts and colors.

Return Value:

Returns null, by default.

Parameter | Description
g | The Graphics object used to determine the size of the IME.

Remarks:

Currently, this method is not implemented.


Interface InputMethodMessageListener

public interface InputMethodMessageListener
{
  // Methods
  public boolean handleIMEMessage( InputMethodMessage IMEMessage ) ;
}

This interface is implemented by classes derived from java.awt.Component to handle Input Method Editor (IME) messages.

Methods

handleIMEMessage

public boolean handleIMEMessage( InputMethodMessage IMEMessage ) ;

Handles IME-related messages. The class that implements the InputMethodMessageListener interface needs to have current focus for IME messages to be successfully handled.

Return Value:

Returns true if the class that implements the interface draws its own custom IME user interface. If the implementation method returns false, IME messages are directed to the InputMethodListener, which draws the IME user interface.

Parameter | Description
IMEMessage | The IME-related message (which is extended from InputMethodMessage). Two examples are IMENotifyMessage and IMECompositionMessage.


About com.ms.xml.dso

This package provides a Data Source Object (DSO) applet class that can be used to provide data for data binding by using XML files.

Classes

Class XMLDSO
This class is an applet that can be used with an <APPLET> tag to load XML files and provide the data contained in these files for data binding.

Hierarchy

Applet
  |
  +--XMLDSO


Class XMLDSO

public class XMLDSO extends Applet
{
  // Constructors
  public XMLDSO();

  // Methods
  public void addDataSourceListener(DataSourceListener listener)
        throws java.util.TooManyListenersException;
  public void clear();
  public Object getDocument();
  public String getError();
  public Object getXML();
  public void init();
  public void load(String arg);
  public OLEDBSimpleProvider msDataSourceObject(String qualifier);
  public void notifyListeners();
  public void paint(Graphics g);
  public void removeDataSourceListener( DataSourceListener listener);
  public void save(String filename);
  public void setRoot(Element e);
  public void updateSchema();
}

This class is an applet that can be used with an <APPLET> tag to load XML files and provide the data contained in these files for data binding.

Also see Document, Element

Applet
  |
  +--XMLDSO

Constructors

XMLDSO

public XMLDSO();

Constructs an XMLDSO object with an empty document.

Methods

addDataSourceListener

public void addDataSourceListener(DataSourceListener listener)
        throws java.util.TooManyListenersException;

Adds a DataSourceListener object to the XMLDSO object.

Return Value:

No return value.

Parameter | Description
listener | The listener to add to the DSO.

Exceptions:

TooManyListenersException if too many listeners are associated with the Data Source Object (DSO).

clear

public void clear();

Replaces the currently loaded document with a new, empty document.

Return Value:

No return value.

getDocument

public Object getDocument();

Retrieves the loaded document.

Return Value:

Returns the loaded document.

getError

public String getError();

Retrieves a string containing last error encountered by the XMLDSO object.

Return Value:

Returns a String that describes the last error that was encountered.

getXML

public Object getXML();

Retrieves the XML for the loaded document as a large string.

Return Value:

Returns a string object that contains the XML contents of the loaded document.

init

public void init();

Searches for a PARAM with a URL and loads this URL if found. Otherwise, it looks for inline XML inside the <APPLET> tag that created the current XMLDSO object.

Return Value:

No return value.

Remarks:

If no URL or inline XML exists, the method performs no action.

load

public void load(String arg);

Reloads the document using the specified URL. Relative URLs are resolved using the HTML document as a base for the URL.

Return Value:

No return value.

Parameter | Description
arg | A String that contains the URL used to reload the document.

msDataSourceObject

public OLEDBSimpleProvider msDataSourceObject(String qualifier);

Provides the OLE-DB Simple Provider Interface to callers.

Return Value:

Returns an OLEDBSimpleProvider object.

Parameter | Description
qualifier | This parameter is currently ignored, but is available to enable the applet to serve more than one data set.

notifyListeners

public void notifyListeners();

Notifies current DataSouceListener objects associated with the XMLDSO that data has changed.

Return Value:

No return value.

paint

public void paint(Graphics g);

Displays diagnostic information that helps the page author debug the page if the applet that contains the XMLDSO is given bounds that are non-zero.

Return Value:

No return value.

Parameter | Description
g | The graphics context to use to paint the applet.

removeDataSourceListener

public void removeDataSourceListener( DataSourceListener listener);

Removes a DataSourceListener object from the XMLDSO object.

Return Value:

No return value.

Parameter | Description
listener | The listener to remove from the DSO.

save

public void save(String filename);

Saves the XML document to a file.

Return Value:

No return value.

Parameter | Description
filename | The name of the file to save the XML document to.

setRoot

public void setRoot(Element e);

Sets the root of the document for this XMLDSO object. This is useful when you want to link together multiple DSOs.

Return Value:

No return value.

Parameter | Description
e | The Element to set as the root of the document.

updateSchema

public void updateSchema();

Updates the SCHEMA whenever the document is changed. The method is called from the clear, load, and setRoot methods, but you can also call this method if you have manually changed the document or the SCHEMA <PARAM>. The SCHEMA <PARAM> is used to define a subset of data that is visible through the DSO.

Return Value:

No return value.


About com.ms.xml.om

The com.ms.xml.om package provides classes that implement the Microsoft XML Object Model in Java. These classes provide a way of loading XML documents, manipulating the resulting XML tree, and then writing the modified XML back out, thereby enabling applications based on XML.

Classes

Class Document
This class implements an XML document, which can be thought of as the root of a tree.
Class DocumentBeanInfo
This class provides specialized JavaBeans support for the Document class to resolve which overloaded functions are accessible through scripting.
Class ElementCollection
This class provides a collection interface to elements similar to the element collections found in the Internet Explorer 4.0 Dynamic HTML object model.
Class ElementEnumeration
This class is a simple Enumeration for iterating over the immediate children of a given node in the XML tree.
Class ElementFactoryImpl
This class represents the default implementation for the element factory.
Class ElementImpl
This class represents the default implementation of the Element interface.
Class ElementImplBeanInfo
This class provides specialized JavaBeans support for the ElementImpl class to resolve which overloaded functions are accessible through scripting.

Interfaces

Interface Element
This interface implements an Element object.
Interface ElementFactory
This interface specifies a method to create elements for an XML element tree.

Hierarchy

Object
  |
  +--ElementImpl (Element)
  |  |
  |  +--Document (ElementFactory)
  |
  +--ElementCollection
  |
  +--ElementEnumeration (Enumeration)
  |
  +--ElementFactoryImpl (ElementFactory)

SimpleBeanInfo
  |
  +--DocumentBeanInfo
  |
  +--ElementImplBeanInfo

Element
ElementFactory


Class Document

public class Document extends ElementImpl implements
            ElementFactory
{
  // Fields
  protected DTD dtd;
  protected ElementFactory factory;

  // Constructors
  public Document();
  public Document(ElementFactory f);

  // Methods
  public void addChild(Element elem, Element after);
  public void clear();
  public final Element createElement(int type, Name tag);
  public final Element createElement(int type, String tag);
  public final Element createElement(int type);
  public XMLOutputStream createOutputStream(
        OutputStream out) throws IOException;
  public final Enumeration elementDeclarations();
  public final String getCharset();
  public final String getDocType();
  public DTD getDTD();
  public final String getDTDURL();
  public final String getEncoding();
  public long getFileModifiedDate();
  public final String getId();
  public int getOutputStyle();
  public Element getParent();
  public final Element getRoot();
  public String getText();
  public int getType();
  public final String getURL();
  public final String getVersion();
  public void load(String urlstr) throws ParseException;
  public void load(URL url) throws ParseException;
  public void load(InputStream in) throws ParseException;
  public void parsed(Element e);
  public void removeChild(Element elem);
  public void reportError(ParseException e, OutputStream out);
  public void save(XMLOutputStream o) throws IOException;
  public final void setCharset(String encoding);
  public final void setEncoding( String encoding );
  public void setOutputStyle(int style);
  public void setText(String text);
  public void setURL( String urlstr ) throws ParseException;
  public final void setVersion( String version );
}

This class implements an XML document, which can be thought of as the root of a tree. Each XML tag can either represent a node or a leaf of this tree. The Document class allows you to load an XML document, manipulate it, and then save it back out again. The document can be loaded by specifying a URL or an input stream.

According to the XML specification, the root of the tree consists of any combination of comments and processing instructions, but only one root element. A helper method getRoot is provided as a short cut to finding the root element.

Also see com.ms.xml.om.Element

ElementImpl
  |
  +--Document

Constructors

Document

public Document();

Constructs a new empty document using the default element factory.

Document

public Document(ElementFactory f);

Constructs a new empty document using the given ElementFactory object when building the XML element hierarchy.

Parameter | Description
f | The ElementFactory to use.

Methods

addChild

public void addChild(Element elem, Element after);

Adds a child Element to the document. This is an override of the Element.addChild method that stores the new child and stores the last element of type Element.ELEMENT, so that getRoot can be used as a short cut to find a particular element.

Parameter | Description
elem | The child element to add.
after | The element after which to add the elem element.

Overrides:

addChild(Element,Element) in ElementImpl.

clear

public void clear();

Sets the Document back to its initial empty state retaining only the ElementFactory association.

Return Value:

No return value.

createElement

public final Element createElement(int type, Name tag);

Creates a new element for the given element type and tag name using the ElementFactory for this Document. This method allows the Document class to be used as an ElementFactory itself.

Parameter | Description
type | The element type.
tag | The element tag.

createElement

public final Element createElement(int type, String tag);

Creates a new element for the given element type and tag name.

Parameter | Description
type | The element type.
tag | The element tag name.

createElement

public final Element createElement(int type);

Creates a new element for a given element type with a null tag name.

Return Value:

Returns the element created.

Parameter | Description
type | The element type.

createOutputStream

public XMLOutputStream createOutputStream(OutputStream out)
        throws IOException;

Creates an XML output stream matching the format found on load().

Return Value:

Returns the XML output stream.

Parameter | Description
out | The output stream.

Exceptions:

IOException if the output stream cannot be created.

elementDeclarations

public final Enumeration elementDeclarations();

Retrieves an enumeration of the element declarations from the DTD. These are returned as ElementDecl objects.

Return Value:

Returns the element declarations enumeration object.

getCharset

public final String getCharset();

Retrieves the character set. This is an alias for the setEncoding method and exists for compatibility reasons only.

Return Value:

Returns the character set.

getDocType

public final String getDocType();

Retrieves the document type.

Return Value:

Returns the name specified in the <!DOCTYPE> tag.

getDTD

public DTD getDTD();

Retrieves the document's DTD.

Return Value:

Returns the DTD.

getDTDURL

public final String getDTDURL();

Retrieves the document type URL.

Return Value:

Returns the URL specified in the <!DOCTYPE> tag or null if an internal DTD was specified.

getEncoding

public final String getEncoding();

Retrieves the character encoding information.

Return Value:

Returns the encoding information stored in the <?XML ...?> tag or the user-defined output encoding if it has been more recently set.

getFileModifiedDate

public long getFileModifiedDate();

Retrieves the last modified date on the source of the URL.

Return Value:

Returns the modified date.

getId

public final String getId();

Retrieves the external identifier.

Return Value:

Returns the external identifier specified in the <!DOCTYPE> tag or null if no <!DOCTYPE> tag was specified.

getOutputStyle

public int getOutputStyle();

Retrieves the current output style.

Return Value:

Returns the output style. The default style is XMLOutputStream.PRETTY.

getParent

public Element getParent();

Retrieves the parent element. There is no parent element for Document, so this method always returns null.

Return Value:

Returns null.

Overrides:

getParent() in ElementImpl.

getRoot

public final Element getRoot();

Retrieves the root node of the XML parse tree. This is guaranteed to be of type Element.ELEMENT.

Return Value:

Returns the root node.

getText

public String getText();

Retrieves the document text.

Return Value:

Returns a plain text (that is, not marked-up) representation of the entire document.

Overrides:

getText() in ElementImpl.

getType

public int getType();

Retrieves the document type.

Return Value:

Returns the value defined by Element.DOCUMENT.

Overrides:

getType() in ElementImpl.

getURL

public final String getURL();

Retrieves the URL.

Return Value:

Returns the last URL sent to the load() method or null if an input stream was used.

getVersion

public final String getVersion();

Retrieves the version information.

Return Value:

Returns the version number stored in the <?XML ...?> tag.

load

public void load(String urlstr) throws ParseException;

Loads the document from the given URL string.

Return Value:

No return value.

Parameter | Description
urlstr | The URL specifying the address of the document.

Exceptions:

ParseException if the file contains errors.

load

public void load(URL url) throws ParseException;

Loads the document from the given URL.

Return Value:

No return value.

Parameter | Description
url | The URL string.

Exceptions:

ParseException if a syntax error is found.

load

public void load(InputStream in) throws ParseException;

Loads the document using the given input stream. This is useful if you have the XML data already in memory.

Return Value:

No return value.

Parameter | Description
in | The input stream.

Exceptions:

ParseException when a syntax error is found.

parsed

public void parsed(Element e);

Called when the given element is completely parsed.

Return Value:

No return value.

Parameter | Description
e | The Element that has been parsed.

removeChild

public void removeChild(Element elem);

Removes the specified child Element from the Document.

Parameter | Description
elem | The child element to remove.

Overrides:

removeChild(Element) in ElementImpl.

reportError

public void reportError(ParseException e, OutputStream out);

Returns information about the given parse exception that was generated during the load.

Return Value:

No return value.

Parameter | Description
e | The exception to report on.
out | The output stream to report to.

save

public void save(XMLOutputStream o) throws IOException;

Saves the document to the given output stream.

Return Value:

No return value.

Parameter | Description
o | The output stream.

Overrides:

save(XMLOutputStream) in ElementImpl.

Exceptions:

IOException if there is a problem saving the output.

setCharset

public final void setCharset(String encoding);

Sets the character set. This is an alias for the getEncoding method and exists for compatibility reasons only.

Return Value:

No return value.

Parameter | Description
encoding | The encoding information.

setEncoding

public final void setEncoding( String encoding );

Sets the character encoding for output. Eventually it sets the ENCODING stored in the <?XML ...?> tag, but not until the document is saved. You should not call this method until the Document has been loaded.

Return Value:

No return value.

setOutputStyle

public void setOutputStyle(int style);

Sets the style for writing to an output stream. Use XMLOutputStream.PRETTY or .COMPACT.

Return Value:

No return value.

Parameter | Description
int | The style to set.

See Also: XMLOutputStream

setText

public void setText(String text);

Passes the text through to the root node, if there is a root node.

Parameter | Description
text | The text to be set.

Overrides:

setText(String) in ElementImpl.

setURL

public void setURL( String urlstr ) throws ParseException;

An alias for load and is here for compatibility reasons only.

Return Value:

No return value.

Parameter | Description
urlstr | The URL string.

Exceptions:

ParseException if an error occurs while parsing the URL string.

setVersion

public final void setVersion( String version );

Sets the version number stored in the <?XML ...?> tag.

Return Value:

No return value.

Parameter | Description
version | The version information to set.

Fields

dtd
The Document Type Definition (DTD).
factory
The factory used to create the elements in the document.


Class DocumentBeanInfo

public class DocumentBeanInfo extends SimpleBeanInfo
{
  // Methods
  public MethodDescriptor[] getMethodDescriptors();
}

This class provides specialized JavaBeans support for the Document class to resolve which overloaded functions are accessible through scripting.

SimpleBeanInfo
  |
  +--DocumentBeanInfo

Methods

getMethodDescriptors

public MethodDescriptor[] getMethodDescriptors();

Returns the method descriptions for the methods that are to be made available through scripting.

Return Value:

Returns an array of MethodDescriptor objects.


Class ElementCollection

public class ElementCollection
{
  // Constructors
  public ElementCollection(Element root);
  public ElementCollection(Element root, Name tag, int type);

  // Methods
  public Element getChild(int index);
  public int getLength();
  public Object item(String name);
  public Element item(String name, int index);
}

This class provides a collection interface to elements similar to the element collections found in the Internet Explorer 4.0 Dynamic HTML object model.

Constructors

ElementCollection

public ElementCollection(Element root);

Creates new collection object for given element.

ElementCollection

public ElementCollection(Element root, Name tag, int type);

Creates a new collection for iterating over the immediate children of the given root node that have matching tag names and/or element types.

Parameter | Description
root | The root to form the collection around.
tag | The name of the tag; this parameter can be null if the name is not important.
type | The element type. Element.ELEMENT is the most common. If the element type is not important, pass -1.

Methods

getChild

public Element getChild(int index);

Retrieves a specified item from the collection by index.

Return Value:

Returns the requested child node; returns null if not found.

Parameter | Description
index | The index of the item in the element collection.

getLength

public int getLength();

Retrieves the number of items in the collection.

Return Value:

Returns the item count.

item

public Object item(String name);

Retrieves a named item or a collection of matching items.

Return Value:

Returns the requested item. Possible types of objects returned are Element, ElementCollection, or null.

Parameter | Description
name | The name of the item or collection of matching items.

item

public Element item(String name, int index);

Retrieves a specified item from the collection of matching items.

Return Value:

Returns the requested item if it is found; returns null if it is not found.

Parameter | Description
name | The name of the matching items.
index | The index of the specific matching item to return.


Class ElementEnumeration

public class ElementEnumeration implements Enumeration
{
  // Constructors
  public ElementEnumeration(Element root);
  public ElementEnumeration(Element root, Name tag, int type);

  // Methods
  public boolean hasMoreElements();
  public Object nextElement();
  public void reset();
}

This class is a simple Enumeration for iterating over the immediate children of a given node in the XML tree. This is not a hierarchical iterator. It does not walk the entire tree.

Also see com.ms.xml.om.Element, Name

Constructors

ElementEnumeration

public ElementEnumeration(Element root);

Creates a new enumerator for enumerating over all of the children of the given root node.

Parameter | Description
root | The element whose children are going to be enumerated.

ElementEnumeration

public ElementEnumeration(Element root, Name tag, int type);

Creates a new enumerator for enumerating over the immediate children of the given root node that have matching tag names and/or types.

Parameter | Description
root | The element whose children are going to be enumerated.
tag | The name of the tag; this parameter can be null if the name is not important.
type | The element type. Element.ELEMENT is the most common. If the element type is not important, pass -1.

Methods

hasMoreElements

public boolean hasMoreElements();

Determines if there are any more matching elements.

Return Value:

Returns true if the next call to nextElement will return a non-null result.

nextElement

public Object nextElement();

Retrieves the next matching element.

Return Value:

Returns Element or null if there are no more matching elements.

reset

public void reset();

Resets the iterator so that you can iterate through the elements again.

Return Value:

No return value.


Class ElementFactoryImpl

public class ElementFactoryImpl implements ElementFactory
{
  // Constructors
  public ElementFactoryImpl();

  // Methods
  public Element createElement(int type, Name tag);
  public void parsed(Element elem);
}

This class represents the default implementation for the element factory. This is what the XML parser uses if no other factory is specified.

Constructors

ElementFactoryImpl

public ElementFactoryImpl();

Constructs the factory object.

Methods

createElement

public Element createElement(int type, Name tag);

Retrieves a new element for the specified tag and type.

Return Value:

Returns the newly created element.

Parameter | Description
type | The element type.
tag | The element name.

parsed

public void parsed(Element elem);

This method is called when the element is fully parsed.

Return Value:

No return value.

Parameter | Description
elem | The element parsed.

See Also: com.ms.xml.om.Element


Class ElementImpl

public class ElementImpl implements Element
{
  // Fields
  protected Attributes attrlist;

  // Constructors
  public ElementImpl();
  public ElementImpl(Name tag, int type);

  // Methods
  public void addChild(Element elem, Element after);
  public void addChild(Element elem, int pos, int reserved);
  public Object getAttribute(String name);
  public Object getAttribute(Name attrName);
  public Enumeration getAttributes();
  public Element getChild(int index);
  public ElementCollection getChildren();
  public Enumeration getElements();
  public Element getParent();
  public Name getTagName();
  public String getText();
  public int getType();
  public boolean isAttributeQualified(Name attr, DTD dtd);
  public int numAttributes();
  public int numElements();
  public void removeAttribute(String name);
  public void removeAttribute(Name attrName);
  public void removeChild(Element elem);
  public void save(XMLOutputStream o) throws IOException;
  public void saveAttributes(Name ns, XMLOutputStream o)
        throws IOException;
  public void saveText(String str, XMLOutputStream o)
        throws IOException;
  public void setAttribute(String name, Object value);
  public void setAttribute(Name attrName, Object value);
  public void setParent(Element parent);
  public void setText(String text);
  public String toString();
}

This class represents the default implementation of the Element interface. These are created by the XML parser when using the default element factory.

Also see com.ms.xml.om.Element, Parser, com.ms.xml.om.ElementFactory, com.ms.xml.om.ElementFactoryImpl

Constructors

ElementImpl

public ElementImpl();

ElementImpl

public ElementImpl(Name tag, int type);

Methods

addChild

public void addChild(Element elem, Element after);

Adds a child to this element. Any element can only have one parent element, and so the previous parent will lose this child from its subtree.

Return Value:

No return value.

Parameter | Description
elem | The element to add. The child element becomes the last element if after is null. The child is added to the beginning of the list if after is this object.
after | The element after which to add it.

addChild

public void addChild(Element elem, int pos, int reserved);

Adds a child to this element.

Return Value:

No return value.

Parameter | Description
elem | The element to add.
pos | The position to add this element (calling getChild(pos) will return this element). If pos is less than 0, elem becomes the new last element.
reserved | The reserved parameter.

getAttribute

public Object getAttribute(String name);

Retrieves an attribute's value given its name.

Return Value:

Returns the value of the attribute; returns null if the attribute is not found.

Parameter | Description
name | The name of the attribute.

getAttribute

public Object getAttribute(Name attrName);

Retrieves an attribute's value given its name.

Return Value:

Returns the value of the attribute; returns null if the attribute is not found.

Parameter | Description
name | The name of the attribute.

getAttributes

public Enumeration getAttributes();

Retrieves an enumeration for the element attributes. The enumeration returns Attribute objects.

Return Value:

Returns the enumeration. This method must not return null (see EnumWrapper for returning empty enumerations).

See Also: Attribute

getChild

public Element getChild(int index);

Retrieves the child element by index.

Return Value:

Returns null if there is no child by that index.

Parameter | Description
index | The index of the child element.

getChildren

public ElementCollection getChildren();

Returns an element collection of the children of this element. This method must not return null. See EnumWrapper for an empty enumeration.

Return Value:

Returns element collection of child objects.

getElements

public Enumeration getElements();

Returns an enumeration of the children of this element. Enumeration.nextElement returns Element objects.

Return Value:

Returns an enumeration of child objects. It must not return null. See EnumWrapper for an easy way to return an empty enumeration.

getParent

public Element getParent();

Retrieves the parent of this element. Every element in the tree except the Document object itself, has a parent.

Return Value:

Returns the parent element or null if the element is at the root of the tree.

getTagName

public Name getTagName();

Retrieves the name of the tag as a string. The string will be in uppercase.

Return Value:

Returns the tag name or null for DATA and PCDATA elements.

getText

public String getText();

Returns the non-marked-up text contained by this element. For text elements, this is the raw data. For elements with child nodes, this method traverses the entire subtree and appends the text for each terminal text element, effectively stripping out the XML markup for the subtree. For example, if the XML document contains the following: <xmp> <AUTHOR> <FIRST>William</FIRST> <LAST>Shakespeare</LAST> </AUTHOR> </xmp>

Document.getText returns "William Shakespeare".

getType

public int getType();

Retrieves the type of the element. This is always one of the following values: DOCUMENT, ELEMENT, PCDATA, PI, META, COMMENT, or CDATA.

Return Value:

Returns the element type.

isAttributeQualified

public boolean isAttributeQualified(Name attr, DTD dtd);

Determines if the attribute is qualified.

Return Value:

Returns true if the attribute is qualified; otherwise, returns false.

Parameter | Description
attr | The name of the attribute.
dtd | The Document Definition Type (DTD) in which the attribute is found.

numAttributes

public int numAttributes();

Retrieves the number of attributes.

Return Value:

Returns the number of attributes.

numElements

public int numElements();

Retrieves the number of child elements.

Return Value:

Returns the number of child elements.

removeAttribute

public void removeAttribute(String name);

Deletes an attribute from an element.

Return Value:

No return value.

Parameter | Description
name | The attribute to delete.

removeAttribute

public void removeAttribute(Name attrName);

Deletes an attribute from an element.

Parameter | Description
attrName | The attribute name to delete.

removeChild

public void removeChild(Element elem);

Removes a child element from the tree.

Return Value:

No return value.

Parameter | Description
elem | The element to remove.

save

public void save(XMLOutputStream o) throws IOException;

Saves the element in XML format.

Return Value:

No return value.

Parameter | Description
o | The output stream to save to.

Exceptions:

IOException if an error occurs when writing to the output stream.

saveAttributes

public void saveAttributes(Name ns, XMLOutputStream o) throws IOException;

Saves the element attributes in XML format.

Return Value:

No return value.

Parameter | Description
ns | The name of the element attribute.
o | The output stream to save to.

Exceptions:

IOException if an error occurs when writing to the output stream.

saveText

public void saveText(String str, XMLOutputStream o) throws IOException;

Saves the text out restoring any built-in entities that may be needed to keep the document valid.

Return Value:

No return value.

Parameter | Description
str | The text to save.
o | The output stream to save to.

Exceptions:

IOException if an error occurs when writing to the output stream

setAttribute

public void setAttribute(String name, Object value);

Sets the attribute of this element.

Return Value:

Returns any previous value, if any.

Parameter | Description
name | The attribute name.
value | The attribute value.

setAttribute

public void setAttribute(Name attrName, Object value);

Sets the attribute of this element.

Parameter | Description
attrName | The attribute name.
value | The attribute value.

setParent

public void setParent(Element parent);

Sets the parent of this element.

Return Value:

No return value.

Parameter | Description
parent | The element to set as the parent.

setText

public void setText(String text);

Sets the text for this element. This text is Only meaningful in CDATA, PCDATA, and COMMENT nodes.

Parameter | Description
The | text to set.

toString

public String toString();

Retrieves the string representation of this element.

Return Value:

Returns a string representing the element.

Fields

attrlist
The attribute list.


Class ElementImplBeanInfo

public class ElementImplBeanInfo extends SimpleBeanInfo
{
  // Methods
  public MethodDescriptor[] getMethodDescriptors();
}

This class provides specialized JavaBeans support for the ElementImpl class to resolve which overloaded functions are accessible through scripting.

SimpleBeanInfo
  |
  +--ElementImplBeanInfo

Methods

getMethodDescriptors

public MethodDescriptor[] getMethodDescriptors();

Returns the method descriptions for the methods that are to be made available through scripting.

Return Value:

Returns an array of MethodDescriptor objects.


Interface Element

public interface Element
{
  // Fields
  static public final int CDATA;
  static public final int COMMENT;
  static public final int DOCUMENT;
  static public final int DTD;
  static public final int ELEMENT;
  static public final int ELEMENTDECL;
  static public final int ENTITY;
  static public final int ENTITYREF;
  static public final int NAMESPACE;
  static public final int NOTATION;
  static public final int PCDATA;
  static public final int PI;

  // Methods
  public void addChild(Element elem, Element after);
  public void addChild(Element elem, int pos, int reserved);
  public Object getAttribute(String name);
  public Object getAttribute(Name n);
  public Enumeration getAttributes();
  public Element getChild(int index);
  public ElementCollection getChildren();
  public Enumeration getElements();
  public Element getParent();
  public Name getTagName();
  public String getText();
  public int getType();
  public int numAttributes();
  public int numElements();
  public void removeAttribute(String name);
  public void removeAttribute(Name name);
  public void removeChild(Element elem);
  public void save(XMLOutputStream o) throws IOException;
  public void setAttribute(String name, Object value);
  public void setAttribute(Name name, Object value);
  public void setParent(Element parent);
  public void setText(String text);
}

This interface implements an Element object. Each XML tag in a document is represented by an Element object in the XML parse tree. The elements are named with a string, have attributes, and can contain child nodes.

There are seven types of elements, DOCUMENT, ELEMENT, PCDATA, PI, META, COMMENT, and CDATA.

Methods

addChild

public void addChild(Element elem, Element after);

Adds a child to this element. Any element can only have one parent element and so the previous parent will lose this child from its subtree.

Return Value:

No return value.

Parameter | Description
elem | The element to add. The child element becomes the last element if after is null. The child is added to the beginning of the list if after is this object.
after | The element after which to add it.

addChild

public void addChild(Element elem, int pos, int reserved);

Adds a child to this element.

Return Value:

No return value.

Parameter | Description
elem | The element to add.
pos | The position to add this element (calling getChild(pos) will return this element). If pos is less than 0, elem becomes the new last element.
reserved | The reserved parameter.

getAttribute

public Object getAttribute(String name);

Retrieves an attribute's value given its name.

Return Value:

Returns the value of the attribute or null if the attribute is not found.

Parameter | Description
name | The name of the attribute.

getAttribute

public Object getAttribute(Name n);

Retrieves an attribute's value given its name.

Return Value:

Returns the value of the attribute or null if the attribute is not found.

Parameter | Description
name | The name of the attribute.

getAttributes

public Enumeration getAttributes();

Retrieves an enumeration for the element attributes. The enumeration returns Attribute objects.

Return Value:

Returns the enumeration. It must not return null (see EnumWrapper for returning empty enumerations).

See Also: Attribute

getChild

public Element getChild(int index);

Retrieves the child element by index.

Return Value:

Returns null if there is no child by that index.

Parameter | Description
index | The index of the child element.

getChildren

public ElementCollection getChildren();

Returns an element collection of the children of this element. It must not return null. See EnumWrapper for an emptyEnumeration.

Return Value:

Returns ElementCollection of child objects.

getElements

public Enumeration getElements();

Returns an enumeration of the children of this element. Enumeration.nextElement returns Element objects.

Return Value:

Returns an enumeration of child objects. It must not return null. See EnumWrapper for an easy way to return an empty enumeration.

getParent

public Element getParent();

Retrieves the parent of this element. Every element in the tree except the Document itself, has a parent.

Return Value:

Returns the parent element or null if at the root of the tree.

getTagName

public Name getTagName();

Retrieves the name of the tag as a string. The string will be in uppercase.

Return Value:

Returns the tag name or null for DATA and PCDATA elements.

getText

public String getText();

Returns the non-marked-up text contained by this element. For text elements, this is the raw data. For elements with child nodes, this traverses the entire subtree and appends the text for each terminal text element, effectively stripping out the XML markup for the subtree. For example, if the XML document contains the following: <xmp> <AUTHOR> <FIRST>William</FIRST> <LAST>Shakespeare</LAST> </AUTHOR> </xmp>

Document.getText returns "William Shakespeare".

getType

public int getType();

Retrieves the type of the element. This is always one of the following values: DOCUMENT, ELEMENT, PCDATA, PI, META, COMMENT, or CDATA.

Return Value:

Returns element type.

numAttributes

public int numAttributes();

Retrieves the number of attributes.

Return Value:

Returns the number of attributes.

numElements

public int numElements();

Retrieves the number of child elements.

Return Value:

Returns the number of child elements.

removeAttribute

public void removeAttribute(String name);

Deletes an attribute from an element.

Return Value:

No return value.

Parameter | Description
name | The attribute to delete.

removeAttribute

public void removeAttribute(Name name);

Deletes an attribute from an element.

Return Value:

No return value.

Parameter | Description
name | The attribute to delete.

removeChild

public void removeChild(Element elem);

Removes a child element from the tree.

Parameter | Description
elem | The element to remove.

save

public void save(XMLOutputStream o) throws IOException;

Saves this element.

Return Value:

No return value.

Parameter | Description
o | The output stream to save to.

Exceptions:

IOException if there is a problem saving the output.

setAttribute

public void setAttribute(String name, Object value);

Sets the attribute of this element.

Parameter | Description
name | The attribute name.
value | The attribute value.

setAttribute

public void setAttribute(Name name, Object value);

Sets the attribute of this element.

Parameter | Description
name | The attribute name.
value | The attribute value.

setParent

public void setParent(Element parent);

Sets the parent of this element.

Return Value:

No return value.

Parameter | Description
parent | The element to set as parent.

setText

public void setText(String text);

Sets the text for this element. Only meaningful in CDATA, PCDATA, and COMMENT nodes.

Return Value:

No return value.

Parameter | Description
text | The text to set.

Fields

CDATA
Raw character data specified with special CDATA construct: <![CDATA[...]]> where ... can be anything except ]]>, including HTML tags.
COMMENT
An XML comment ( <!-- ... --> ).
DOCUMENT
Reserved for use by the Document node only.
DTD
Reserved for use by the DTD node only.
ELEMENT
A general container element having optional attributes and optional child elements.
ELEMENTDECL
An element declaration node.
ENTITY
An entity node.
ENTITYREF
Entity reference nodes.
NAMESPACE
A namespace node that declares new namespaces in the element tree.
NOTATION
A notation node.
PCDATA
A text element that has no children or attributes and that contains parsed character data.
PI
A processing instruction node ( <? ... ?> ).


Interface ElementFactory

public interface ElementFactory
{
  // Methods
  Element createElement(int type, Name tag);
  void parsed(Element elem);
}

This interface specifies a method to create elements for an XML element tree. This is used by the XML Document to create nodes in the tree as it parses the elements.

Methods

createElement

Element createElement(int type, Name tag);

Creates an element with the specified tag for the specified type of element.

Return Value:

Returns the created element.

Parameter | Description
tag | The name of the element.
type | One of the predefined Element types that can be returned from Element.getType.

See Also: com.ms.xml.om.Element

parsed

void parsed(Element elem);

Notifies that the element is fully parsed.

Parameter | Description
elem | The element parsed.

See Also: com.ms.xml.om.Element


About com.ms.xml.parser

The com.ms.xml.parser package contains the Microsoft® XML Parser, which is a validating XML parser written in Java. The parser checks for well-formed documents and, optionally, permits checking of the documents' validity according to the Document Type Definition (DTD). This package is encapsulated by the Document class in the com.ms.xml.om package, so you shouldn't need to use this package directly.

Classes

Class ContentModel
This class represents the content model definition for a given XML element.
Class DTD
This class contains all the Document Type Definition (DTD) information for an XML document.
Class ElementDecl
The class represents an element declaration in an XML Document Type Definition (DTD).
Class Entity
This class implements an Entity object representing an XML internal or external entity as defined in the XML Document Type Definition (DTD).
Class Notation
This class implements an entity object representing an XML notation.
Class ParseException
This class signals that a parsing exception of some sort has occurred.
Class Parser
This class implements an eXtensible Markup Language (XML) parser according to the latest World Wide Web Consortium (W3C) working draft of the XML specification.

Hierarchy

Object
  |
  +--ContentModel
  |
  +--DTD
  |
  +--Parser

ElementImpl
  |
  +--ElementDecl
  |
  +--Entity
  |
  +--Notation

Exception
  |
  +--ParseException


Class ContentModel

public class ContentModel
{
  // Methods
  public void save(Name ns, XMLOutputStream o) throws IOException;
  public String toString();
}

This class represents the content model definition for a given XML element. The content model is defined in the element declaration in the Document Type Definition (DTD); for example, (a,(b|c)*,d). The content model is stored in an expression tree of Node objects for use by the XML parser during validation.

Methods

save

public void save(Name ns, XMLOutputStream o) throws IOException;

Saves the content model out to the specified stream.

Return Value:

No return value.

Parameter | Description
ns | The current name space context.
o | The output stream to write to.

Exceptions:

IOException if there was a problem writing to the output stream.

toString

public String toString();

Retrieves a string representation of the content type.

Return Value:

Returns a String.


Class DTD

public class DTD
{
  // Constructors
  public DTD();

  // Methods
  public final void addLoadedNameSpace(Name url);
  public final void addNameSpace(Name as, Name href);
  final public void clear();
  public final Enumeration elementDeclarations();
  public final ElementDecl findElementDecl(Name name);
  public final Entity findEntity(Name n);
  public final Name findLoadedNameSpace(Name url);
  public final Name findLongNameSpace(Name as);
  public final Notation findNotation(Name name);
  public final Name findShortNameSpace(Name href);
  final public Name getDocType();
  static public boolean isReservedNameSpace(Name n);
  final public void save(XMLOutputStream o) throws IOException;
}

This class contains all the Document Type Definition (DTD) information for an XML document.

Constructors

DTD

public DTD();

Creates a new empty DTD.

Methods

addLoadedNameSpace

public final void addLoadedNameSpace(Name url);

Adds a specified URL to the list of loaded namespaces.

Return Value:

No return value.

Parameter | Description
url | The long name for the namespace.

addNameSpace

public final void addNameSpace(Name as, Name href);

Adds a name pair (long name, short name) to the name space hashtable.

Return Value:

No return value.

Parameter | Description
as | The long name part of the namespace.
href | The short name part of the namespace.

clear

final public void clear();

Resets the DTD to its initial state.

Return Value:

No return value.

elementDeclarations

public final Enumeration elementDeclarations();

Retrieves an object for enumerating the element declarations.

Return Value:

Returns an Enumeration object that returns ElementDecl objects when enumerated.

findElementDecl

public final ElementDecl findElementDecl(Name name);

Finds an element declaration for the given tag name.

Return Value:

Returns the element declaration object.

Parameter | Description
name | The tag name.

findEntity

public final Entity findEntity(Name n);

Finds a named entity in the DTD.

Return Value:

Returns the specified Entity object; returns null if it is not found.

Parameter | Description
n | The name of the entity.

findLoadedNameSpace

public final Name findLoadedNameSpace(Name url);

Determines whether the specified URL is already a loaded namespace so that the caller can decide not to load it again.

Return Value:

Returns true if it is already loaded; otherwise, returns false.

Parameter | Description
url | The long name for the namespace.

findLongNameSpace

public final Name findLongNameSpace(Name as);

Retrieves the long name of a specified namespace.

Return Value:

Returns the long name; returns null if it is not found.

Parameter | Description
as | The short name of the namespace.

findNotation

public final Notation findNotation(Name name);

Retrieves the named XML notation in the DTD.

Return Value:

Returns the Notation object; returns null if it is not found.

Parameter | Description
name | The name of the notation.

findShortNameSpace

public final Name findShortNameSpace(Name href);

Retrieves the short name of a specified namespace.

Return Value:

Returns the short name; returns null if it is not found.

Parameter | Description
href | The long name of the namespace.

getDocType

final public Name getDocType();

Retrieves the name specified in the DOCTYPE tag.

Return Value:

Returns the name of the document type.

isReservedNameSpace

static public boolean isReservedNameSpace(Name n);

Determines if the given namespace is reserved.

Return Value:

Returns true if reserved; otherwise, returns false.

Parameter | Description
n | The namespace to verify.

save

final public void save(XMLOutputStream o) throws IOException;

Saves the DTD information to the given XML output stream.

Return Value:

No return value.

Parameter | Description
o | The output stream to write to.

Exceptions:

IOException if there are problems writing to the output stream.


Class ElementDecl

public class ElementDecl extends ElementImpl
{
  // Methods
  public final AttDef findAttDef(Name name);
  public final ContentModel getContent();
  public final Name getName();
  public void save(XMLOutputStream o) throws IOException;
}

The class represents an element declaration in an XML Document Type Definition (DTD).

ElementImpl
  |
  +--ElementDecl

Methods

findAttDef

public final AttDef findAttDef(Name name);

Retrieves the attribute definition of the named attribute.

Return Value:

Returns an attribute definition object; returns null if it is not found.

Parameter | Description
name | The name of the attribute.

getContent

public final ContentModel getContent();

Retrieves the content model object for the element declaration.

Return Value:

Returns the content model for the element.

getName

public final Name getName();

Retrieves the name of the element declaration.

Return Value:

Returns the Name object containing the element declaration name.

save

public void save(XMLOutputStream o) throws IOException;

Saves the element declaration in DTD syntax to the given output stream.

Return Value:

No return value.

Parameter | Description
o | The output stream to write to.

Exceptions:

IOException if there is a problem writing to the output stream.


Class Entity

public class Entity extends ElementImpl
{
  // Constructors
  public void saveEntity(XMLOutputStream o) throws IOException;

  // Methods
  public Name getName();
  public void save(XMLOutputStream o) throws IOException;
  public void setText(String text);
}

This class implements an Entity object representing an XML internal or external entity as defined in the XML Document Type Definition (DTD).

ElementImpl
  |
  +--Entity

Constructors

saveEntity

public void saveEntity(XMLOutputStream o) throws IOException;

Saves the entity to the given output stream.

Parameter | Description
o | The output stream.

Exceptions:

IOException if there is a problem writing to the output stream.

Methods

getName

public Name getName();

Retrieves the name of the entity.

Return Value:

Returns the Name object containing the entity name.

save

public void save(XMLOutputStream o) throws IOException;

Saves the entity to the given output stream with indenting and new lines.

Parameter | Description
o | The output stream.

Exceptions:

IOException if there is a problem writing to the output stream.

setText

public void setText(String text);

Changes the text of entity.

Parameter | Description
text | The new text of the entity.


Class Notation

public class Notation extends ElementImpl
{
  // Methods
  public void save(XMLOutputStream o) throws IOException;
}

This class implements an entity object representing an XML notation.

ElementImpl
  |
  +--Notation

Methods

save

public void save(XMLOutputStream o) throws IOException;

Saves the notation to the given output stream with indenting and new lines.

Parameter | Description
o | The output stream.

Exceptions:

IOException if there is a problem writing to the output stream.


Class ParseException

public class ParseException extends Exception
{
  // Fields
  public int column;
  public int line;
  public Object owner;

  // Constructors
  public ParseException();
  public ParseException(String s);
  public ParseException(String s, int line, int column,
        Object owner);
}

This class signals that a parsing exception of some sort has occurred.

Exception
  |
  +--ParseException

Constructors

ParseException

public ParseException();

Constructs a ParseException exception with no detail message.

ParseException

public ParseException(String s);

Constructs a ParseException exception with a specified message.

Parameter | Description
s | The detail message.

ParseException

public ParseException(String s, int line, int column, Object owner);

Constructs a ParseException exception with detail about what occurred.

Parameter | Description
s | The detail message.
line | The line number of the input where the error was found.
column | The position on the line.
owner | The context in which the error was encountered. This is either an Entity object or a Parser object.

Fields

column
The position on the line where the error was found.
line
The line where the error was found.
owner
The parser context in which the error occurred.


Class Parser

public class Parser
{
  // Constructors
  public Parser();

  // Methods
  public final XMLOutputStream createOutputStream(OutputStream out);
  public final void parse(URL url, ElementFactory factory, DTD dtd,
        Element root) throws ParseException;
  final public void parse(InputStream in, ElementFactory factory,
        DTD dtd, Element root) throws ParseException;
  final public void report(ParseException e, OutputStream out);
}

This class implements an eXtensible Markup Language (XML) parser according to the latest World Wide Web Consortium (W3C) working draft of the XML specification. This parser class is used internally by the XML document load method, so you shouldn't need to use it directly.

Constructors

Parser

public Parser();

Creates a new parser object.

Methods

createOutputStream

public final XMLOutputStream createOutputStream(OutputStream out);

Creates an output stream that best matches the XML data format found during parsing. For example, this will match big endian or little endian XML data formats.

Return Value:

Returns an XMLOutputStream object that uses the newline separator defined by the system property "line.separator".

Parameter | Description
out | The output stream.

parse

public final void parse(URL url, ElementFactory factory, DTD dtd,
        Element root) throws ParseException;

Parses the XML document pointed to by the given URL and creates the corresponding XML document hierarchy.

Return Value:

No return value.

Parameter | Description
url | The URL address of the XML document to parse.
factory | The element factory used to create XML Element objects during parsing.
dtd | The object that the parser stores DTD information in.
root | The starting root node to which children are added during parsing.

Exceptions:

com.ms.xml.parser.ParseException if syntax or other errors are encountered.

parse

final public void parse(InputStream in, ElementFactory factory, DTD dtd,
        Element root) throws ParseException;

Parses the XML from the given input stream.

Return Value:

No return value.

Parameter | Description
in | The input stream containing XML data to parse.
factory | The element factory used to create XML Element objects during parsing.
dtd | The object that the parser stores DTD information in.
root | The starting root node to which children are added during parsing.

Exceptions:

com.ms.xml.parser.ParseException if syntax or other errors are encountered.

report

final public void report(ParseException e, OutputStream out);

Reports errors to the specified output stream including parsing context and stack trace where the error occurred.

Return Value:

No return value.

Parameter | Description
e | The exception to report.
out | The output stream to write the report to.


About com.ms.xml.util

This package provides base classes for Microsoft XML object technology, including input and output stream objects specifically designed for XML.

Classes

Class Attribute
This class encapsulates an XML Name and value pair.
Class Attributes
This class encapsulates a list of Attribute objects.
Class EnumWrapper
This class is a simple implementation of the Enumeration interface.
Class Name
This class represents a general-purpose Name object, and is used for efficient sharing of duplicate strings in the system.
Class QualifiedName
This class represents a QualifiedName object, and is used for efficient sharing of duplicate strings in the system.
Class ReadOnlyAttributes
This class encapsulates a read-only list of Attribute objects.
Class XMLInputStream
This class is an input stream reader, specifically designed to handle different encoding formats as well as liitle endian files.
Class XMLOutputStream
This class is an output stream writer specifically designed for XML, including XML encoding as well as little endian files, XML namespaces, and white-space handling.

Hierarchy

Object
  |
  +--ReadOnlyAttributes
  |  |
  |  +--Attributes
  |
  +--EnumWrapper (Enumeration)
  |
  +--Name
  |  |
  |  +--QualifiedName
  |
  +--Attribute

OutputStream
  |
  +--XMLOutputStream

InputStream
  |
  +--XMLInputStream


Class Attribute

public class Attribute
{
  // Constructors
  public Attribute();
  public Attribute(Name n, Object v);

  // Methods
  public Name getName();
  public Object getValue();
}

This class encapsulates an XML Name and value pair.

Constructors

Attribute

public Attribute();

Constructs an uninitialized Attribute.

Attribute

public Attribute(Name n, Object v);

Constructs an Attribute with given Name and associated value object.

Parameter | Description
n | The name of the Attribute pair.
v | The value object to associate with the name.

Methods

getName

public Name getName();

Retrieves the Name of the Attribute object.

Return Value:

Returns the name of the Attribute.

getValue

public Object getValue();

Retrieves the value object of the Attribute.

Return Value:

Returns the value of the Attribute.


Class Attributes

public class Attributes extends ReadOnlyAttributes
{
  // Constructors
  public Attributes();
  public Attributes(int elems);
  public Attributes(ReadOnlyAttributes attrs);
  public Attributes(Vector v);

  // Methods
  public Object put(Attribute v);
  public Object put(Name name, Object value);
  public void remove(Name name);
  public void removeAll();
}

This class encapsulates a list of Attribute objects.

ReadOnlyAttributes
  |
  +--Attributes

Constructors

Attributes

public Attributes();

Constructs an empty Attribute collection.

Attributes

public Attributes(int elems);

Constructs an empty Attrribute collection of a specified size. If you add more Attribute objects to it than the initially specified size, the collection grows automatically.

Parameter | Description
elems | The number of Attributes to initially reserve space for in the collection.

Attributes

public Attributes(ReadOnlyAttributes attrs);

Constructs a collection of Attribute objects from an existing collection of read-only Attribute objects.

Parameter | Description
attrs | A read-only Attribute collection used to create the new Attributes object.

Attributes

public Attributes(Vector v);

Constructs an empty collection of Attribute objects using the specified Vector.

Parameter | Description
v | The vector to use for the Attribute collection.

Methods

put

public Object put(Attribute v);

Adds an Attribute Name and value pair to the collection, or replaces the value for the named Attribute if it is already present in the collection.

Return Value:

Returns null if the Attribute was added to the collection, or returns the previous value of the Attribute if the value was replaced.

Parameter | Description
v | The Attribute to add. If the Attribute is already present in the collection, its current value is replaced with that in the value parameter.

put

public Object put(Name name, Object value);

Adds an Attribute Name and value pair the the collection, or replaces the value for the named Attribute if it is already present in the collection.

Return Value:

Returns null if the Attribute was added to the collection, or returns the previous value of the Attribute if the value was replaced.

Parameter | Description
name | The Name of the Attribute to add. If the Attribute is already present in the collection, its current value is replaced with that in the value parameter.
value | The object to associate with the Attribute.

remove

public void remove(Name name);

Removes the named Attribute from the collection.

Return Value:

No return value.

Parameter | Description
name | The Name of the Attribute to remove from the collection.

removeAll

public void removeAll();

Removes all Attributes from the collection and sets the collection's size to zero.

Return Value:

No return value.


Class EnumWrapper

public class EnumWrapper implements Enumeration
{
  // Constructors
  public EnumWrapper(Object o);

  // Methods
  public boolean hasMoreElements();
  public Object nextElement();
}

This class is a simple implementation of the Enumeration interface. The EnumWrapper object generates a list of objects and accesses them through calls to the nextElement method.

Constructors

EnumWrapper

public EnumWrapper(Object o);

Constructs an EnumWrapper from the specified base object.

Parameter | Description
o | The object to create the EnumWrapper object from.

Methods

hasMoreElements

public boolean hasMoreElements();

Determines if there are elements remaining in the Enumeration.

Return Value:

Returns true if the EnumWrapper contains more elements; otherwise, returns false.

nextElement

public Object nextElement();

Retrieves the next object in the enumeration.

Return Value:

Returns the next object in the enumeration.


Class Name

public class Name
{
  // Methods
  public static Name create(String s);
  public boolean equals(Object that);
  public int hashCode();
  public String toString();
}

This class represents a general-purpose Name object, and is used for efficient sharing of duplicate strings in the system.

Methods

create

public static Name create(String s);

Constructs a Name object for an XML Attribute using the given string.

Parameter | Description
s | The String object with which to create the Name. The string is case sensitive.

equals

public boolean equals(Object that);

Determines whether the current Name object is equal to the one passed in the that parameter.

Return Value:

Returns true if the objects are equal; otherwise, returns false.

Parameter | Description
that | The object with which to compare the Name object.

hashCode

public int hashCode();

Retrieves the hash code for the Name. A global hash table of all Name objects that have been constructed is used to share duplicate strings.

Return Value:

Returns the hash code for the Name.

toString

public String toString();

Retrieves a String representation of the class name of the Name object.

Return Value:

Returns the class name of the Name object.


Class QualifiedName

public class QualifiedName extends Name
{
  // Methods
  public static QualifiedName create(Name name, Name nameSpace);
  public boolean equals(Object that);
  public Name getName();
  public Name getNameSpace();
  static public Name getNameSpace(Name n);
  public void save(XMLOutputStream o);
  public String toString();
}

This class represents a QualifiedName object and is used for efficient sharing of duplicate strings in the system. A QualifiedName is a combination of a Name and an associated namespace.

Name
  |
  +--QualifiedName

Methods

create

public static QualifiedName create(Name name, Name nameSpace);

Creates a QualifiedName object for the given Name and namespace. QualifiedName objects are case sensitive.

Return Value:

Returns a QualifiedName object that is constructed with the given parameters.

Parameter | Description
name | The Name of the QualifiedName object.
nameSpace | The namespace of the QualifiedName object.

equals

public boolean equals(Object that);

Determines whether the current QualifiedName object is equal to the one passed in the that parameter.

Return Value:

Returns true if the objects are equal; otherwise, returns false.

Parameter | Description
that | The object with which to compare the QualifiedName object.

Overrides:

equals(Object) in Name.

getName

public Name getName();

Retrieves the Name component of the QualifiedName object.

Return Value:

Returns the Name.

getNameSpace

public Name getNameSpace();

Retrieves the namespace component that the QualifiedName object is created with.

Return Value:

Returns the namespace.

getNameSpace

static public Name getNameSpace(Name n);

Retrieves the global namespace for the given Name object if that Name object is a valid QualifiedName.

Return Value:

Returns the namespace of the specified Name object; returns null if the Name object is not valid.

Parameter | Description
n | The Name object for which to retrieve the namespace.

save

public void save(XMLOutputStream o);

Writes the QualifiedName (Name and its associated namespace) to an XMLOutputStream object.

Return Value:

No return value.

Parameter | Description
o | The output stream to write the data to.

toString

public String toString();

Retrieves a String representation of the class name for the QualifiedName object.

Return Value:

Returns the class name of the QualifiedName object.

Overrides:

toString() in Name.


Class ReadOnlyAttributes

public class ReadOnlyAttributes
{
  // Constructors
  public ReadOnlyAttributes();
  public ReadOnlyAttributes(Vector v);
  public ReadOnlyAttributes(int elems);

  // Methods
  public Enumeration attributes();
  public Object get(Name name);
  public Attribute lookup(Name name);
  public int size();
  public String toString();
}

This class encapsulates a read-only list of Attribute objects.

Constructors

ReadOnlyAttributes

public ReadOnlyAttributes();

Constructs an empty read-only Attribute collection.

ReadOnlyAttributes

public ReadOnlyAttributes(Vector v);

Constructs a read-only collection of Attribute objects using the given Vector of Attributes.

Parameter | Description
v | The Vector that contains the Attribute objects.

ReadOnlyAttributes

public ReadOnlyAttributes(int elems);

Constructs an empty Attribute collection of the specified size. If you add more Attribute objects to the collection than the initially specified size, it grows automatically.

Parameter | Description
elems | The number of Attribute objects to initially reserve space for in the collection.

Methods

attributes

public Enumeration attributes();

Retrieves an Enumeration of the Attribute objects in the collection.

Return Value:

Returns an Enumeration of the Attribute objects in the collection.

get

public Object get(Name name);

Retrieves the named Attribute object and returns its associated value.

Return Value:

Returns an object that is the associated value for the named Attribute.

Parameter | Description
name | A Name object that identifies the Attribute to retrieve.

lookup

public Attribute lookup(Name name);

Cycles through the collection of Attribute objects and retrieves the named Attribute, if it is present.

Return Value:

Returns the named Attribute; returns null if the Attribute is not currently included in the collection.

Parameter | Description
name | The Name of the Attribute to retrieve.

size

public int size();

Retrieves the number of Attribute Name and value pairs currently in the collection.

Return Value:

Returns the number of pairs in the collection.

toString

public String toString();

Retrieves a String representation of the class name of the ReadOnlyAttributes object.

Return Value:

Returns the class name for the ReadOnlyAttributes object.


Class XMLInputStream

public class XMLInputStream extends InputStream
{
  // Constructors
  public XMLInputStream( InputStream in );

  // Methods
  public XMLOutputStream createOutputStream( OutputStream out );
  public int read() throws IOException;
  public void setEncoding( String encoding ) throws IOException;
}

This class is an input stream reader, specifically designed to handle different encoding formats and little endian files.

InputStream
  |
  +--XMLInputStream

Constructors

XMLInputStream

public XMLInputStream( InputStream in );

Constructs an XMLInputStream object from an InputStream. The first four bytes of the InputStream are read to determine the character encoding of the file. The XMLInputStream object does not ensure that the input stream follows the XML standard, and expects any non-UTF-8 file to begin with a <?XML> tag.

Parameter | Description
in | The input stream to base the XMLInputStream object on.

Methods

createOutputStream

public XMLOutputStream createOutputStream( OutputStream out );

Constructs an XMLOutputStream with the appropriate initial state. XMLOutputStream objects should always be created using this method for the output stream to mimic the input stream.

Return Value:

Returns a correctly initilized XMLOutputStream for use with the current XMLInputStream.

Parameter | Description
out | The output stream to base the XMLOutputStream object on.

read

public int read() throws IOException;

Retrieves the next unicode character in the input stream. The read operation performed depends on the current read state.

Return Value:

Returns the next unicode character in the stream.

Exceptions:

IOException if an I/O error occurs.

setEncoding

public void setEncoding( String encoding ) throws IOException;

Defines the character encoding of the input stream.

Return Value:

No return value.

Parameter Description
encoding The type of character encoding. This may be one of the following formats:
  • UTF-8
  • Shift_JIS
  • ISO-8859-1
  • ISO-10646-UCS-4 (not yet supported)
  • ISO-10646-UCS-2 or UCS-2

The default character encoding is ASCII.

Remarks:

The character encoding must agree with the encoding determined by the constructer. The setEncoding method is used to clarify encodings that are not fully determinable by reading the first four bytes in a stream. The method is not used to change the encoding of a stream. This method must be called within 4096 read() operations after the XMLInputStream object's creation.

Exceptions:

IOException if the encoding type is not supported by the currently installed virtual machine.


Class XMLOutputStream

In this topic

* Constructors

* Methods

* Fields

Packages
 Previous This Package
Package com.ms.xml.util Previous This
Package

Class XMLOutputStream

public class XMLOutputStream extends OutputStream
{
  // Fields
  public static int COMPACT;
  public static int PRETTY;

  // Constructors
  public XMLOutputStream( OutputStream out );

  // Methods
  public void addIndent(int offset);
  public void close() throws IOException;
  public void flush() throws IOException;
  public int getOutputStyle();
  public void setEncoding( String encoding, boolean littleendian,
        boolean byteOrderMark ) throws IOException;
  public void setOutputStyle(int style);
  public void write( int c ) throws IOException;
  public void writeChars( String str ) throws IOException;
  public void writeIndent() throws IOException;
  public void writeNewLine() throws IOException;
  public void writeQualifiedName(Name n, Name ns) throws IOException;
  public void writeQuotedString( String str ) throws IOException;
}

This class is an output stream writer that is specifically designed for XML including XML encoding, little endian files, XML namespaces, and white-space handling.

OutputStream
  |
  +--XMLOutputStream

Constructors

XMLOutputStream

public XMLOutputStream( OutputStream out );

Constructs the XMLOutputStream object as a standard UTF-8 output stream. A subsequent call to the setEncoding method will specify the correct character encoding that is required. Create an XMLOutputStream by using the createOutputStream method of the XMLInputStream class.

Parameter | Description
out | An output stream to use to create the XMLOutputStream.

Methods

addIndent

public void addIndent(int offset);

Sets the relative indentation level (for example, addIndent(+1) or addIndent(-1)). The indent level controls what the writeIndent writes.

Return Value:

No return value.

Parameter | Description
offset | A signed value for the indentation level.

close

public void close() throws IOException;

Closes the XMLOutputStream and frees any system resources that are associated with the stream.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurs.

flush

public void flush() throws IOException;

Flushes the XMLOutputStream.

Return Value:

No return value.

Exceptions:

IOException if an I/O error occurred.

getOutputStyle

public int getOutputStyle();

Retrieves the current output style for the output stream.

Return Value:

Returns either the COMPACT or the PRETTY output style.

setEncoding

public void setEncoding( String encoding, boolean littleendian,
        boolean byteOrderMark ) throws IOException;

Defines the character encoding of the output stream.

Return Value:

No return value.

Parameter | Description
encoding The type of character encoding. This may be one of the following formats:
  • UTF-8
  • Shift_JIS
  • ISO-8859-1
  • ISO-10646-UCS-4 (not yet supported)
  • UCS-2

The default character encoding is ASCII.

littleendian | Set this parameter to true to specify whether the stream is in little endian format.
byteOrderMark | This flag is only relevant if the character encoding type is UCS-2. Otherwise, it is ignored.

Exceptions:

IOException if the encoding type is not supported by the currently installed virtual machine.

setOutputStyle

public void setOutputStyle(int style);

Sets the output style for the output stream.

Return Value:

No return value.

Parameter | Description
style | The output style. This can be either PRETTY or COMPACT.

write

public void write( int c ) throws IOException;

Writes a character to the output stream according to the current write state. In order to avoid an extra conditional in every UCS-2 write, an extra state for a UCS-2 write operation that requires a ByteOrderMark is used. The ByteOrderMark is written only once at the beginning of the file.

Return Value:

No return value.

Parameter | Description
c | The character to write to the output stream.

Exceptions:

IOException if there was an error writing to the stream.

writeChars

public void writeChars( String str ) throws IOException;

Writes the given string to the output stream.

Return Value:

No return value.

Parameter | Description
str | The String to write to the output stream.

Exceptions:

IOException if there was an error writing to the output stream.

writeIndent

public void writeIndent() throws IOException;

Writes the appropriate indent, according to the indentation level that is specified by the addIndent method. If the output style is COMPACT, the method performs no operation.

Return Value:

No return value.

Exceptions:

IOException if there was an error writing to the output stream.

writeNewLine

public void writeNewLine() throws IOException;

Writes a new line. If the output style is COMPACT, the method performs no operation.

Return Value:

No return value.

Exceptions:

IOException if there was an error writing to the output stream.

writeQualifiedName

public void writeQualifiedName(Name n, Name ns) throws IOException;

Writes out the fully qualified name, using the appropriate short name syntax.

Return Value:

No return value.

Parameter | Description
n | The Name being written.
ns | The namespace that defines the context in which the name was defined.

Exceptions:

IOException if there was an error writing to the stream.

writeQuotedString

public void writeQuotedString( String str ) throws IOException;

Writes out the string enclosed in quotation marks. This method uses quotation marks that are appropriate for the string (for example, if a string contains a single quotation mark ('), the method uses a double quotation mark ("), and so on).

Return Value:

No return value.

Parameter | Description
str | The String to write to the output stream.

Fields

COMPACT
An ouput style that specifies that no newline characters or tabs are used in the output stream.
PRETTY
The default output style. Newlines and tabs are used when writing to the output stream.


About com.ms.vm

This package provides a class that implements a weak reference to an object. A weak reference tracks an object without preventing it from being garbage collected.

Classes

Class WeakReference
This class implements a weak reference to an object.

Hierarchy

Object
  |
  +--WeakReference


Class WeakReference

public class WeakReference
{
  // Constructors
  public WeakReference(Object referent);

  // Methods
  public void finalize();
  public Object getReferent();
  public void setReferent(Object object);
}

This class implements a weak reference to an object. A weak reference tracks an object without preventing it from being garbage-collected.

Constructors

WeakReference

public WeakReference(Object referent);

Constructs a weak reference to a specified object.

Parameter | Description
referent | The object to track.

Methods

finalize

public void finalize();

Finalizes the weak reference instance. The referent is no longer tracked.

Return Value:

No return value.

getReferent

public Object getReferent();

Retrieves the current object being tracked.

Return Value:

Returns the object being tracked; returns null if the object was collected.

setReferent

public void setReferent(Object object);

Sets the current object being tracked.

Return Value:

No return value.

Parameter | Description
object | The object being tracked, or null if the object was collected.


Security Articles and References

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Security | Welcome! | Next
 | Welcome! | Next

Security Articles and References

Trust-based security for Java is a cross-platform security model that provides fine-grained administration of the permissions granted to Java applets and libraries. This security system provides intermediate levels of trust so that Java applications can be given some additional permissions without being offered unlimited access to every permission in the system.

Articles

The following articles provide an overview of the security model for Java classes that is supported by Internet Explorer 4.0, and also provide information on signing your code to work with that security model:

  • Trust-Based Security for Java
  • Signing Cabinet Files with Signcode

Reference

The following packages enable control over security features:

  • Package com.ms.security
  • Package com.ms.security.auditing
  • Package com.ms.security.permissions


Internationalization Articles and References

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Internationalization | Welcome! | Next
 | Welcome! | Next

Internationalization Articles and References

Java was designed to support internationalization—its primitive character type is based on Unicode, which is an international standard for encoding written language elements. The Microsoft SDK for Java enhances the internationalization features of Java with support for local character set encoding, Microsoft® Win32® resources, locales, vertical writing, and Java-based input method editors (IMEs).

Articles

The Internationalization article provides a comprehensive overview of the internationalization support in the SDK for Java.

The LCID reference lists Win32 LCID values used for localization of resources.

References

Enhanced internationalization support is provided by the following Microsoft packages:
Package com.ms.ui.resource | Provides support for using Win32 resources in Java applications.
Package com.ms.lang | Includes the SystemX class that provides system-level internationalization services, such as managing IMEs and converting strings between local code pages and Unicode.
Package com.ms.util.InputMethod | Provides support for creating Java-based IMEs.
Package java.util | Includes the java.util.Locale class, with additional locales and methods for retrieving the Win32 locale identifiers and code pages.


Introduction

In this topic

* Creating Multilingual Java Applications using Win32 Resources

* Using Multilingual Java Applications with Win32 Resources

* Enhanced Locale Support

* Vertical Writing Support

* Input Method Editors

* Unicode Support

Internationalization | Previous | Int. | Next
 | Previous | Int. | Next

Introduction

The global connectivity provided by the Internet will increase the demand for internationalized software products and place additional requirements on internationalized applications. For example, applications that are delivered and run over the Internet may need to adapt to the user's language at run time. Other applications will need to be multilingual and support a combination of different languages. Java was designed to support internationalization—its primitive character type is based on Unicode, an international standard for encoding written language elements. The Microsoft SDK for Java enhances the internationalization features of Java with support for local character set encoding, Microsoft® Win32® resources, locales, vertical writing, and Java-based input method editors (IMEs).

Enhanced internationalization support is provided by the following Microsoft packages:

  • Package com.ms.ui.resource provides support for using Win32 resources in Java applications.
  • Package com.ms.lang includes the SystemX class that provides system-level internationalization services, such as managing IMEs and converting strings between local code pages and Unicode.
  • Package com.ms.util.InputMethod provides support for creating Java-based IMEs.
  • Package com.ms.fx provides FxFormattedText, the standard text layout class, for vertical writing in Far Eastern languages.

In addition to the enhanced support provided by the packages in the preceding list, the Microsoft Win32 VM for Java (Microsoft VM) includes fully functional versions of the java.lang.Runtime methods getLocalizedInputStream and getLocalizedOutputStream.

Creating Multilingual Java Applications using Win32 Resources

Resources are used to isolate text and user interface elements, such as menus and dialog boxes, from the executable part of an application. Although the advantages of using resources apply to all applications, resources are particularly useful in applications requiring internationalization. Resource files can be localized and tested without having to rebuild an entire application. Using resources also decreases size and shortens load time for .class files, as they are not implemented with large amounts of static data.

The Microsoft SDK for Java supports a compact resource format. The com.ms.ui.resource.ResourceDecoder class is an extensible class designed to load resources from a binary file. The com.ms.ui.resource.Win32ResourceDecoder class reads resources in the Win32 resource format. This class also provides methods for accessing the individual resource elements within a resource file. This enables you to use existing resource files with Java applications and to use familiar tools and processes to create and localize new resources.

One problem with current development tools is that they are not necessarily capable of modifying resources in multiple languages within the same file. For example, a common problem is merging Far Eastern language resources with Western ones due to operating system limitations. The Microsoft SDK for Java includes the resmerge utility to address this problem. It enables you to develop resources separately, and then combine resources for different languages into one .res file. When you load Win32 resources from these combined resource files, you can specify the combined resource file as a source, and the language of the resource (the LCID) that you want to load.

There are four steps used in creating a Java application that uses localized resources.

  1. Develop the application.
    • Design your application so that you don't set fonts for resources you are loading. The Microsoft VM for Java automatically assigns default system fonts for loaded resources.
    • Make sure you take multilingual requirements (vertical writing, and so on) into account and set the size for GUI elements (for example, dialog boxes) accordingly.
  2. Create the resource files, and localize them with existing resource localization tools.
  3. Merge the localized resource files using the resmerge utility, if necessary.
  4. Use the Win32ResourceDecoder class to access and load localized resources from your Java application.

For example, if you wanted to be able to load both a Chinese and an English string resource, you would first develop these two resources, and then combine them using resmerge.

C:\..\>resmerge -a resources.res MyProjResUS.res MyProjResJP.res

Using Multilingual Java Applications with Win32 Resources

Using Win32 resources in an application is easy. You link to the file and extract the resource using the Win32ResourceDecoder. For example, to populate a panel with localizable controls, you create a resource file that contains dialog resources with the controls laid out as you want them. Execute the following code at run time:

public void populate(UIPanel p, int id)
{
    Win32ResourceDecoder res=new Win32ResourceDecoder("resources.res");
    try
    {
        res.populateDialog(p, id);
    }
    catch (Exception e)
    {
        System.out.println("Problem "+e);
    }
}

Note that a locale identifier (LCID) is not used because you will typically load the resources in the language the user needs. However, you can specify a language for any resource by adding the LCID to the method call. For example, an English/Greek dictionary would specify that the list of translated words be loaded in those languages, even if the application is currently being used by someone in Germany, and if all the rest of the user interface is in German.

Note Using Win32 resources allows you to localize your Java applications, without giving your Java source code to localization translators. This way, there will be no confusion between literal text strings and text that should be localized.

Enhanced Locale Support

The Microsoft VM includes the following enhancements to the Locale class to support internationalization.

  • Locale support for all locales supported by Win32. This enhancement adds more than forty locales to the locales supported by JDK 1.1, including locales that use vertical writing (for example, Locale.JAPANESE_VERTICAL).
  • A new method, getLCID, to get the locale identifier.
  • A new method, getCodePage, to get the code page associated with a locale.

Vertical Writing Support

Traditional Chinese and Japanese texts are written vertically—characters appear in a vertical line from the top to the bottom of the page, with lines progressing from the right to the left side of the page. The Microsoft VM supports vertical writing with the FxFormattedText class. There are two ways to specify that the text for an FxFormattedText buffer be written vertically:

  • Use the setLocale method to set the locale to a locale that uses vertical writing. Locales that use vertical writing are Locale.TRADITIONAL_CHINESE_VERTICAL, Locale.SIMPLIFIED_CHINESE_VERTICAL, Locale.KOREAN_VERTICAL, and Locale.JAPANESE_VERTICAL.
  • Use the setTextDirection method to set the text direction to top-to-bottom, and right-to-left (FxFormattedText.tdTB_RL).

The following sample code implements a panel that contains vertical writing.

class VerticalWritingSample extends UIPanel
{
    FxFormattedText fxft;

    public VerticalWritingSample ()
    {
        fxft = new FxFormattedText ("Vertical Text!");
        fxft.setLocale (Locale.JAPANESE_VERTICAL);
    }

    public void paint (FxGraphics g)
    {
        fxft.paint (g);
    }
}

Note When written vertically, characters are rotated 90 degrees (clockwise). This rotation is in accordance with the conventions of vertical writing for traditional Chinese and Japanese texts.

Input Method Editors

An input method editor (IME) is a program that allows computer users to enter complex characters and symbols, such as Japanese Kanji characters, by using a standard keyboard. Internationalized versions of Microsoft® Windows® provide native system IMEs for locales with languages using non-Latin alphabets (for example, Japanese, Korean, Traditional Chinese, and Simplified Chinese). The Microsoft VM provides IME support for Java applications with an Input Method Manager (IMM) that hosts Java-based IMEs, as well as native system IMEs.

Native System IMEs

The Microsoft VM supports existing native system IMEs interchangeably with Java-based IMEs. However, there are some limitations associated with using system IMEs. You can use a Java-based IME on any system, regardless of what language the system is localized for as long as the Microsoft VM is installed. With native system IMEs, however, you are limited to IMEs supported by the host system.

Java-Based IMEs

The Microsoft VM for Java fully supports IMEs written in the Java language. Java-based IMEs provide more flexibility and control for applications than native system IMEs. The following is a summary of the features of Java-based IMEs.

Feature | Description
Unicode-based | Java IMEs can be used with any version of Microsoft Windows.
Cross-platform | Java IMEs will run on any system that has the Microsoft VM installed.
Multilingual | Java IMEs for different languages can be activated concurrently by a single Java application (provided the proper fonts are installed on the user's system).
Web-downloadable | Java IMEs can be packaged and downloaded with applets or downloaded at the discretion of the user.
Managed by the application | Applications can control Java IME interface elements such as composition, status, and candidate windows.
Secure | Java IMEs follow normal Java security rules and run in the "sandbox" with Java applications.

Writing a Java-Based Input Method Editor

The com.ms.util.InputMethod package contains the following classes for creating Java-based IMEs.

  • The IMECompositionMessage class represents messages sent to the composition window of an IME.
  • The IMENotifyMessage class represents messages sent to an IME to notify it to perform an action on the status or candidate windows.
  • The InputMethodCallback class is an interface class that enables an IME to return composed characters and messages to the IMM.
  • The InputMethodListener class is an interface class that IMEs must implement to be used with the IMM.

Note The Microsoft SDK for Java includes a sample application, SampleIME, that illustrates how to write a simple, Java-based IME.

Handling Keystrokes

Keystrokes are passed from the Microsoft VM to the IMM, which routes them to the IME. To receive keystrokes, the IME must override the InputMethodListener.handledKey method. The imeCallback parameter in InputMethodListener.handledKey specifies an InputMethodCallback object that allows the IME to send messages back to the Microsoft VM. When composition is complete, the IME should use the InputMethodCallback.handleIMEChar method to return the composed Unicode character to the Microsoft VM.

Note Keystrokes are represented by virtual key codes defined by the KeyEvent class in the java.awt.event package. Keyboard state codes (ALT, CTRL, SHIFT, and so on) are defined in the InputManagerListener class.

Using IMEs with Java Applications

You don't have to do anything special with your Java application to use native system IMEs. If a native system IME is present on a system running the Microsoft VM, it will correctly process and route IME-composed strings to the application.

If you want to use a Java-based IME with your application, you'll need to use the IMM to activate the IME that you want to use. The following list shows the classes you use to work with the IMM.

  • The SystemX class (in the com.ms.lang package) enables you to get and set the default IMM provided by the Microsoft VM.
  • The InputManagerListener class (in the com.ms.util.InputMethod package) is an interface class that includes methods for managing IMEs.

You must set the current IMM before activating an IME. The following code shows how to set the default IMM and install an IME.

InputManagerListener imm;
MyIME ime;

// Set default IMM
imm = com.ms.lang.SystemX.getDefaultInputManager ();
com.ms.lang.SystemX.setInputManager (imm, true);
if (imm != null)
{
    // Instantiate IME.
    ime = new MyIME () ;

    if (ime != null)
    {
        // Set IME to be current IME and activate it.
        imm.setInputMethod (ime);
        ime.activate ();
    }
}

Unicode Support

Although the Java language includes support for Unicode strings, many text editors use local character set encoding, and many text files contain local character set strings, not Unicode strings. This causes two different problems:

  • At compile time, local character set encoded string literals must be converted to Unicode.
  • At run time, strings must be converted between local character set encoding and Unicode during read and write operations.

The Microsoft Compiler for Java (jvc) translates local character set encoded string literals in Java source code to Unicode when it compiles the source into class files. When the Microsoft VM runs these class files, the string literals will appear correctly. The java.lang.Runtime methods getLocalizedInputStream and getLocalizedOutputStream will convert between local character set encoding and Unicode.

Note You should only use getLocalizedInputStream on input streams that are known to be encoded in a local character set. Do not use this method on input streams that contain Unicode characters.

Converting Local Encoding to Unicode

The getLocalizedInputStream method converts local character set encoding to Unicode. To use it, you must first call Runtime.getRuntime to get a Runtime object. Then, call the Runtime.getLocalizedInputStream method, passing the input stream object that you want to have converted. The getLocalizedInputStream method returns a DataInputStream object that performs local-character-set-to-Unicode conversion on the input stream. The following example demonstrates this technique.

Runtime rt = Runtime.getRuntime();
FileInputStream fisLoc;  // local
DataInputStream disUni;  // Unicode
String sInput;

fisLoc = new FileInputStream("LOCAL.TXT");
disUni = (DataInputStream)rt.getLocalizedInputStream(fisLoc);
sInput = disUni.readLine();

Converting Unicode to Local Encoding

The getLocalizedOutputStream method converts Unicode to local character set encoding. To use it, you must first call Runtime.getRuntime to get a Runtime object. Then, call the Runtime.getLocalizedOutputStream method, passing the output stream object that you want to have converted. The getLocalizedOutputStream method returns a DataOutputStream object that performs Unicode-to-local-character-set conversion on the output stream. The following example demonstrates this technique.

Runtime rt = Runtime.getRuntime();
FileOutputStream fosUni;  // Unicode
DataOutputStream dosLoc;  // local
String sOutput = "This is a Unicode string";

fosUni = new FileOutputStream("OUTPUT.TXT");
dosLoc = (DataOutputStream)rt.getLocalizedOutputStream(fosUni);
dosLoc.writeChars(sOutput);


LCID Reference

130 LCIDs assigned (*unsupported)
105 LCIDs supported
 59 Primary languages

Number of LCID Language and Locale
Occurrences
-------------------------------------
 1	    0401	Arabic - Saudi Arabia
 2	    0801	Arabic - Iraq
 3	    0c01	Arabic - Egypt
 4	    1001	Arabic - Libya
 5	    1401	Arabic - Algeria
 6          1801	Arabic - Morocco
 7          1c01	Arabic - Tunisia
 8          2001	Arabic - Oman
 9          2401	Arabic - Yemen
10          2801	Arabic - Syria
11          2c01	Arabic - Jordan
12          3001	Arabic - Lebanon
13          3401	Arabic - Kuwait
14          3801	Arabic - United Arab Emirates
15          3c01	Arabic - Bahrain
16          4001	Arabic - Qatar
 1          0402	Bulgarian - Bulgaria
 1          0403	Catalan - Spain
 1          0404	Chinese - Taiwan
 2          0804	Chinese - PRC
 3          0c04	Chinese - Hong Kong
 4          1004	Chinese - Singapore
 5          1404*	Chinese - Macao
 1          0405	Czech - Czech Republic
 1          0406	Danish - Denmark
 1          0407	German - Germany
 2          0807	German - Switzerland
 3          0c07	German - Austria
 4          1007	German - Luxembourg
 5          1407	German - Liechtenstein
 1          0408	Greek - Greece
 1          0409	English - United States
 2          0809	English - United Kingdom
 3          0c09	English - Australia
 4          1009	English - Canada
 5          1409	English - New Zealand
 6          1809	English - Ireland
 7          1c09	English - South Africa
 8          2009	English - Jamaica
 9          2409	English - Caribbean
10          2809	English - Belize
11          2c09	English - Trinidad
12          3009*	English - Zimbabwe
13          3409*	English - Philippines
 1          040a	Spanish - Spain (Traditional Sort)
 2          080a	Spanish - Mexico
 3          0c0a	Spanish - Spain (Modern Sort)
 4          100a	Spanish - Guatemala
 5          140a	Spanish - Costa Rica
 6          180a	Spanish - Panama
 7          1c0a	Spanish - Dominican Republic
 8          200a	Spanish - Venezuela
 9          240a	Spanish - Colombia
10          280a	Spanish - Peru
11          2c0a	Spanish - Argentina
12          300a	Spanish - Ecuador
13          340a	Spanish - Chile
14          380a	Spanish - Uruguay
15          3c0a	Spanish - Paraguay
16          400a	Spanish - Bolivia
17          440a	Spanish - El Salvador
18          480a	Spanish - Honduras
19          4c0a	Spanish - Nicaragua
20          500a	Spanish - Puerto Rico
 1          040b	Finnish - Finland
 1          040c	French - France
 2          080c	French - Belgium
 3          0c0c	French - Canada
 4          100c	French - Switzerland
 5          140c	French - Luxembourg
 6          180c*	French - Monaco
 1          040d	Hebrew - Israel
 1          040e	Hungarian - Hungary
 1          040f	Icelandic - Iceland
 1          0410	Italian - Italy
 2          0810	Italian - Switzerland
 1          0411	Japanese - Japan
 1          0412	Korean (Extended Wansung) - Korea
 2          0812	Korean (Johab) - Korea
 1          0413	Dutch - Netherlands
 2          0813	Dutch - Belgium
 1          0414	Norwegian - Norway (Bokmal)
 2          0814	Norwegian - Norway (Nynorsk)
 1          0415	Polish - Poland
 1          0416	Portuguese - Brazil
 2          0816	Portuguese - Portugal
 1          0417*	Rhaeto-Romanic - Rhaeto-Romanic
 1          0418	Romanian - Romania
 2          0818*	Romanian - Moldavia
 1          0419	Russian - Russia
 2          0819*	Russian - Moldavia
 1          041a	Croatian - Croatia
 2          081a	Serbian - Serbia (Latin)
 3          0c1a	Serbian - Serbia (Cyrillic)
 1          041b	Slovak - Slovakia
 1          041c	Albanian - Albania
 1          041d	Swedish - Sweden
 2          081d	Swedish - Finland
 1          041e	Thai - Thailand
 1          041f	Turkish - Turkey
 1          0420*	Urdu - Urdu
 1          0421	Indonesian - Indonesia
 1          0422	Ukrainian - Ukraine
 1          0423	Belarussian - Belarus
 1          0424	Slovene - Slovenia
 1          0425	Estonian - Estonia
 1          0426	Latvian - Latvia
 1          0427	Lithuanian - Lithuania
 0          0028
 1	    0429  	Farsi - Iran
 1          042a	Vietnamese - Vietnam
 0          002b
 0	    002c
 1          042d	Basque - Spain
 1          042e*	Sorbian - Sorbian
 1          042f*	Macedonian - Macedonian
 1          0430*	Sutu - Sutu
 1          0431*	Tsonga - Tsonga
 1          0432*	Tswana - Tswana
 1          0433*	Venda - Venda
 1          0434*	Xhosa - Xhosa
 1          0435*	Zulu - Zulu
 1          0436	Afrikaans - South Africa
 0          0037
 1          0438	Faeroese - Faeroe Islands
 1          0439*	Hindi - Hindi
 1          043a*	Maltese - Maltese
 1          043b*	Saami - Saami (Lappish)
 1          043c*	Gaelic - Scots
 2          083c*	Gaelic - Irish
 1          043d*	Yiddish - Yiddish
 1          043e*	Malay - Malaysian
 2          083e*	Malay - Brunei
 0          003f
 0          0040
 1          0441*	Swahili - Kenya


About java.util

Classes

Class Locale
A Locale object represents a specific geographical, political, or cultural region.

Hierarchy

Object
  |
  +--Locale (Cloneable, Serializable)


Class Locale

public final class Locale implements Cloneable, Serializable
{
  // Fields
  static public final Locale AFRIKAANS;
  static public final Locale ALBANIAN;
  static public final Locale AUSTRALIA;
  static public final Locale BASQUE;
  static public final Locale BELGIAN;
  static public final Locale BELGIAN_FRENCH;
  static public final Locale BRAZILIAN;
  static public final Locale BULGARIAN;
  static public final Locale BYELORUS;
  static public final Locale CANADA;
  static public final Locale CANADA_FRENCH;
  static public final Locale CATALAN;
  static public final Locale CHINA;
  static public final Locale CHINESE;
  static public final Locale CROATIAN;
  static public final Locale CZECH;
  static public final Locale DANISH;
  static public final Locale DUTCH;
  static public final Locale ENGLISH;
  static public final Locale ESTONIAN;
  static public final Locale FINNISH;
  static public final Locale FRANCE;
  static public final Locale FRENCH;
  static public final Locale GERMAN;
  static public final Locale GERMAN_AUSTRIAN;
  static public final Locale GERMAN_SWISS;
  static public final Locale GERMANY;
  static public final Locale GREEK;
  static public final Locale HEBREW;
  static public final Locale HUNGARIAN;
  static public final Locale ICELANDIC;
  static public final Locale INDONESIAN;
  static public final Locale IRELAND;
  static public final Locale ITALIAN;
  static public final Locale ITALY;
  static public final Locale JAPAN;
  static public final Locale JAPANESE;
  static public final Locale JAPANESE_VERTICAL;
  static public final Locale KOREA;
  static public final Locale KOREAN;
  static public final Locale KOREAN_VERTICAL;
  static public final Locale LATVIAN;
  static public final Locale LITHUANIAN;
  static public final Locale MEXICAN;
  static public final Locale NEWZEALAND;
  static public final Locale NORWEGIAN;
  static public final Locale NORWEGIAN_NYNORSK;
  static public final Locale POLISH;
  static public final Locale PORTUGESE;
  static public final Locale PRC;
  static public final Locale ROMANIAN;
  static public final Locale RUSSIAN;
  static public final Locale SERBIAN;
  static public final Locale SIMPLIFIED_CHINESE;
  static public final Locale SIMPLIFIED_CHINESE_VERTICAL;
  static public final Locale SINGAPORE;
  static public final Locale SLOVAKIAN;
  static public final Locale SLOVENIAN;
  static public final Locale SOUTH_AFRICA;
  static public final Locale SPANISH;
  static public final Locale SPANISH_MODERN;
  static public final Locale SWEDISH;
  static public final Locale SWISS;
  static public final Locale TAIWAN;
  static public final Locale THAI;
  static public final Locale TRADITIONAL_CHINESE;
  static public final Locale TRADITIONAL_CHINESE_VERTICAL;
  static public final Locale TURKISH;
  static public final Locale UK;
  static public final Locale UKRANIAN;
  static public final Locale US;

  // Constructors
  public Locale(String language, String country, String variant);
  public Locale(String language, String country, String variant, int LCID,
        int codepage);
  public Locale(String language, String country);

  // Methods
  public Object clone();
  public boolean equals(Object obj);
  public int getCodePage();
  public String getCountry();
  public static synchronized Locale getDefault();
  public Locale[] getDefaultLocaleList();
  public final String getDisplayCountry();
  public String getDisplayCountry(Locale inLocale);
  public final String getDisplayLanguage();
  public String getDisplayLanguage(Locale inLocale);
  public final String getDisplayName();
  public String getDisplayName(Locale inLocale);
  public final String getDisplayVariant();
  public String getDisplayVariant(Locale inLocale);
  public String getISO3Country() throws MissingResourceException;
  public String getISO3Language() throws MissingResourceException;
  public String getLanguage();
  public int getLCID() throws MissingResourceException;
  public static Locale getLocaleFromLCID(int lcid);
  public String getVariant();
  public synchronized int hashCode();
  public static synchronized void setDefault(Locale newLocale);
  public final String toString();
}

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.

You create a Locale object using one of the constructors in this class:

Locale(String language, String country)
Locale(String language, String country, String variant)
Locale(String language, String country, String variant, int LCID, int codepage)

The first argument to both constructors is a valid ISO Language Code. These codes are the lower-case, two-letter codes as defined by ISO-639. You can find a full list of these codes at a number of sites, such as:
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt

The second argument to both constructors is a valid ISO Country Code. These codes are the upper-case, two-letter codes as defined by ISO-3166. You can find a full list of these codes at a number of sites, such as:
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html

The second constructor requires a third argument--the Variant. The Variant codes are vendor and browser-specific. For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. Where there are two variants, separate them with an underscore, and put the most important one first. For example, a Traditional Spanish collation might be referenced, with "ES", "ES", "Traditional_WIN".

The third constructor requires two additional arguments in addition to language, country, and variant: Win32 locale and code page identifiers.

Because a Locale object is just an identifier for a region, no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct, you must query those resources. For example, ask the NumberFormat for the locales it supports using its getAvailableLocales method.

Note: When you ask for a resource for a particular locale, you get back the best available match, not necessarily precisely what you asked for. For more information, look at ResourceBundle.

The Locale class provides a number of convenient constants that you can use to create Locale objects for commonly used locales. For example, the following creates a Locale object for the United States:

Locale.US

Once you've created a Locale you can query it for information about itself. Use getCountry to get the ISO Country Code and getLanguage to get the ISO Language Code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable for displaying to the user. Interestingly, the getDisplayXXX methods are themselves locale-sensitive and have two versions: one that uses the default locale and one that uses the locale specified as an argument.

There are a number of classes that perform locale-sensitive operations. For example, the NumberFormat class formats numbers, currency, or percentages in a locale-sensitive manner. Classes such as NumberFormat have a number of convenience methods for creating a default object of that type. For example, the NumberFormat class provides these three convenience methods for creating a default NumberFormat object:

NumberFormat.getInstance()
NumberFormat.getCurrencyInstance()
NumberFormat.getPercentInstance()

These methods have two variants; one with an explicit locale and one without; the latter using the default locale.

NumberFormat.getInstance(myLocale)
NumberFormat.getCurrencyInstance(myLocale)
NumberFormat.getPercentInstance(myLocale)

A Locale is the mechanism for identifying the kind of object (NumberFormat) that you would like to get. The locale is just a mechanism for identifying objects, not a container for the objects themselves.

Each class that performs locale-sensitive operations allows you to get all the available objects of that type. You can sift through these objects by language, country, or variant, and use the display names to present a menu to the user. For example, you can create a menu of all the collation objects suitable for a given language. Such classes must implement these three class methods:

public static Locale[] getAvailableLocales()
public static String getDisplayName(Locale objectLocale,
                                    Locale displayLocale)
public static final String getDisplayName(Locale objectLocale)
    // getDisplayName will throw MissingResourceException if the locale
    // is not one of the available locales.

Also see ResourceBundle, Format, NumberFormat, Collation

Constructors

Locale

public Locale(String language, String country, String variant);

Construct a locale from language, country, variant.

Parameter | Description
language | Lowercase two-letter ISO-639 code.
country | Uppercase two-letter ISO-3166 code.
variant | Vendor- and browser-specific code. See class description.

Locale

public Locale(String language, String country, String variant, int LCID,
        int codepage);

Construct a Locale from language, country, variant, locale identifier, code page.

Parameter | Description
language | Lowercase two-letter ISO-639 code.
country | Uppercase two-letter ISO-3166 code.
variant | Vendor and browser specific code. See class description.
LCID | Win32 locale identifier.
codepage | Win32 code page.

Locale

public Locale(String language, String country);

Construct a locale from language, country.

Parameter | Description
language | Lowercase two-letter ISO-639 code.
country | Uppercase two-letter ISO-3166 code.

Methods

clone

public Object clone();

Creates a clone of locale.

Return Value:

Returns clone of locale.

equals

public boolean equals(Object obj);

Compares two locales for equality.

Return Value:

Returns true if equal; otherwise, false.

getCodePage

public int getCodePage();

Gets the code page of the locale.

Return Value:

Returns Win32 code page identifier for the locale.

Exceptions:

MissingResourceException Throws MissingResourceException if there is no code page associated with the locale.

getCountry

public String getCountry();

Gets the programatic name of country field, an uppercased two-letter ISO-3166 code.

Return Value:

Returns lowercased two-letter ISO-639 code representing country.

See Also: getDisplayCountry

getDefault

public static synchronized Locale getDefault();

Common method of getting the current default Locale. Used for the presentation: menus, dialogs, and so on. Generally set once when your applet or application is initialized, then never reset. (If you do reset the default locale, you probably want to reload your GUI, so that the change is reflected in your interface.)

More advanced programs will allow users to use different locales for different fields, e.g. in a spreadsheet.
Note that the initial setting will match the host system.

getDefaultLocaleList

public Locale[] getDefaultLocaleList();

Gets a list of all predefined Locale constants.

Return Value:

Returns list of predefined Locale constants.

getDisplayCountry

public final String getDisplayCountry();

Retrieves the display country of the locale. If the localized name is not found, returns the ISO code. The default locale determines the language used for display country name

Return Value:

Returns name of country for display to user.

getDisplayCountry

public String getDisplayCountry(Locale inLocale);

Retrieves the localized name of the display country of the locale. If the localized name is not found, it returns the ISO code.

Return Value:

Returns the localized name of the country for display to user.

Parameter | Description
inLocale | Specifies the desired user language.

getDisplayLanguage

public final String getDisplayLanguage();

Retrieves the display language of the locale. If the localized name is not found, it returns the ISO code. The desired user language is from the default locale.

Return Value:

Returns name of language for display to user.

getDisplayLanguage

public String getDisplayLanguage(Locale inLocale);

Gets the localized name of the display language of the locale. If the localized name is not found, it returns the ISO codes. For example: "English (UK)", "Deutsche (Germany)".

Return Value:

Returns the localized name of language for display to user.

Parameter | Description
inLocale | Specifies the desired user language.

getDisplayName

public final String getDisplayName();

Gets the display of the entire locale to the user. If the localized name is not found, it uses the ISO codes. The default locale is used for the presentation language.

getDisplayName

public String getDisplayName(Locale inLocale);

Gets the display of the entire locale to the user. If the localized name is not found, it uses the ISO codes.

Return Value:

Returns name of locale for display to user.

Parameter | Description
inLocale | Specifies the desired user language.

getDisplayVariant

public final String getDisplayVariant();

Gets the display of the variant field to the user. If the localized name is not found, it returns the variant code. The default locale is used for the presentation language.

Return Value:

Returns variant field for display to user.

getDisplayVariant

public String getDisplayVariant(Locale inLocale);

Gets the display of the field to the user. If the localized name is not found, it returns the variant code.

Return Value:

Returns localized variant field for display to user.

Parameter | Description
inLocale | Specifies the desired user language.

getISO3Country

public String getISO3Country() throws MissingResourceException;

Gets the three-letter ISO country abbreviation of the locale.

Return Value:

Returns the three-letter ISO country abbreviation of the locale.

Exceptions:

MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.

getISO3Language

public String getISO3Language() throws MissingResourceException;

Gets the three-letter ISO language abbreviation of the locale.

Return Value:

Returns the three-letter ISO language abbreviation of the locale.

Exceptions:

MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.

getLanguage

public String getLanguage();

Gets the programatic name of the language field, a lowercased, two-letter ISO-639 code.

Return Value:

Returns lowercased two-letter ISO-639 code representing the language.

See Also: getDisplayLanguage

getLCID

public int getLCID() throws MissingResourceException;

Gets the locale identifier (LCID) as used in Windows.

Return Value:

Returns Win32 locale identifier for the locale.

Exceptions:

MissingResourceException Throws MissingResourceException if there is no LCID associated with the locale.

getLocaleFromLCID

public static Locale getLocaleFromLCID(int lcid);

Gets a Locale from the specified locale identifier (LCID).

Return Value:

Returns the Locale if successful; otherwise, returns null.

Parameter | Description
lcid | Win32 locale identifier (LCID)

getVariant

public String getVariant();

Gets the programatic name of the variant field.

Return Value:

Returns the programatic name of the variant field.

See Also: getDisplayVariant

hashCode

public synchronized int hashCode();

Overrides hashCode. Since locales are often used in hashtables, it caches the value for speed.

Return Value:

Returns hash code.

setDefault

public static synchronized void setDefault(Locale newLocale);

Sets the default. Normally it is set once at the beginning of an applet or application, then never reset. setDefault does not reset the host locale.

Parameter | Description
newLocale | Locale to set to.

toString

public final String toString();

Gets the programatic name of the entire locale with the language, country and variant separated by underscores. If a field is missing, at most one underscore will occur. For example: "EN", "DE_DE", "EN_US_WIN", "DE_POSIX", "FR_MAC".

Return Value:

Returns the programatic name of the locale.

See Also: getDisplayName

Fields

AFRIKAANS
Useful constant for language.
ALBANIAN
Useful constant for language.
AUSTRALIA
Useful constant for country.
BASQUE
Useful constant for language.
BELGIAN
Useful constant for language.
BELGIAN_FRENCH
Useful constant for country.
BRAZILIAN
Useful constant for language.
BULGARIAN
Useful constant for language.
BYELORUS
Useful constant for language.
CANADA
Useful constant for country.
CANADA_FRENCH
Useful constant for country.
CATALAN
Useful constant for language.
CHINA
Useful constant for country.
CHINESE
Useful constant for language.
CROATIAN
Useful constant for language.
CZECH
Useful constant for language.
DANISH
Useful constant for language.
DUTCH
Useful constant for language.
ENGLISH
Useful constant for language.
ESTONIAN
Useful constant for country.
FINNISH
Useful constant for country.
FRANCE
Useful constant for country.
FRENCH
Useful constant for language.
GERMAN
Useful constant for language.
GERMAN_AUSTRIAN
Useful constant for language.
GERMAN_SWISS
Useful constant for language.
GERMANY
Useful constant for country.
GREEK
Useful constant for language.
HEBREW
Useful constant for language.
HUNGARIAN
Useful constant for language.
ICELANDIC
Useful constant for language.
INDONESIAN
Useful constant for language.
IRELAND
Useful constant for country.
ITALIAN
Useful constant for language.
ITALY
Useful constant for country.
JAPAN
Useful constant for country.
JAPANESE
Useful constant for language.
JAPANESE_VERTICAL
Useful constant for language.
KOREA
Useful constant for country.
KOREAN
Useful constant for language.
KOREAN_VERTICAL
Useful constant for language.
LATVIAN
Useful constant for language.
LITHUANIAN
Useful constant for language.
MEXICAN
Useful constant for language.
NEWZEALAND
Useful constant for country.
NORWEGIAN
Useful constant for language.
NORWEGIAN_NYNORSK
Useful constant for language.
POLISH
Useful constant for language.
PORTUGESE
Useful constant for language.
PRC
Useful constant for country.
ROMANIAN
Useful constant for language.
RUSSIAN
Useful constant for language.
SERBIAN
Useful constant for language.
SIMPLIFIED_CHINESE
Useful constant for language.
SIMPLIFIED_CHINESE_VERTICAL
Useful constant for language.
SINGAPORE
Useful constant for language.
SLOVAKIAN
Useful constant for language.
SLOVENIAN
Useful constant for language.
SOUTH_AFRICA
Useful constant for country.
SPANISH
Useful constant for language.
SPANISH_MODERN
Useful constant for language.
SWEDISH
Useful constant for language.
SWISS
Useful constant for country.
TAIWAN
Useful constant for country.
THAI
Useful constant for language.
TRADITIONAL_CHINESE
Useful constant for language.
TRADITIONAL_CHINESE_VERTICAL
Useful constant for language.
TURKISH
Useful constant for language.
UK
Useful constant for country.
UKRANIAN
Useful constant for language.
US
Useful constant for country.


J/Direct Articles and Reference

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

JDirect | Welcome! | Next
 | Welcome! | Next

J/Direct Articles and Reference

Microsoft® J/Direct™ is a new feature that provides easy access to Windows dynamic-link libraries (DLLs). Using J/Direct, you can make direct calls to standard Win32 system DLLs (such as KERNEL32 and USER32) and third-party DLLs. J/Direct is far simpler to use than the older Raw Native Interface or the Java Native Interface (known as RNI and JNI, respectively), both of which require you to write a specialized wrapper DLL and perform all non-trivial data type translations yourself. With J/Direct, the majority of pre-existing DLL functions can be invoked simply by declaring the function and calling it. J/Direct uses the @dll.import directive, which is similar in usage and in spirit to the Visual Basic® DECLARE facility.

Articles

The About J/Direct article provides a complete overview and detailed information about how to use the J/Direct technology.

References

  • Package com.ms.dll


Introduction

Microsoft® J/Direct™ is a new feature that provides easy access to Microsoft® Windows® dynamic-link libraries (DLLs). Using J/Direct, you can make direct calls to standard Win32 system DLLs (such as KERNEL32 and USER32) and third-party DLLs. J/Direct is far simpler to use than the older Raw Native Interface or the Java Native Interface (known as RNI and JNI, respectively), both of which require you to write a specialized wrapper DLL and perform all non-trivial data type translations yourself. With J/Direct, the vast majority of pre-existing DLL functions can be invoked by simply declaring the function and calling it. J/Direct uses the @dll.import directive, which is similar in usage and in spirit to Visual Basic's DECLARE facility.

To use J/Direct, you must install the latest versions of the Microsoft Compiler for Java and the Microsoft Win32 Virtual Machine for Java. These are available with the Microsoft SDK for Java version 2.5. You can find code samples that use J/Direct under \MsVmJava\Samples\JDirect\ in the directory in which you install the Microsoft SDK for Java.

This article explains how to use the @dll.import directive to invoke a DLL function from Java. This article also offers details about how each data type is passed and received, and describes how the @dll.struct directive is used to pass and receive structures from DLL methods.

The following topics are included:

Getting Started

How Data Types are Marshaled

Invoking OLE API Functions

Aliasing (Method Renaming)

Linking by Ordinal

Specifying @dll.import for an Entire Class

How the VM Chooses Between ANSI and Unicode

Obtaining the Error Code Set By a DLL Function

Dynamically Loading and Invoking DLLs

Comparing J/Direct to Raw Native Interface

Security Issues

Error Messages

Troubleshooting Tips

Frequently Asked Questions


Getting Started

This section provides a message box application that uses @dll.import. Then, the syntaxes of the @dll.import, @dll.struct, and @dll.structmap compiler directives are presented.

Example

Using Microsoft® J/Direct™ to call Win32 DLLs from Java code is straightforward. Here is a short Java application that displays a message box.

class ShowMsgBox {
   public static void main(String args[])
   {
      MessageBox(0, "It worked!",
                 "This messagebox brought to you from Java", 0);
   }

   /** @dll.import("USER32") */
   private static native int MessageBox(int hwndOwner, String text,
                                        String title, int fuStyle);
}

The @dll.import directive tells the compiler that the MessageBox method will link to the Win32 USER32.DLL using the J/Direct protocol rather than the Raw Native Interface protocol supported in previous versions. In addition, the Microsoft Win32 VM for Java provides automatic type marshaling from String objects to the null-terminated strings expected by C.

You may have noticed that it is not necessary to indicate whether the ANSI MessageBox (MessageBoxA) function or the Unicode MessageBox function (MessageBoxW) should be called. In the previous example, the ANSI version is always called. The How the VM Chooses Between ANSI and Unicode section explains how to use the auto modifier to call the optimal version of the function, depending on the version of Microsoft® Windows® that is hosting the application.

Quick Syntax Reference

The following sections give a quick reference to the @dll.import, @dll.struct, and @dll.structmap directives. For each directive, the required syntax is shown and explained.

Syntax for @dll.import

Syntax for @dll.struct

Syntax for @dll.structmap

Be aware that white space within @dll directives can cause syntax errors. You can put white space between the directive and the comment tags, but not within the directive itself. For example, the following directive would cause a syntax error.

  /**@dll.import("MyDll",   auto)*/

But this one would not cause an error.

  /**       @dll.import("MyDll",auto) */

Syntax for @dll.import

The @dll.import directive should be placed just above the method declaration. The syntax of the directive is as follows.

  /**@dll.import("LibName",<Modifier>)*/
  ...method declaration...;

LibName is the name of the DLL that contains the function you want to invoke. Modifier is optional, and the value that you should supply for it varies depending on your needs. In the method declaration, you can use the function name that the DLL uses, or you can give the method a different name by using aliasing (see Aliasing (Method Renaming)). The Java data types that you choose for the parameters and for the return value of the method should be types that map to the types of the DLL function parameters and return value. See How Data Types are Marshaled for more information about how Java data types map to native types.

The following table presents the @dll.import syntax for several situations that are described in this article.

Situation | Required Syntax | Explanation
Calling Win 32 DLLs | /**@dll.import("LibName")*/
Calling OLE APIs | /**@dll.import("LibName",ole)*/
Aliasing | /**@dll.import("LibName",entrypoint="DLLFunctionName")*/ | In the method declaration, use the Java name that you selected.
Linking by Ordinal | /**@dll.import("LibName",entrypoint="#ordinal")*/ | "ordinal" is a 16-bit integer, specified in decimal, that indicates the DLL function that you are importing.

Syntax for @dll.struct

The @dll.struct directive should be placed just above the class declaration. The syntax of @dll.struct is as follows.

  /**@dll.struct(<LinkTypeModifier>,<pack=n>)*/
  ...class declaration...;

LinkTypeModifier tells the compiler whether fields of type String and char represent ANSI or Unicode characters in native format. LinkTypeModifier can be ansi, unicode, or auto. If you do not specify LinkTypeModifier, ansi is used by default. The How the VM Chooses Between ANSI and Unicode section can help you learn more about which value to use for LinkTypeModifier.

You can also specify pack=n to tell the compiler to set the packing size of the structure to either 1,2,4, or 8, depending on the value you specify for n. If you omit the pack=n modifier, the packing size is set to 8 by default. See the Structure Packing section of this article for more information on setting the packing size.

Within the class declaration, you need to supply fields whose Java types map to the types of the fields in the native structure, in the order they occur in the native structure. See the section on Correspondence Between Types Inside Structures for information about choosing the data types of the fields.

The following table describes the syntax for several situations in which you might use the @dll.struct directive.

Situation | Required Syntax | Explanation
Declare a Structure | /**@dll.struct()*/ | When you do not specify LinkTypeModifier, char or String fields are assumed to represent ANSI characters.
Set a Structure's Packing Size | /**@dll.struct(pack=n)*/ | n can be 1,2,4, or 8.
Declare a Structure that has a Field of Type char | /**@dll.struct(ansi)*/ | The character field represents an ANSI character.
Declare a Structure with a Field of Type String and Set the Packing Size | /**@dll.struct(unicode,pack=n)*/ | The String fields will be in Unicode format, and the packing size is set to 1,2,4, or 8, depending on the value of n.

Syntax for @dll.structmap

The @dll.structmap directive is used to declare fixed-size strings and arrays embedded in structures. It should be placed within a structure that is declared with @dll.struct, and directly above the declaration of the fixed-size string or array field. For more information on how to use @dll.structmap, see the Fixed-size Strings Embedded within Structures and Fixed-size Scalar Arrays Embedded within Structures sections of this article.

The following table presents the syntax of the @dll.structmap directive.

Situation | Required Syntax | Explanation
Structure that contains a fixed-size string. | /**@dll.structmap([type=TCHAR[Size]])*/ | Size is a decimal integer that indicates the number of characters in the string, including space for the null terminator.
Structure that contains a fixed-size array. | /**@dll.structmap([type=FIXEDARRAY,size=n])*/ | n is a decimal integer that represents the size of the array.


How Data Types are Marshaled

In this topic

* Quick Reference

* Basic Scalar Types

* Chars

* Booleans

* Strings

* Arrays

* Structures

* Pointers

* Polymorphic Parameters

* Callbacks

JDirect | Previous | JDirect | Next
About J/Direct | Previous | JDirect | Next

How Data Types are Marshaled

The Microsoft Win32 VM for Java infers the native type of each parameter and the return value from the declared (compile-time) Java type of the parameter. For example, a parameter declared as a Java integer is passed as a 32-bit integer; a parameter declared as a Java String object is passed as a null-terminated string, and so forth. There are no invisible attributes that provide information about the native types. In Java, what you see is what you get.

The following sections describe in detail how the Java data types map to native data types.

Quick Reference | Provides tables that list the Java type that maps to each native type.
Basic Scalar Types | Describes the mappings for int, byte, short, long, float, and double.
Chars | Explains the mapping of the char data type.
Booleans | Explains the mapping of the boolean data type.
Strings | Explains how to pass and receive strings.
Arrays | Explains how to pass arrays of scalars.
Structures | Explains how to use the @dll.struct directive to pass and receive structures and how to use @dll.structmap to embed fixed-sized arrays within structures.
Pointers | Explains how to handle DLLs that have multiple return values and how to read and write data through raw pointers.
Polymorphic Parameters | Explains how to simulate polymorphic parameters.
Callbacks | Explains how to declare and invoke a DLL function that takes a Callback parameter and how to embed a Callback inside a structure.

Quick Reference

The following two tables list the native type that corresponds to each Java type. The first table describes the mappings for parameters and return values, and the second table shows the mappings that are used with the @dll.struct directive.

Parameter and Return Value Mappings

Java | Native | Notes/Restrictions
byte | BYTE or CHAR
short | SHORT or WORD
int | INT, UINT, LONG, ULONG, or DWORD
char | TCHAR
long | __int64
float | float
double | double
boolean | BOOL
String | LPCTSTR | Not allowed as return value, except in ole mode. In ole mode, String maps to LPWSTR. The Microsoft VM frees the string by using CoTaskMemFree.
StringBuffer | LPTSTR | Not allowed as return value. Set the StringBuffer capacity large enough to hold the largest string that the DLL function can generate.
byte[] | BYTE*
short[] | WORD*
char[] | TCHAR*
int[] | DWORD*
float[] | float*
double[] | double*
long[] | __int64*
boolean[] | BOOL[]
Object | pointer to struct | In ole mode, an IUnknown* is passed instead.
Interface | COM interface | Use jactivex or similar tool to generate interface file.
com.ms.com.SafeArray | SAFEARRAY* | Not allowed as return value.
com.ms.com._Guid | GUID,IID,CLSID
com.ms.com.Variant | VARIANT*
@dll.struct classes | pointer to struct
@com.struct classes | pointer to struct
void | VOID | As return value only.
com.ms.dll.Callback | function pointer | As parameter only.

Mappings Used with @dll.struct

Java | Native
byte | BYTE or CHAR
char | TCHAR
short | SHORT or WORD
int | INT, UINT, LONG, ULONG or DWORD
long | __int64
float | float
double | double
boolean | BOOL[]
Java | Native
String | Pointer to a string, or an embedded fixed-size string
Class marked with @dll.struct | Nested structure
char[] | Nested array of TCHAR
byte[] | Nested array of BYTE
short[] | Nested array of SHORT
int[] | Nested array of LONG
long[] | Nested array of __int64
float[] | Nested array of floats
double [] | Nested array of doubles

Basic Scalar Types

The basic scalar types are mapped as you would expect.
Java type | DLL
int | signed 32-bit integer
byte | signed 8-bit integer
short | signed 16-bit integer
long | signed 64-bit integer
float | 32-bit float
double | 64-bit double

There is no direct representation of unsigned integer types in Java, except by using the signed types as a two's complement representation. For example, the integer type can be used without loss of representation for the common DWORD (unsigned 32-bit) type.

Chars

The Java char type becomes a CHAR (an 8-bit ANSI character) unless the unicode or ole modifier is in effect, in which case it becomes a WCHAR (a 16-bit Unicode character).

Booleans

The Java boolean type maps to the Win32 BOOL type, which is a 32-bit type. As a parameter, the Java true maps to 1, and false maps to 0. As a return value, all non-zero values map to true.

Note that BOOL and VARIANT_BOOL (the internal boolean type in Microsoft® Visual Basic®) are not interchangeable. To pass a VARIANT_BOOL to a Visual Basic DLL, you must use the Java short type and use -1 for VARIANT_TRUE, and 0 for VARIANT_FALSE.

Strings

This section explains how you can pass a string in ANSI or Unicode format to a DLL function. It also discusses two ways to return a string from a DLL function.

Passing a String to a DLL Function

To pass a standard null-terminated string to a DLL function, just pass a Java String.

For example, to change the current directory, you can access the Kernel32 function CopyFile function as follows.

class ShowCopyFile
{
  public static void main(String args[])
  {
    CopyFile("old.txt", "new.txt", true);
  }
  /** @dll.import("KERNEL32") */
  private native static boolean CopyFile(String existingFile,
                                  String newFile, boolean f);
}

Strings are read-only in Java, so the Microsoft VM will only convert the String object as an input. To allow virtual machine implementations to marshal Strings without copying the characters, String object parameters should not be passed to DLL functions that can modify the string. If the DLL function might modify the string, pass a StringBuffer object.

Strings are converted to ANSI unless the unicode or ole modifier is used, in which case the string is passed in Unicode format.

Strings cannot be declared as return types of a DLL function except in ole mode, where the native return type is assumed to be a LPWSTR allocated using the CoTaskMemAlloc function.

Receiving a String From a DLL Function

There are two common ways of passing a string back from a function: either the caller allocates a buffer that is filled in by the function, or the function allocates the string and returns it to the caller. Most Win32 functions use the first method, but OLE functions use the second method. (See Invoking OLE API Functions to learn about the special support that Microsoft® J/Direct™ provides for calling OLE functions.) One function that uses the first method is the Kernel32 function GetTempPath, which has the following prototype.

  DWORD GetTempPath(DWORD sizeofbuffer, LPTSTR buffer);

This function simply returns the path of the system tempfile directory (such as "c:\tmp\"). The buffer argument points to a caller-allocated buffer that receives the path, and sizeofbuffer indicates the number of characters that can be written to the buffer. (This is different from the number of bytes in the Unicode version.) In Java, Strings are read-only, so you cannot pass a String object as the buffer. Instead, you can use Java's StringBuffer class to create a writable StringBuffer object. Here is an example that invokes the GetTempPath function.

class ShowGetTempPath
{
  static final int MAX_PATH = 260;
  public static void main(String args[])
  {
    StringBuffer temppath = new StringBuffer(MAX_PATH);
    GetTempPath(temppath.capacity()+1, temppath);
    System.out.println("Temppath = " + temppath);
  }

  /** @dll.import("KERNEL32") */
  private static native int GetTempPath(int sizeofbuffer,
                                        StringBuffer buffer);
}

To understand this example, it is important to distinguish between a StringBuffer's length and its capacity. The length is the number of characters logically in the string currently stored in the StringBuffer. The capacity is the actual amount of storage currently allocated to that StringBuffer. After the following statement executes,

  StringBuffer sb = new StringBuffer(259);

the value of sb.length is zero, and the value of sb.capacity is 259. When you invoke a DLL method passing a StringBuffer, the Microsoft VM examines the capacity of the StringBuffer, adds one for the null terminator, multiplies by 2 if Unicode is the default character size, and then allocates that many bytes of memory for the buffer that is passed to the DLL function. In other words, you use the capacity, not the length, to set the size of the buffer. Be careful not to make the following mistake.

  StringBuffer sb = new StringBuffer();  //Wrong!
  GetTempPath(MAX_PATH, sb);

Invoking the StringBuffer constructor with no arguments creates a StringBuffer object with a capacity of 16, which is probably too small. MAX_PATH was passed to the GetTempPath method, indicating that there was enough room in the buffer to hold 260 characters. Thus, GetTempPath will probably overrun the buffer. If you were planning to use GetTempPath extensively, you should wrap it in the following manner.

public static String GetTempPath()
{
  StringBuffer temppath = new StringBuffer(MAX_PATH-1);
  int res = GetTempPath(MAX_PATH, temppath);
  if (res == 0 || res > MAX_PATH) {
    throw new RuntimeException("GetTempPath error!");
  }
  return temppath.toString(); // can't return a StringBuffer
}

This method offers both convenience and safety, and it maps the error return value of the function to a Java exception. Notice that you cannot return StringBuffer objects.

Arrays

J/Direct automatically handles arrays of scalars. The following Java array types translate directly into native pointer types as follows.
Java | Native | # of bytes per element
byte[] | BYTE* | 1
short[] | SHORT* | 2
int[] | DWORD* | 4
float[] | FLOAT* | 4
double[] | DOUBLE* | 8
long[] | __int64* | 8
boolean[] | BOOL* | 4

The char[] array type maps to CHAR* unless the unicode modifier is in effect, in which case it maps to WCHAR*.

All scalar array parameters can be modified by the caller (like [in,out] parameters).

Array types cannot be used as return types. There is no support for arrays of objects or strings.

Typically, this facility is used by OLE functions to return values. (OLE functions reserve the "function" return value to return the HRESULT error code.) See Invoking OLE API Functions to learn how to obtain the return value for OLE functions.

Structures

The Java language does not directly support the concept of a structure. Although Java classes containing fields can be used to emulate the concept of a structure within the Java language, ordinary Java objects cannot be used to simulate structures in native DLL calls. This is because the Java language does not guarantee the layout of the fields and because the garbage collector is free to move the object around in memory.

Therefore, to pass and receive structures from DLL methods, you need to use the @dll.struct compiler directive. When applied to a Java class definition, this directive causes all instances of the class to be allocated in a memory block that will not move during garbage collection. In addition, the layout of the fields in memory can be controlled using the pack modifier (see Structure Packing). For example, the Win32 SYSTEMTIME structure has the following definition in the C programming language.

typedef struct {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME;

The correct declaration of this structure in Java is as follows.

/** @dll.struct() */
class SYSTEMTIME {
  public short wYear;
  public short wMonth;
  public short wDayOfWeek;
  public short wDay;
  public short wHour;
  public short wMinute;
  public short wSecond;
  public short wMilliseconds;
}

The following example uses the SYSTEMTIME structure in a DLL method call.

class ShowStruct {
    /** @dll.import("KERNEL32") */
    static native void GetSystemTime(SYSTEMTIME pst);
    public static void main(String args[])
    {
      SYSTEMTIME systemtime = new SYSTEMTIME();
      GetSystemTime(systemtime);
      System.out.println("Year is " + systemtime.wYear);
      System.out.println("Month is " + systemtime.wMonth);
      // etc.
    }
}

Note: Classes declared with @dll.struct are considered unsafe and therefore cannot be used by untrusted applets.

Correspondence Between Types Inside Structures

The following table describes how scalar types map inside structures.
Java | Native
byte | BYTE
char | TCHAR (CHAR or WCHAR depending on @dll.struct definition)
short | SHORT
int | LONG
long | __int64
float | float
double | double
boolean | BOOL (32-bit boolean)

Reference types (Java objects and classes) normally map to embedded structures and arrays. Each supported mapping is described in the following table.
Java | Native
String | Pointer to a string, or an embedded fixed-size string
Class marked with @dll.struct | Nested structure
char[] | Nested array of TCHAR (CHAR/WCHAR)
byte[] | Nested array of BYTE
short[] | Nested array of SHORT
int[] | Nested array of LONG
long[] | Nested array of __int64
float[] | Nested array of floats
double [] | Nested array of doubles

There is no direct support for pointers inside structures, due to the large number of possible ways referenced objects could be allocated and disposed of. To represent a structure with an embedded pointer, declare the pointer field as type int. You will need to make explicit DLL calls to the appropriate allocation functions and initialize the memory blocks yourself. (You could use DllLib.ptrToStruct to map the blocks onto @dll.struct classes.)

Nested Structures

A structure can embed another structure simply by naming the other structure as the field type. For example, the Windows MSG structure embeds a POINT structure as follows.

    typedef struct {
        LONG x;
        LONG y;
    } POINT;

    typedef struct {
        int hwnd;
        int message;
        int wParam;
        int lParam;
        int time;
        POINT pt;
    } MSG;

This translates directly into Java as follows.

    /** @dll.struct() */
    class POINT {
        int x;
        int y;
    }
    /** @dll.struct() */
    class MSG {
        public int hwnd;
        public int message;
        public int wParam;
        public int lParam;
        public int time;
        public POINT pt;
    }

Performance tip: Although embedding structures is handy, the fact remains that Java does not truly support embedded objects – only embedded references to objects. The Microsoft VM must translate between these two formats each time a nested structure is passed. Therefore, in a critical code path, you can improve performance by nesting structures manually (by copying the fields of the nested structure into the containing structure). For example, the pt field in the MSG structure could easily be declared as two integer fields, pt_x and pt_y.

Fixed-size Strings Embedded within Structures

Some structures have fixed size strings embedded in them. The LOGFONT structure is defined as follows.

   typedef struct {
     LONG lfHeight;
     LONG lfWidth;
     /* <many other fields deleted for brevity> */
     TCHAR lfFaceName[32];
   } LOGFONT;

This structure can be expressed in Java using an extension syntax to specify the size.

   /** @dll.struct() */
   class LOGFONT {
     int lfHeight;
     int lfWidth;
     /* <many other fields deleted for brevity> */
     /** @dll.structmap([type=TCHAR[32]]) */
     String	lfFaceName;
   }

The @dll.structmap directive indicates the size of the fixed string as measured in characters (including space for the null terminator).

Fixed-size Scalar Arrays Embedded within Structures

Fixed-size arrays of scalars embedded in structures can be specified using the @dll.structmap directive. Here is a C language structure that contains fixed-size scalar arrays.

struct EmbeddedArrays
{
  BYTE     b[4];
  CHAR     c[4];
  SHORT    s[4];
  INT      i[4];
  __int64  l[4];
  float    f[4];
  doubl    d[4];
};

You can specify the EmbeddedArrays structure by using @dll.structmap in the following way.

/** @dll.struct() */
class EmbeddedArrays
{
    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    byte b[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    char c[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    short s[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    int i[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    long l[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    float f[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    double d[];

}

Structure Packing

Structure fields are padded and aligned according to ANSI 3.5.2.1. The packing size can be set using the pack modifier.

   /** @dll.struct(pack=n) */

where n can be 1, 2, 4 or 8. The default is 8. For users of the Microsoft® Visual C++® compilers, "pack=n" is equivalent to "#pragma pack(n)".

The Relationship Between @dll.struct and @com.struct

The @dll.struct directive is very similar to the @com.struct directive emitted by the jactivex tool and emitted (implicitly) by the javatlb tool. (The javatlb tool has been replaced by jactivex.) The main difference is that the default type mappings are suited for Microsoft® Windows® function calling instead of COM object calling. Given this information, it follows that you can also generate @dll.struct classes by describing the structure in a type library and using jactivex to generate the Java class. However, it's usually faster to generate the classes manually.

Pointers

Java does not support a pointer data type. However, instead of passing a pointer, you can pass a one-element array. You can store pointers in Java integers, and you can read and write data from raw pointers.

Return Value Pointers

Win32 functions that have multiple return values typically handle them by having the caller pass a pointer to a variable to be updated. For example, the GetDiskFreeSpace function has the following prototype.

   BOOL GetDiskFreeSpace(LPCTSTR szRootPathName,
                         DWORD  *lpSectorsPerCluster,
                         DWORD  *lpBytesPerCluster,
                         DWORD  *lpFreeClusters,
                         DWORD  *lpClusters);

GetDiskFreeSpace is typically called as follows.

DWORD sectorsPerCluster, bytesPerCluster, freeClusters, clusters;
GetDiskFreeSpace(rootname, &sectorsPerCluster,
                 &bytesPerCluster, &freeClusters, &clusters);

In Java, this is just a special case of passing scalar arrays where the array size is one element. The following example shows how to call the GetDiskFreeSpace function.

class ShowGetDiskFreeSpace
{
  public static void main(String args[])
  {
    int sectorsPerCluster[] = {0};
    int bytesPerCluster[] = {0};
    int freeClusters[] = {0};
    int clusters[] = {0};
    GetDiskFreeSpace("c:\\", sectorsPerCluster, bytesPerCluster,
                     freeClusters, clusters);
    System.out.println("sectors/cluster  = " + sectorsPerCluster[0]);
    System.out.println("bytes/cluster = " + bytesPerCluster[0]);
    System.out.println("free clusters = " + freeClusters[0]);
    System.out.println("clusters = " + clusters[0]);
  }

  /** @dll.import("KERNEL32") */
  private native static boolean GetDiskFreeSpace(String rootname,
                   int pSectorsPerCluster[], int pBytesPerCluster[],
                   int pFreeClusters[], int pClusters[]);
}

Raw Pointers

A pointer to an unknown or particularly difficult structure can be stored in a plain Java integer. If your application only needs to store the pointer and not dereference it, this is the simplest (and most efficient) approach. You might want to use this technique to store a pointer that has been returned by a DLL function that allocates a memory block. In fact, you can use this technique to store a pointer returned by any DLL function. Needless to say, using raw pointers eliminates many of the safety advantages of Java. So, an alternative approach should be used whenever possible. However, there are situations when you might choose to use raw pointers. With that in mind, there are two ways to read and write data from raw pointers.

Casting to a Reference to an @dll.struct Class

One way to read and write data through a raw pointer is to cast the raw pointer to a reference to an @dll.struct class. Once this is done, you can read and write the data using normal field access syntax. For instance, suppose you have a raw pointer that you wish to access as a RECT. You can use the system method DllLib.ptrToStruct as follows.

  /** @dll.struct() */
  class RECT {
    int left;
    int top;
    int right;
    int bottom;
  }

  import com.ms.dll.*;

  int  rawptr = ...;
  RECT rect = (RECT)DllLib.ptrToStruct(RECT.class, rawptr);
  rect.left = 0;
  rect.top = 0;
  rect.right = 10;
  rect.bottom = 10;

The ptrToStruct method wraps the raw pointer in a RECT instance. Unlike instances created by the new operator, this RECT instance will not attempt to free the raw pointer upon reclamation by the garbage collector because the RECT object has no way of knowing how the pointer was allocated. In addition, because the native memory was already constructed at the time ptrToStruct was called, the RECT class constructor is not called.

Using the DllLib Copy Methods

Another method for reading and writing data through a raw pointer is to use the overloaded copy methods in DllLib. These methods copy data between Java arrays of various types and raw pointers. If you need to treat a raw pointer as a pointer to a string (LPTSTR), you can use one of the DllLib methods ptrToStringAnsi, ptrToStringUni, or ptrToString to parse the string and convert it into a java.lang.String object.

  import com.ms.dll.*;

  int rawptr = ...;
  String s = DllLib.ptrToStringAnsi(rawptr);

Warning: All Java objects are subject to movement in memory or reclamation by the garbage collector. Therefore, you should not attempt to obtain a pointer to a Java array by calling a DLL function that does generic casting. The following example shows you an incorrect way to obtain the pointer.

  // Do not do this!
  /** @dll.import("MYDLL") */
  private native static int Cast(int javaarray[]);

  // Inside MYDLL.DLL
  LPVOID Cast(LPVOID ptr)
  {
    // Do not do this!
    return ptr; // comes in as a Java array; goes out as a Java int
  }

The value of ptr is guaranteed to be valid only for the duration of the call to the Cast function. This is because VM implementations are allowed to implement passing of arrays by copying rather than pinning and because garbage collection may cause the physical location of the array to be different after the call to the Cast function returns.

Polymorphic Parameters

Some Win32 functions declare a parameter whose type depends on the value of another parameter. For example, the WinHelp function is declared as follows.

  BOOL WinHelp(int hwnd, LPCTSTR szHelpFile, UINT cmd, DWORD dwData);

The innocent-looking dwData parameter can actually be any one of the following: a pointer to a string, a pointer to a MULTIKEYHELP structure, a pointer to a HELPWININFO, or a plain integer, depending on the value of the cmd parameter.

J/Direct offers two ways to declare such a parameter:

  • Declare the parameter to be type Object.
  • Use overloading to declare a separate method for each possible type.

Declaring the Parameter as Type Object

Here is how to declare WinHelp by declaring dwData as type Object.

  /** @dll.import("USER32") */
  static native boolean WinHelp(int hwnd, String szHelpFile,
                                int cmd, Object dwData);

When WinHelp is invoked, J/Direct will use the runtime type to determine how to translate dwData. The following table describes how the types are translated.

Type | Translated as
java.lang.Integer | 4-byte integer
java.lang.Boolean | 4-byte BOOL
java.lang.Char | CHAR (or WCHAR if the unicode or ole modifiers are in effect)
java.lang.Short | 2-byte SHORT
java.lang.Float | 4-byte FLOAT
java.lang.String | LPCSTR (or LPCWSTR if the unicode or ole modifier is in effect)
java.lang.StringBuffer | LPSTR (or LPWSTR if the unicode or ole modifier is in effect)
byte[] | BYTE*
char[] | CHAR* (or WCHAR* if the unicode or ole modifier is in effect)
short[] | SHORT*
int[] | INT*
long[] | __int64
float[] | float*
double[] | double*
@dll.struct | pointer to structure

Overloading the Function

Another way to declare the WinHelp function is to overload the function for each possible type.

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, int dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, String dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, MULTIKEYHELP dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, HELPWININFO dwData);

You cannot handle a polymorphic return value using overloading because Java methods cannot be overloaded on return value only. Therefore, you need to give each variant of the function a different Java name and use the entrypoint modifier to link them all to the same DLL method. (See Aliasing (Method Renaming) to learn more about renaming DLL methods.)

Comparison Between the Two Methods

In most cases (including the WinHelp case), overloading is the preferred approach because it offers superior run time performance as well as better type checking. In addition, overloading avoids the need to wrap integer arguments inside an Integer object.

However, declaring the parameter as type Object can be useful in cases where there is more than one polymorphic parameter. You might also choose this method when you want to access a service that acts generically on a wide variety of types, such as a function that can accept any object declared with @dll.struct.

Callbacks

You can write callbacks in Java by extending the system class com.ms.dll.Callback.

Declaring a Method that Takes a Callback

To represent a callback parameter in Java, declare the Java type to be either type com.ms.dll.Callback or a class that derives from Callback. For example, the Microsoft® Win32® EnumWindows function is prototyped as follows.

  BOOL EnumWindows(WNDENUMPROC wndenumproc, LPARAM lparam);

The corresponding Java prototype is shown in the following example.

  import com.ms.dll.Callback;
  /** @dll.import("USER32") */
  static native boolean EnumWindows(Callback wndenumproc,
                                    int lparam);

Invoking a Function that Takes a Callback

To invoke a function that takes a callback, you need to define a class that extends Callback. The derived class must expose one non-static method whose name is callback (all lowercase). Continuing with the EnumWindows previous example, the C language definition of WNDENUMPROC looks like this.

  BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lparam);

To author an EnumWindowsProc in Java, you declare a class that extends Callback as follows.

  class EnumWindowsProc extends Callback
  {
    public boolean callback(int hwnd, int lparam)
    {
      StringBuffer text = new StringBuffer(50);
      GetWindowText(hwnd, text, text.capacity()+1);

      if (text.length() != 0) {
        System.out.println("hwnd = " + Integer.toHexString(hwnd) +
                           "h: Text = " + text);
      }
      return true;  // return TRUE to continue enumeration.
    }

  /** @dll.import("USER32") */
  private static native int GetWindowText(int hwnd, StringBuffer text,
                                          int cch);
  }

You can invoke EnumWindows with this Callback in the following way.

  boolean result = EnumWindows(new EnumWindowsProc(), 0);

Restrictions on Types Accepted by the Callback Method

The return type of the callback method must be void, int, boolean, char, or short. The only parameter type currently allowed is the int type. Fortunately, this is not as restrictive as it sounds. You can use the DllLib methods ptrToStringAnsi, ptrToStringUni, and ptrToString to treat a parameter as an LPTSTR. You can use the ptrToStruct method to treat a parameter as a pointer to an @dll.struct class.

Associating Data with a Callback

Frequently, it is necessary to pass some data from the caller of the function to the callback. This explains why EnumWindows takes an extra lparam argument. Most Win32 functions that take callbacks accept one extra 32-bit parameter that is passed to the callback without interpretation. With the Callback mechanism, it is not necessary to pass data using the lparam argument. Because the callback method is non-static, you can store your data as fields in the EnumWindowsProc object.

The Lifetime of a Callback

Some care is required to ensure that the Callback is not reclaimed by garbage collection before the native function is finished with it. If the callback is short-term (only callable for the duration of one function call), no special action is required because a Callback passed to a DLL function is guaranteed not to be reclaimed by garbage collection while the call is in progress.

If a callback is long-term (used across function calls), you will need to protect the Callback from being reclaimed, typically by storing a reference to it in a Java data structure. You can also store references to Callbacks within native data structures by using the com.ms.dll.Root class to wrap the Callback inside a root handle. The root handle is a 32-bit handle that prevents the Callback from being reclaimed until the handle is explicitly freed. For example, a root handle to a WndProc can be stored in the application data area of an HWND structure, and then explicitly freed on the WM_NCDESTROY message.

Embedding a Callback Inside a Structure

To embed a callback inside a structure, you can first call the com.ms.dll.Root.alloc method to wrap the Callback in a root handle. Then pass the root handle to the DllLib.addrOf method to obtain the actual (native) address of the callback. Then, store this address as an integer.

For example, the WNDCLASS structure can be declared in Java as follows.

  /** @dll.struct() */
  class WNDCLASS {
    int style;
    int	lpfnWndProc; // CALLBACK
    ... /* <other fields deleted for brevity> */
  }

Let's assume you have extended Callback as follows.

  class WNDPROC extends Callback
  {
    public int callback(int hwnd, int msg, int wparam, int lparam)
    {
    ...
    }
  }

To store a pointer to the callback inside the WNDCLASS object, use the following sequence.

  import com.ms.dll.*;

  WNDCLASS wc = new WNDCLASS();
  int callbackroot = Root.alloc(new WNDPROC());
  wc.lpfnWndProc = DllLib.addrOf(callbackroot);


Invoking OLE API Functions

In this topic

* OLE Mode Syntax

* How Win32 Functions Compare with OLE Functions

* Comparing Win32 Code to OLE Code

* Invoking OLE Functions

* How OLE Mode Works

* Passing and Receiving Strings from OLE Functions

* Passing GUIDs (and IIDs and CLSIDs)

* Passing VARIANTs

* Passing COM Interface Pointers

JDirect | Previous | JDirect | Next
About J/Direct | Previous | JDirect | Next

Invoking OLE API Functions

OLE Mode Syntax

The @dll.import directive includes a special mode tailored for importing OLE API functions. To use this mode, simply include the ole modifier as in the following example.

  /** @dll.import("OLE32", ole) */
  public class OLE32 {
    ...
  }

How Win32 Functions Compare with OLE Functions

In theory, the functions exported out of OLE32.DLL and OLEAUT32.DLL are no different from any other DLL function. In practice, the OLE functions follow a consistent calling style of their own. OLE functions differ from Win32 functions in the following ways:

  • OLE functions only come in Unicode. There are no ANSI OLE functions.
  • Virtually all OLE functions return a 32-bit status code known as an HRESULT through the normal function return value. The high-bit indicates whether the function succeeded (hi-bit off) or failed (hi-bit on). A few functions return multiple success values (typically S_OK and S_FALSE) but most return only one success value (S_OK).
  • If an OLE function returns some value other than the status code, it does so by having the caller supply a pointer to a variable that will receive the value on exit. This return value pointer is, by convention, the last parameter.
  • The Win32 style of returning strings is to fill in a caller-allocated buffer. OLE functions typically return strings by allocating them using CoTaskMemAlloc and expecting the caller to free them using CoTaskMemFree.

Comparing Win32 Code to OLE Code

The code for a simple Add function would look like this in the Win32 style of coding.

  int sum;
  sum = Add(10, 20);

In OLE style, the Add function would be written the following way.

  HRESULT hr;
  int sum;
  hr = Add(10, 20, &sum);
  if (FAILED(hr)) {
    ...handle error..
  }

Invoking OLE Functions

The ole mode takes advantage of this consistent coding style to provide a Java-friendly way to call OLE functions. Invoking an OLE-style Add function from Java looks much like invoking a more traditional Win32-style function.

  /** dll.import("OLELIKEMATHDLL", ole) */
  private native static int Add(int x, int y);
  int sum = Add(10, 20);
  // if we got here, Add succeeded.

How OLE Mode Works

Because of the ole modifier, the Microsoft Win32 VM for Java automatically assumes that the native Add function returns an HRESULT. The Microsoft VM notices that the Add function returns an integer. When invoking Add, the VM automatically allocates a temporary variable of type int and inserts a pointer to it as a third parameter. After the native Add function returns, the VM automatically checks the HRESULT and if it indicates a failure (high-bit on), a Java exception of type com.ms.com.ComFailException is thrown. If the HRESULT does not indicate a failure, the VM retrieves the Add function's true return value from the temporary variable it created, and it returns that value.

Unlike Java/COM integration, a return value of S_FALSE does not cause a ComSuccessException to be thrown. If you need to distinguish between success results, you need to use normal DLL calling mode and treat the HRESULT as an integer return value.

To summarize, ole mode alters the semantics of DLL calling as follows:

  1. All strings and characters are assumed to be Unicode.
  2. The function return value of the native function is presumed to be an HRESULT. The Microsoft VM throws a ComFailException if the returned HRESULT indicates failure.
  3. If the Java method return type is not void, the Microsoft VM will assume that the native function returns an additional result through a pointer, which is the final argument to the function. The VM will supply this pointer argument and dereference it after the call to obtain the additional return value. This value will be returned as the value of the Java method.

Passing and Receiving Strings from OLE Functions

Declaring a parameter as type String on an ole mode function passes a LPCOLESTR. The Microsoft VM also includes a preceding length prefix so the string can also be treated as a BSTR.

Declaring a return value as type String in ole mode causes the Microsoft VM to pass a pointer to an uninitialized LPCOLESTR*. When the native function returns, the Microsoft VM will convert the returned LPCOLESTR to a Java String, and then call CoTaskMemFree to free the string.

Passing GUIDs (and IIDs and CLSIDs)

The system class com.ms.com._Guid is used to represent GUIDs. Passing a _Guid object as a parameter passes a pointer to a GUID to the native function. Declaring a return type of _Guid causes the Microsoft VM to pass a pointer to an uninitialized GUID that the function fills in (in ole mode only).

For example, OLE32 exports the functions CLSIDFromProgID and ProgIDFromCLSID to map between CLSIDs and the human-readable names used by the Visual Basic function CreateObject. These functions have the following prototypes.

HRESULT CLSIDFromProgID(LPCOLESTR szProgID, LPCLSID pclsid);
HRESULT ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *lpszProgId);

In Java, you would declare these methods in the following way.

  import com.ms.com._Guid;
  class OLE {
    /** @dll.import("OLE32", ole) */
    public static native _Guid CLSIDFromProgID(String szProgID);

    /** @dll.import("OLE32", ole) */
    public static native String ProgIDFromCLSID(_Guid clsid);
  }

Do not confuse com.ms.com._Guid with com.ms.com.Guid (with no underscore). The latter is an obsolete class.

Passing VARIANTs

Declaring a parameter to be type com.ms.com.Variant passes a pointer to a VARIANT to the native function. Declaring a return value to be type com.ms.com.Variant (ole-mode only) passes a pointer to an uninitialized Variant for the native function to fill in.

Passing COM Interface Pointers

To pass a COM interface pointer, you must generate a Java/COM interface class using a tool such as jactivex.exe. You can then pass or receive COM interfaces by declaring a parameter to be of that interface type.

For example, the system class com.ms.com.IStream is a Java/COM interface that represents the Structured Storage IStream* interface. The OLE32 function CreateStreamOnHGlobal could be declared as follows.

import com.ms.com.*;
/** @dll.import("OLE32", ole) */
public static native IStream CreateStreamOnHGlobal(int hGlobal,
                                     boolean fDeleteOnRelease);

Java/COM integration is a complex topic and a full discussion is beyond the scope of this documentation. For more information, see the Low-Level Java/COM Integration article.


Aliasing (Method Renaming)

Sometimes you want to use a name for the Java method that is different from the name that the DLL uses when it exports the function. For example, you might want to have the Java name start with a lowercase letter so that it conforms to Java naming conventions. To do so, just use @dll.import with the entrypoint modifier as in the following example.

  /** @dll.import("USER32", entrypoint="GetSysColor") */
  static native int getSysColor(int nIndex);

You do not need to use aliasing to perform the ANSI/Unicode suffixing done by the Win32 APIs. The Microsoft Win32 VM for Java automatically takes care of this (see How the VM Chooses Between ANSI and Unicode). Aliasing is also unnecessary when accessing functions that have been exported by a .def file. Such names are typically exported using "stdcall mangling." That is, a method such as the following sample method would be renamed to _sample@8 (where 8 denotes the number of parameter bytes accepted by the function).

  extern "C"
  __declspec(dllexport)
  VOID sample(int x, int y){
    ...
  }

Microsoft® J/Direct™ automatically binds to stdcall-mangled names without an explicit entrypoint.

The Microsoft VM automatically provides aliases for the following KERNEL32 API functions:

  CopyMemory   (becomes RtlMoveMemory)
  MoveMemory   (becomes RtlMoveMemory)
  FillMemory   (becomes RtlFillMemory)
  ZeroMemory   (becomes RtlZeroMemory)


Linking by Ordinal

Some DLLs export functions by ordinal (16-bit integer) rather than by name. To call such DLLs, you will need to use a method-level @dll.import directive to specify the ordinal. The syntax for ordinal linking is as follows.

  /** @dll.import("Libname", entrypoint="#ordinal") */

Note that ordinal is specified in decimal.

For example, to link a function exported as ordinal 82 in DLL "MyDll.DLL", you would write the following code.

  /** @dll.import("MyDll", entrypoint="#82") */
  public static native void MySample();


Specifying @dll.import for an Entire Class

The @dll.import directive can also be used prior to the class definition to set a library name for all native methods declared in that class. The following declaration uses @dll.import for an entire class.

/** @dll.import("KERNEL32") */ class EnvironmentStrings
{
  public static native int GetEnvironmentStrings();
  public static native int GetEnvironmentVariable(String name,
                            StringBuffer value, int ccbValue);
  public static native boolean SetEnvironmentVariable(String name,
                                                    String value);
}

It is equivalent to specifying @dll.import for each method, as in the following example.

class EnvironmentStrings
{
  /** @dll.import("KERNEL32") */
  public static native int GetEnvironmentStrings();

  /** @dll.import("KERNEL32") */
  public static native int GetEnvironmentVariable(String name,
                              StringBuffer value, int ccbValue);

  /** @dll.import("KERNEL32") */
  public static native boolean SetEnvironmentVariable(String name,
                                                    String value);
}

Using the @dll.import directive at the class level saves space in the .class file and eliminates redundant information. However, class-level @dll.import directives are not inherited by subclasses.


How the VM Chooses Between ANSI and Unicode

The simple MessageBox example that starts this document glosses over a subtle, but important fact: USER32 does not export a function named MessageBox. Because the MessageBox function takes a string, it (like all Win32 functions that deal with strings) must exist in two versions: an ANSI version and a Unicode version (named MessageBoxA and MessageBoxW, respectively). When you code a call to MessageBox in C or C++, the MessageBox "function" you call is actually a macro that expands to either MessageBoxA or MessageBoxW, depending on whether the UNICODE macro is defined.

Calling the ANSI Version of a DLL Function

By default, the Microsoft Win32 VM for Java assumes that the ANSI version of MessageBox is the one that is needed. If you import the MessageBox function using @dll.import (without a modifier) as follows,

  /** @dll.import("USER32") */
  static native int MessageBox(int hwnd, String text,
                               String title, int style);

the Microsoft VM will go through the following steps.

  1. The strings "text" and "title" are converted to ANSI null-terminated strings.
  2. The VM attempts to find an export named MessageBox in USER32.DLL.
  3. This attempt fails. The VM then appends an "A" onto the name and looks for an export named MessageBoxA.
  4. This attempt succeeds, and the VM invokes the MessageBoxA function.

Calling the Unicode Version of a DLL Function

Suppose, instead, you wanted to call the Unicode version of MessageBox. You can do this by using the unicode modifier with the @dll.import directive:

  /** @dll.import("USER32",unicode) */
  static native int MessageBox(int hwnd, String text, String title,
                               int style);

Since the unicode modifier is present, the Microsoft VM will go through the following steps.

  1. The strings "text" and "title" are converted to Unicode null-terminated strings.
  2. The VM attempts to find an export named MessageBox in USER32.DLL.
  3. This attempt fails. The VM appends a "W" onto the name and looks for an export named MessageBoxW.
  4. This attempt succeeds, and the VM invokes the MessageBoxW function.

Calling the Optimal Version of a DLL Function

Unfortunately, neither of these situations is an ideal way to invoke the Win32 functions. Using the default ANSI mode allows your code to run on any Win32 platform, but causes unnecessary performance penalties on fully Unicode systems such as Microsoft® Windows® NT. Using the unicode modifier removes the performance penalty but restricts you to running on systems that implement the Unicode API. Fortunately, you can use the auto modifier with the @dll.import directive to call the optimal version of a DLL function based on the host operating system.

Using the auto modifier gives you the best of both worlds. The following example shows how to call the optimal version of the MessageBox function.

  /** @dll.import("USER32",auto) */
  static native int MessageBox(int hwnd, String text, String title,
                               int style);

When the auto modifier is present, the Microsoft VM determines at run time whether the underlying platform supports the Unicode APIs. If Unicode is supported, the Microsoft VM acts as if the unicode modifier had been specified. Otherwise, the Microsoft VM behaves as if the ansi modifier had been specified. Thus, the auto modifier allows you to generate a single binary which runs well on both ANSI and Unicode Windows systems using the optimal API set available on the given platform.

In general, the auto modifier should be used whenever you call Windows API functions. If you are calling your own DLLs, select either ansi (the default) or unicode depending on your needs.

Here are the details of how the Microsoft VM decides whether to use ANSI or Unicode when you use the auto modifier.

  1. The VM opens the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM and looks for the DWORD-named value DllImportDefaultType. This value can be one of the following:

    2 - ANSI: Uses the ANSI version always.

    3 - Unicode: Uses the Unicode version always.

    4 - Platform: Uses ANSI or Unicode depending on the platform.

  2. If the key does not exist, or if it is set to 4 (indicating platform), the VM calls the Win32 GetVersion function and examines the high bit to determine whether the underlying platform is Microsoft® Windows® 95 or Microsoft® Windows® NT. If the platform is Windows 95, ANSI mode is used. Otherwise, Unicode mode is used.

It is not necessary to set the DllImportDefaultType registry key yourself. It exists primarily so that the installation program can set the appropriate choice on future Windows platforms. You can programatically query the preferred mode on your platform by reading the com.ms.dll.DllLib.systemDefaultCharSize field. This field will be set to 1 on ANSI systems, 2 on Unicode systems.

The ansi, unicode, and auto modifiers can also be used with the @dll.struct directive.


Obtaining the Error Code Set By a DLL Function

Do not invoke the Win32 function GetLastError to obtain an error code set by another DLL call. Because the Microsoft Win32 VM for Java may execute function calls of its own in the process of executing Java code, the error code may have been overwritten by the time you get to it.

To reliably access the error code set by a DLL function, you must use the setLastError modifier to instruct the Microsoft VM to capture the error code immediately after invoking that method. For performance reasons, this is not done by default. You can then invoke the com.ms.dll.DllLib.getLastWin32Error method to retrieve the error code. Each Java thread maintains separate storage for this value.

For example, the FindNextFile function returns status information through the error code. FindNextFile would be declared as follows.

  /** @dll.import("KERNEL32",setLastError) */
  static native boolean FindNextFile(int hFindFile,
                              WIN32_FIND_DATA wfd);

A typical call would look like this.

import com.ms.dll.DllLib;

boolean f = FindNextFile(hFindFile, wfd);
if (!f) {
  int errorcode = DllLib.getLastWin32Error();
}


Dynamically Loading and Invoking DLLs

There might be times when you need more control over the loading and linking process than the @dll.import directive normally provides. For instance, your requirements might include:

  1. Loading a library whose name or path must be computed at run time or generated from user input.
  2. Freeing a library prior to process termination.
  3. Executing a function whose name or ordinal must be computed at run time.

The Win32 APIs have always provided the ability to control loading and linking. The LoadLibrary, LoadLibraryEx, and FreeLibrary functions allow you to have explicit control over the loading and freeing of DLLs. The GetProcAddress function allows you to link to a specific export. The GetProcAddress function returns a function pointer, so any language that can call through a function pointer can implement dynamic invocation without a problem.

Microsoft® J/Direct™ allows Java programmers to declare the requisite functions in the following way. (If you are using the com.ms.win32 package, these declarations also appear in the Kernel32 class.)

/** @dll.import("KERNEL32",auto) */
public native static int LoadLibrary(String lpLibFileName);

/** @dll.import("KERNEL32",auto) */
public native static int LoadLibraryEx(String lpLibFileName,
                                       int hFile, int dwFlags);

/** @dll.import("KERNEL32",auto) */
public native static boolean FreeLibrary(int hLibModule);

/** @dll.import("KERNEL32",ansi) */
public native static int GetProcAddress(int hModule, String lpProcName);

Notice that GetProcAddress is declared with the ansi modifier, not auto. This is because GetProcAddress is one of the few Windows functions without a Unicode equivalent. If we were to use the auto modifier, this function would fail on Microsoft® Windows NT® systems.

That only leaves the problem of invoking a function obtained by GetProcAddress. For your convenience, msjava.dll, (the DLL that implements the Microsoft VM for Java) exports a special function named call. The call function's first argument is a pointer to a second function. All call does is invoke the second function, passing it the remaining arguments.

For example, here is how an application could load a DLL and call AFunction exported by the DLL.

  BOOL AFunction(LPCSTR argument);

  /** @dll.import("msjava") */
  static native boolean call(int funcptr,String argument);

  int hmod = LoadLibrary("...");
  int funcaddr = GetProcAddress(hmod, "AFunction");
  boolean result = call(funcaddr, "Hello");
  FreeLibrary(hmod);


Comparing J/Direct to Raw Native Interface

Microsoft® J/Direct™ and Raw Native Interface (RNI) are complementary technologies. Using RNI requires that DLL functions adhere to a strict naming convention, and it requires that the DLL functions work harmoniously with the Java garbage collector. That is, RNI functions must be sure to call GCEnable and GCDisable around code that is time-consuming, code that could yield, code that could block on another thread, and code that blocks while waiting for user input. RNI functions must be specially designed to operate in the Java environment. In return, RNI functions benefit from fast access to Java object internals and the Java class loader.

J/Direct links Java with existing code such as the Win32 API functions, which were not designed to deal with the Java garbage collector and the other subtleties of the Java runtime environment. However, J/Direct automatically calls GCEnable on your behalf so that you can call functions that block or perform UI without having a detrimental effect on the garbage collector. In addition, J/Direct automatically translates common data types such as strings and structures to the forms that C functions normally expect. So you don't need to write as much glue code and wrapper DLLs. The tradeoff is that DLL functions cannot access fields and methods of arbitrary Java objects. They can only access fields and methods of objects that are declared using the @dll.struct directive. Another limitation of J/Direct is that RNI functions cannot be invoked from DLL functions that have been called using J/Direct. The reason for this restriction is that garbage collection can run concurrently with your DLL functions. Therefore, any object handles returned by RNI functions or manipulated by DLL functions are inherently unstable.

Fortunately, you can use either RNI or J/Direct (or both). The compiler and the Microsoft Win32 VM for Java allow you to mix and match J/Direct and RNI within the same class as your needs dictate.


Security Issues

Although Microsoft® J/Direct™ is a very powerful feature for standalone Java applications and trusted intranet Web applications, it is clearly too powerful to be used by normal Java applets on the Web. This section describes how J/Direct works with the security system of the Microsoft Win32 VM for Java to prevent untrusted code from abusing the power provided by J/Direct.

Trusted Versus Untrusted Classes

J/Direct divides all loaded Java classes into one of two categories:

  1. Fully trusted (indicating maximum permissions).
  2. Untrusted.

Only fully trusted classes are allowed to use J/Direct. A Java class is considered fully trusted if one of the following statements is true.

  1. The class is digitally signed indicating full trust. An example of such a class would be a signed applet. To find out more about signing cabinet files, see the Creating and Using Cabinet Files article and the Signcode article in the Tools section of the Microsoft SDK for Java.
  2. The class is installed on the target computer's CLASSPATH or installed by the package manager. A downloadable digitally signed library designed to be shared among multiple applets could meet this criterion.
  3. The class is running as a non-browser application using the jview or the wjview application.

An unsigned applet on the Web, on the other hand, constitutes untrusted Java code.

Security Checkpoints for J/Direct Method Calls

The Microsoft VM applies security checks to J/Direct methods at three different times:

  1. At link time.
  2. Upon first invocation.
  3. Upon every invocation.

An attempted J/Direct call takes place only if each of the three security checks passes or is explicitly disabled.

Security Checks at Link time

Linking is what occurs when one Java class invokes or accesses (using the Reflection API) a member of another class. At link time, the Microsoft VM checks to see whether the class being referenced is accessible and whether the arguments being passed are of the correct type and number. The class is considered accessible if it is in the same package or if it is declared public.

With the standard Java language, you are limited to a choice of two options for class accessibility: you can either declare a class public (so that anyone can link to it) or non-public (so that only classes in the same package can link to it). However, with Microsoft® Internet Explorer 4.0, there is now a third option. You can declare the class as "public for fully trusted callers only." You can declare any class with this type of accessibility, even if the class does not use J/Direct. To declare the class, place the following directive at the beginning of the class.

  /** @security(checkClassLinking=on) */

It is important to notice that this security check only prevents untrusted callers from directly calling the "protected" class. It does not prevent indirect calls. A third (fully trusted) class can forward a call from an untrusted caller to the "protected" class. However, there is a safeguard. The intermediate class must either be installed on the target computer's CLASSPATH, or it must be digitally signed for maximum trust and installed using the browser.

Security Checks upon First Invocation

The first invocation of a method is the first time the method is invoked from any caller. At this time, for each method marked with the native keyword, the Microsoft VM determines whether the method is a member of a fully trusted class. If it is not, a SecurityException is thrown that includes the message, "Only fully trusted classes can have native methods as members." Because this security check does not depend on the calling context, it only needs to be performed once. If it passes, the check does not take place on future invocations. There is no way to disable this security check.

Security Checks upon Every Invocation

This is the most stringent check available. On every call, the entire call stack is examined. If even one caller that is not fully-trusted is discovered on the call stack, a SecurityException is thrown. By default, all J/Direct methods perform this check. RNI methods do not perform this check because of backwards compatibility requirements. RNI was designed to allow easy porting from the original JDK 1.0 native interface, which did not offer this security check.

Although this security check offers maximum safety, Microsoft offers a way to disable it. The mechanism for disabling is provided because this stringent security check has two important side effects.

Possible Performance Degradation | This security check requires a scan of the entire call stack each time a J/Direct method is called. The performance degradation is most noticeable on trusted applets, which generally run with a security manager present. Applications, on the other hand, usually do not see a significant performance drop. This is due to the fact that J/Direct omits the call stack scan for applications that run without a security manager.
Inflexibility | This security mechanism forces the use of maximum permissions, even in cases where only one specific permission is required. For example, consider a trusted library that uses J/Direct to expose a single permission to untrusted applets in a safe way. It would be appropriate for this library to turn off the call time security check and perform its own security check for the specific permission.

The @security directive disables the per-invocation security check. Here is the syntax for this directive.

  /** @security(checkDllCalls=off) */

The @security directive applies to the entire class. Individual methods within a class cannot be tagged. The following example shows the placement of the @security directive.

  /** @security(checkDllCalls=off) */
  class FastJDirectMethods{
    /** @dll.import(...) */
    static native void func();
  }

Be aware of the fact that disabling this security check transfers responsibility for security from the Microsoft VM to you. Remember that even with this security check disabled, you will still have to digitally sign the class for maximum trust. If you decide to use this directive, be sure to take the following precautions:

  • All J/Direct methods should be declared private.
  • Any publicly accessible methods should never blindly pass caller arguments to J/Direct. You must take responsibility for ensuring that only valid arguments are passed to native code.
  • Your class should expose no more capability than is required, and it should guard all access to these capabilities with the appropriate security checks.

Important Note Regarding Trusted Applets: Calls from within an applet's init, start, stop, or destroy methods may trigger a SecurityExceptionEx even if the applet is trusted. To avoid this situation, you should assert permissions by executing the following code.

  import com.ms.security.*;
    ...
  PolicyEngine.assertPermission(PermissionID.SYSTEM);

Security Checkpoints for J/Direct Structures

J/Direct also imposes security restrictions on classes that are marked using the @dll.struct compiler directive. Because structures only become unsafe when they are instantiated, these security checks are more efficient than the checks used for J/Direct methods. The following two security checks are performed on @dll.struct classes.

Load time | Classes marked with @dll.struct will load only if the context indicates full trust.
Link time | Code that is not fully trusted cannot link to classes declared using @dll.struct. The Microsoft VM will throw a NoClassDefFoundError if such an attempt is made.

Security and the com.ms.win32 Classes

For maximum security, the J/Direct methods defined in the com.ms.win32 package do perform the call stack check on each invocation. If you are using these classes for a Java application (running under jview or wjview), the performance overhead will be negligible. If you are using com.ms.win32 classes from a trusted class and require maximum performance, you should copy the required J/Direct declarations into your own classes and disable the per-invocation security check. See the Security Checks upon Every Invocation section for more information on disabling the per-invocation security check.


Error Messages

There are several types of exceptions that might be thrown by the Microsoft Win32 VM for Java when you are using Microsoft® J/Direct™. For each of the following errors, possible causes and solutions are explained.

java.lang.SecurityException [class.method]: Only fully trusted classes can have native methods as members.

java.lang.IllegalAccessError: Class has been marked as nonpublic to untrusted code.

java.lang.SecurityException: J/Direct method has not been authorized for use on behalf of an untrusted caller.

java.lang.NoClassDefFoundError

com.ms.security.SecurityExceptionEx: [host] J/Direct method has not been authorized for use on behalf of an untrusted caller.

java.lang.SecurityException [class.method]: Only fully trusted classes can have native methods as members.

Exception Class | java.lang.SecurityException
Message | class.method: Only fully trusted classes can have native methods as members.
Possible Causes | The native keyword has been used on a method that is a member of a class that is not loaded with full permissions (for example, an unsigned applet). This exception is thrown only if an attempt is made to invoke the native method.
Possible Solutions | Digitally sign your applet requesting full permissions. For more information on signing applets, see the article on Signing a Cabinet File with Java Permissions Using Signcode.

java.lang.IllegalAccessError: Class has been marked as nonpublic to untrusted code.

Exception Class | java.lang.IllegalAccessError
Message | Class has been marked as nonpublic to untrusted code.
Possible Causes An untrusted class has attempted to refer to a field or method of another class that has been marked for trusted use only. Many of the system classes in the com.ms.com and com.ms.dll packages have been marked this way. A class can be marked as nonpublic to untrusted code using the @security directive in the following way:

  /** @security(checkClassLinking=on) */
  public class ForTrustedUseOnly{
   ...
  }

Possible Solutions | Digitally sign your applet requesting full permissions. For more information on signing applets, see the article on Signing a Cabinet File with Java Permissions Using Signcode.

java.lang.SecurityException: J/Direct method has not been authorized for use on behalf of an untrusted caller.

Exception Class | java.lang.SecurityException
Message | J/Direct method has not been authorized for use on behalf of an untrusted caller.
Possible Causes | An untrusted class has invoked a trusted method that attempts to make a J/Direct call. Even if the class making the actual J/Direct call is trusted, the security manager will throw a SecurityException if any of the methods in the call stack belong to an untrusted class.
Possible Solutions Digitally sign your applet requesting full permissions. For more information on signing applets, see the article on Signing a Cabinet File with Java Permissions Using Signcode. Or, you could disable the security check by marking the class that attempts the J/Direct call with the @security directive, as shown in the following example.

  /** @security(checkDllCalls=off) */
  public class SafeDllCalls{
   ...
  }

Note: Disabling this security check transfers responsibility for security from the Microsoft VM for Java to you. Remember that even with this security check disabled, you will still have to digitally sign the class for maximum trust. If you use the @security directive, you should ensure that the following statements are true.

  • All J/Direct methods are declared private.
  • Your class exposes only the functionality needed by the client.
  • Your class guards all access to these capabilities with appropriate security checks.

java.lang.NoClassDefFoundError

Exception Class | java.lang.NoClassDefFoundError
Message | None.
Possible Causes | An untrusted class has attempted to load either a class marked with @dll.struct or a class generated using the jactivex tool. Although this is really a security violation (not a class loader error), a NoClassDefFoundError is thrown for backwards compatibility purposes.
Possible Solutions | Digitally sign your applet requesting full permissions. For more information on signing applets, see the article on Signing a Cabinet File with Java Permissions Using Signcode.

com.ms.security.SecurityExceptionEx: [host] J/Direct method has not been authorized for use on behalf of an untrusted caller.

Exception Class | com.ms.security.SecurityExceptionEx
Message | [host] J/Direct method has not been authorized for use on behalf of an untrusted caller.
Possible Causes | A J/Direct call was attempted from the init, start, stop, or destroy method of an applet. To make J/Direct calls during these methods, the applet must assert permissions even if the applet has been signed.
Possible Solutions Execute the following code to assert permissions.

  import com.ms.security.*;
    ...
  PolicyEngine.assertPermission(PermissionID.SYSTEM);


Troubleshooting Tips

In this topic

* UnsatisfiedLinkError When Calling a Method

* Getting SecurityException When Calling a DLL Method or Using an @dll.struct Class

* StringBuffers Truncated on Return From DLL Function

* Mysterious Syntax Errors Within @dll Directives

* Compiler Cannot Find Basic System Packages Like java.lang

* Compiler Cannot Find the com.ms.dll Package

* Syntax Errors When Using J/Direct with Inner Classes

* @dll Directives Do Not Work on Applets (or Only Works Within the Microsoft Visual J++ Environment)

* Using J/Direct Makes Class Unusable

* J/Direct Throws a ParameterCountMismatchError After Calling a Native Function

* J/Direct Does Not Unload a DLL

JDirect | Previous | JDirect | Next
About J/Direct | Previous | JDirect | Next

Troubleshooting Tips

The following topics describe problems that you might encounter when using Microsoft® J/Direct™. For each situation, possible solutions are provided.
UnsatisfiedLinkError When Calling a Method
Getting SecurityException When Calling a DLL Method or Using an @dll.struct Class
StringBuffers Truncated on Return From DLL Function
Mysterious Syntax Errors Within @dll Directives
Compiler Cannot Find Basic System Packages Like java.lang
Compiler Cannot Find the com.ms.dll Package
Syntax Errors When Using J/Direct with Inner Classes
@dll Directives Do Not Work on Applets (or Only Works Within the Microsoft Visual J++ Environment)
Using J/Direct Makes Class Unusable
J/Direct Throws a ParameterCountMismatchError After Calling a Native Function
J/Direct Does Not Unload a DLL

UnsatisfiedLinkError When Calling a Method

  • Check the version of your compiler to see that you have a compatible compiler. (To display the version number, execute jvc with no arguments on the command line.) The Microsoft SDK for Java supplies a version of the compiler that supports J/Direct. See the SDK release notes for the version number that corresponds to that release. If your compiler does not support J/Direct, the Microsoft Win32 VM for Java will attempt to link native methods using the Raw Native Interface and will not succeed.
  • Make sure your DLL is visible on the system path. DLLs are searched for in the following locations (in order):
    1. The directory from which the application (typically jview) loaded.
    2. The current directory.
    3. The Windows system directory.
    4. The Windows directory.
    5. The directories listed in the PATH environment variable.

    The Microsoft VM will not attempt to load the DLL until a method requiring it is actually called. Therefore, do not assume that the DLL load was successful simply because the Java class loaded successfully.

  • Check the method qualifiers. Methods declared with the @dll.import directive must be native and static. They can have any level of access (public, private, and so on) supported by the Java language.
  • Make sure that your method name matches the DLL export name exactly, including capitalization. The DLL linking mechanism in Win32 is case-sensitive.
  • If you still have trouble linking to a method, use a utility such as dumpbin/exports (Visual C++) to verify that the DLL exports the method by the name you are using. Some DLLs may require you to link to exports by ordinal (an integer) rather than a name. In such a case, use the entrypoint override on the method using the "#ordinal" syntax as in the following example.

  // This method is exported as ordinal #34.
  /** @dll.import("MyDll",entrypoint="#34") */
  public static native void MySample();
  • Be aware that some so-called functions are actually C macros and the actual DLL export name may be quite different from the name of the macro.

Getting SecurityException When Calling a DLL Method or Using an @dll.struct Class

DLL calling and the use of @dll.struct classes is restricted to Java applications and signed Java applets. For more information about signing applets, see the article on Signing a Cabinet File with Java Permissions.

StringBuffers Truncated on Return From DLL Function

You must ensure that the StringBuffer's capacity is sufficient to contain the string you need before you invoke the DLL function. You can specify the capacity in the StringBuffer's constructor, and you can use the StringBuffer.ensureCapacity method to guarantee a minimum capacity prior to the DLL call.

Mysterious Syntax Errors Within @dll Directives

Extra white space within @dll.import and @dll.struct directives can cause syntax errors. Avoid using white space inside @dll constructs.

Compiler Cannot Find Basic System Packages Like java.lang

The compiler shipped with SDK for Java looks for system packages in the classes.zip file. This conflicts with the new Package Management scheme used by the Microsoft VM, which stores system packages as .zip files with obfuscated names under the %WINDIR%\java\packages directory. Unfortunately, the Java Language Compiler has not yet been updated to recognize this new scheme. To compile Java programs against the new VM, you must create an old-style .zip file and ensure that it is included in the CLASSPATH.

Normally, the SDK installation program does this for you. If, however, you installed the SDK by some other method, or if your configuration has been corrupted since the installation, you may need to recreate CLASSES.ZIP. The easiest way to do this is to type clspack -auto at the MS-DOS® command prompt. This will create a single CLASSES.ZIP in your %WINDIR%\java\Classes directory that contains all classes stored in the package manager. The Microsoft compiler for Java looks for classes in this location by default, so there is no need to set your CLASSPATH environment variable.

Compiler Cannot Find the com.ms.dll Package

An older version of classes.zip is being used. Try renaming all older versions of classes.zip on your disk drive and follow the instructions under Compiler Cannot Find Basic System Packages Like java.lang for creating a new classes.zip file.

Syntax Errors When Using J/Direct with Inner Classes

The version of the Java compiler that ships with the SDK for Java does not correctly handle @dll directives on inner classes or classes that contain inner class declarations.

@dll Directives Do Not Work on Applets (or Only Works Within the Microsoft Visual J++ Environment)

Because the use of J/Direct can compromise security, its use is restricted to Java applications and signed Java applets. See Signing a Cabinet File with Java Permissions for more information about signing applets.

Using J/Direct Makes Class Unusable

Any use of J/Direct within a class marks that class as unsafe and unusable by untrusted code, even if the J/Direct methods are not actually invoked.

J/Direct Throws a ParameterCountMismatchError After Calling a Native Function

The ParameterCountMismatchError exception alerts you to the fact that the called function consumed (popped off the stack) more or fewer parameters than was passed by J/Direct. This error normally indicates that the parameters in the Java method declaration do not match up with the parameters expected by the DLL function.

If the function pops off no arguments, it is assumed to be using the cdecl calling convention and an exception is not thrown, even if the Java method declares a non-zero number of arguments.

Caution You should not attempt to catch and deal with the ParameterCountMismatchError exception. This exception was designed to assist developers in catching bugs during the development stage. For performance reasons, parameter count checking is performed only when the application is running under a Java debugger. It is also important to note that J/Direct performs this check after the function call has been completed. Because this exception indicates that one or more invalid parameters might have been passed to the function call, it cannot be guaranteed that the process can recover.

J/Direct Does Not Unload a DLL

J/Direct unloads a DLL when the Microsoft VM discards the Java class that imported the DLL. For a Java application running under jview, this does not occur until the process exits. For a trusted Java applet, this happens at some undetermined time after the browser has left the page containing the applet. The Microsoft VM attempts to keep Java classes loaded for several pages afterward in order to optimize applet refresh time in case the page is revisited.

If you need explicit control over the loading and unloading of DLLs, you need to call the Windows loader explicitly and use the call entrypoint to invoke functions dynamically. For more information on how to do this, see the section in this article on Dynamically Loading and Invoking DLLs.


Frequently Asked Questions

In this section, answers to the following questions about Microsoft® J/Direct™ are provided.
What versions of the Microsoft Compiler for Java support J/Direct?
What versions of the Microsoft Win32 Virtual Machine for Java support J/Direct?
Where can I find more code samples that use J/Direct?
Where can I get prewritten declarations for the Win32 functions and constants?
How can I programatically learn whether the auto modifier will select Unicode or ANSI on a given platform?
Where I can find more services helpful for DLL calling?
How do I obtain the application instance handle?
How do I obtain the parameters passed to the WinMain function?
How do I turn my Java application into an .exe file?

What versions of the Microsoft Compiler for Java support J/Direct?

The version of the compiler available with the Microsoft SDK for Java version 2.5 supports J/Direct. Use that version or later. To display the version number, execute jvc with no arguments on the command line. If you are copying the compiler manually, be aware that the Microsoft compiler is composed of three executables: jvc.exe, jps.dll, and msjvc.dll. See the SDK release notes for version numbers corresponding to that release.

What versions of the Microsoft Win32 Virtual Machine for Java support J/Direct?

The version of the Microsoft VM available with the SDK for Java version 2.5 and with Internet Explorer 4.0 supports J/Direct. Use that version or later. See the SDK release notes for version numbers corresponding to that release.

To find out what version is installed using Windows Explorer, you need to find the executable msjava.dll, which is normally installed in your windows\system directory. Make sure that Windows Explorer is configured to show all files. (To do this, open the windows\system folder, pull down the View menu, select the Options item to display the Options dialog box. Select the view tab, and select Show all files.) Find msjava.dll in the folder and right-click it. From the pop-up menu, select the Properties item to display the Properties dialog box. Select the Version tab. You will see the version number displayed next to File Version.

Where can I find more code samples that use J/Direct?

You can find code samples under \MsVmJava\Samples\JDirect\ in the directory in which you install the SDK for Java.

Where can I get prewritten declarations for the Win32 functions and constants?

Prewritten declarations for the most common Win32 functions and constants can be downloaded separately. From the SDK for Java 2.5 Component Download menu, select the check box next to Win32 API Java Package.

How can I programatically learn whether the auto modifier will select Unicode or ANSI on a given platform?

The system class com.ms.dll.DllLib has a public integer field named systemDefaultCharSize. Its value is set to 1 (for ANSI) or 2 (for Unicode).

Where I can find more services helpful for DLL calling?

The com.ms.dll package includes several classes (especially DllLib) that contain useful methods for extracting strings from native memory blocks, mapping raw pointers onto @dll.struct classes, copying bytes between various types, and other helpful tasks.

How do I obtain the application instance handle?

Many Windows functions (in particular, the USER32 functions) require the application instance handle as a parameter. In Win32, an instance handle is defined to be the same as a module handle. Thus, the instance handle can be obtained by passing NULL to the GetModuleHandle function.

  /** @dll.import("KERNEL32") */
  private static native int GetModuleHandle(String modName);

  int hInst = GetModuleHandle(null);

How do I obtain the parameters passed to the WinMain function?

Windows applications written in C have a WinMain function where execution begins. Java applications written in C have a main function instead.

The Microsoft® Windows® operating system passes four parameters to WinMain. Here is how to obtain these values from Java.
The application instance handle: | Pass NULL to the GetModuleHandle function. For more information, see the How do I obtain the application instance handle? FAQ in this section.
The previous instance handle: | In Win32, this value is always NULL.
The command line: | Passed as the String args[] parameter to main.
The default value to pass to ShowWindow: | Can be obtained by GetStartupInfo. However, Microsoft® Win32® applications are encouraged to pass SW_SHOWDEFAULT to ShowWindow rather than using the value passed to WinMain.

How do I turn my Java application into an .exe file?

The jexegen tool can be used to create an .exe file that can be launched like a normal Windows application. When using jexegen, you can select whether to build a GUI executable or a console executable. The default is console, but you can select GUI by specifying the /W switch. For example, consider the following Java application.

public class app
{
  public static void main(String args[])
  {
    int hInst = GetModuleHandle(null);
    MessageBox(0,"Instance handle is " +
               Integer.toHexString(hInst),"",0);
  }

  /** @dll.import("KERNEL32") */
  private static native int GetModuleHandle(String modName);

  /** @dll.import("USER32") */
  private static native int MessageBox(int hWndOwner,String text,
                                       String title,int fuStyle);
}

This class can be converted to a GUI executable by executing the following command lines.

  jvc app
  jexegen /W /out:app.exe /main:app *.class

For details on the using the jexegen tool, see the Introduction to Jexegen article.


Articles and References For Using Java with Native Code

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Java & Native Code | Welcome! | Next
 | Welcome! | Next

Articles and References For Using Java with Native Code

The Microsoft Win32 VM for Java enables access to native code libraries and components from Java. The following articles and references show how this can be accomplished and describe the best approach based on your needs.

Articles

These articles provide overview information on the various paths you can take in mixing Java and native code.

  • Mixing Java and Native Code
  • About J/Direct
  • Low-Level Java/COM Integration
  • Using Jactivex to Create a User-Defined Type for Java/COM Marshaling
  • Introduction to Using the Raw Native Interface
  • Native Code Interface Specification

References

The following references describe the packages and API elements for implementing Java and native code integration:
Package com.ms.dll | A package used for Microsoft® J/Direct™.
Package com.ms.activeX | A package used for ActiveX/Beans integration.
Package com.ms.com | A package used for low-level Java/COM integration.
Raw Native Interface Functions | The Raw Native Interface API reference.
Raw Native Interface Structures | The Raw Native Interface Structures reference.


Mixing Java and Native Code

In this topic

* J/Direct

* ActiveX/Beans Integration

* Raw Native Interface

* Low-Level Java/COM Integration

* Summary

Java & Native Code | Previous | Welcome! | Next
Mixing Java and Native Code | Previous | Welcome! | Next

Mixing Java and Native Code

Java is a powerful and sophisticated language that is taking its place alongside other widely used software development languages. Because few developers have the time to rewrite much of the useful code available in libraries written in other languages, it makes sense to understand how Java can access this code. Like any other programming language, Java embodies a set of tradeoffs, making it a good solution for some problems and a poor solution for others. The ability to mix and match code written in different languages lets developers achieve the maximum benefit from the tools at their disposal.

There are many scenarios that require Java code to call code that is written in some other language. For example, a Java developer may want to do any of the following:

  • Provide efficient algorithms where performance is an issue.
  • Take advantage of the hardware present on the host computer.
  • Take advantage of the full richness of the operating environment on the host computer.
  • Utilize the rich set of components available through other component technologies, such as COM (Component Object Model) that underlies Microsoft® ActiveX®.

Almost all class libraries, including the ones from JavaSoft's JDK, call code written in other languages to exploit some of these scenarios.

In the context of Java, any code that is not written in Java is called native code. This document does not dwell on the pros and cons of using native code versus Java code. Rather, it attempts to give the spectrum of options available to a Java programmer who wants to call native code from Java for any number of reasons.

The Microsoft Win32 VM for Java (Microsoft VM) provides many ways for Java code to call native code, as shown in the following list:

  • J/Direct, which is used primarily to call into existing dynamic-link libraries (DLLs), including the entire set of Win32 API.
  • ActiveX/Beans Integration, which automatically exposes JavaBeans components as ActiveX controls and allows ActiveX controls to be hosted as JavaBeans components. This integration is seamless and bidirectional.
  • Raw Native Interface, which allows the most efficient interaction between native code and Java code, but imposes programming requirements on the native code.
  • Low-Level Java/COM Integration, which provides Java access to dual-interface COM objects and provides access to custom marshaling of user data types between the object and Java using vtable access.

The remainder of this document discusses these interfaces between Java and native code in more detail.

J/Direct

Microsoft® J/Direct™ is a powerful mechanism that enables Java code to call application programming interfaces (APIs) in DLLs in the most straightforward manner possible. The code in DLLs called through J/Direct has no additional interfacing responsibility imposed on it, which makes J/Direct an excellent vehicle for calling previously developed native code. (The RNI or JNI programmer typically must write wrapper DLLs around existing native code to interface between the Java environment and the native code.)

The most obvious use of J/Direct is to call Win32 APIs or APIs in third-party Dynamic-link libraries. The Microsoft VM automatically translates common Java data types to those expected by C functions. Compared to RNI, J/Direct dramatically reduces the amount of extra code and the number of wrapper Dynamic-link libraries that would need to be written.

J/Direct is best illustrated with an example, as follows:

class ShowMsgBox
{
  public static void main(String args[])
  {
     MessageBox(0, "Hello World!", "Message box using Win32 API from Java", 0);
  }

  /** @dll.import("USER32") */
  private static native int MessageBox(int hwnd, String text, String title, int fuStyle);
}

If you know both Java and Microsoft® Windows® programming, the only line that might be new is:

/** @dll.import("USER32") */

In the example, this line is a directive to the compiler to link MessageBox to the Win32 API in USER32.DLL using the J/Direct protocol. The Microsoft VM provides the necessary support to make this happen. For example, the String Java class is marshaled into a null-terminated string, expected by the C language calling convention for a string. The support provided by the Microsoft VM makes it possible to call more than 95 percent of the Win32 API functions in a simple manner, similar to the previous example. Helper classes, source code, and samples provided as part of the Microsoft SDK for Java will help Java programmers who want to exploit the richness of the Win32 platform from their Java applications.

For a detailed description of how to use J/Direct, see About J/Direct. Also, see the J/Direct samples that are available in the SDK for Java.

ActiveX/Beans Integration

JavaBeans provides the component model for Java. JavaBeans, while still in its infancy, is gaining popularity with Java developers. It is likely there will be a variety of JavaBeans components in the marketplace in the near future. ActiveX is a language-neutral component model that uses COM as its base. In terms of the marketplace, ActiveX is a much more mature component model, supported by a whole set of power tools, such as Microsoft® Visual Basic®, Microsoft® Visual C++®, Borland Delphi, and Powersoft PowerBuilder, as well as thousands of commercially available ActiveX components. The integration of ActiveX and Beans provided by the Microsoft VM enables a Java programmer to take advantage of the vast array of rich ActiveX controls available. Similarly, ActiveX control programmers can make use of compelling JavaBeans components as they begin to appear in the marketplace.

The integration provided by the Microsoft VM is such that an ActiveX control appears as just another Bean to the Java programmer. Likewise, the JavaBeans component appears as just another ActiveX control to the ActiveX control programmer or control container. This enables programmers to work in the environment they are most familiar with, while exploiting the richness of the available components and controls on the platform, no matter what language was used to develop the control or component.

Thus, the two main features of the integration provided by the Microsoft VM enable a programmer to:

  • Host a Bean in an ActiveX container.
  • Host an ActiveX control in Java.

The following sections describe how a developer can utilize the Microsoft VM and SDK tools to accomplish these objectives.

Hosting a Bean in an ActiveX Container

In JavaBeans architecture, a Bean is a reusable Java component, which is usually meant to be used in the context of other Beans or components in some container. The Microsoft VM provides the bridge necessary to host a Bean in an ActiveX container. The ActiveX container cannot differentiate the Bean from an ActiveX control; it treats it like any other ActiveX control. So, for example, Microsoft® Visual Basic® 5.0 can use the Bean exactly as it would use a control.

Hosting a Bean in an ActiveX container is essentially a two-step process: write the Bean and run a tool called javareg. The following example shows a typical javareg command line registering a Bean called JChart:

javareg /register /control /class:JChart /codebase:.
/clsid:{177cf4a0-e7e0-11d0-b8e7-0000f81ecce7} /typelib:JChart.tlb

The javareg tool introspects the JavaBeans component to gather information about its properties, events, and methods, and then outputs this information in the form of a type library. A type library is the file that an ActiveX container uses to find information about an ActiveX control. The tool also registers the Bean, which allows an ActiveX container to find the Bean, like it would any other ActiveX control.

For more information about the javareg tool, see Using Javareg. The Microsoft SDK for Java also provides samples of this technique that a developer will find useful.

After running javareg, the Bean can be hosted in any ActiveX container, appearing there as an ActiveX control. When the JavaBeans component is invoked as an ActiveX control, the Microsoft VM is loaded and makes the appropriate mapping between the methods, properties, and events of the JavaBeans and the interfaces, methods, properties, and events of the ActiveX control. Examples of some popular ActiveX containers include Visual Basic, Microsoft® Office, Borland Delphi, and Corel WordPerfect, among others.

It should be noted at this point that Microsoft® Internet Explorer is itself an ActiveX container, and when a JavaBeans component is wrapped as an ActiveX control by the VM in Internet Explorer, the component exposes the same COM interfaces as any ActiveX control in the browser. To enable this mode of use, however, you must use the OBJECT tag to load your Java applet. When you use the OBJECT tag, you do not need to run javareg. See Using the HTML 4.0 OBJECT Tag below for more information on using this tag.

Java Monikers

ActiveX containers, such as Visual Basic 5.0, are able to find a Bean through a "Java Moniker," which uses a URL syntax similar to the one used in the HTML OBJECT tag. So for example, in Visual Basic 5.0, you can use the command GetObject("java:java.util.Date") to create an instance of the Date object, and then invoke methods on it.

This is possible because DCOM introduced an extensible moniker namespace, so if you pass a string like "java:some.class" to MkParseDisplayName, OLE32 will load the Microsoft VM and let it provide the class moniker to bind to the object (it looks up "java" as a progid in the registry and gets the CLSID of a handler implemented by the VM).

Furthermore, ActiveX containers that host a Bean can find information about the Bean through a COM interface called ITypeInfo. This allows access to interfaces such as IDispatch and permits all the usual operations represented through ActiveX interfaces, such as calling QueryInterface, and so on.

To help illustrate how moniker binding works, here is an example C++ program that uses monikers to bind to a simple Java object called TestObject, whose source code follows this example:

TEST.CPP

#include <windows.h>
#include <olectl.h>
#include <stdio.h>

HRESULT BindToObject(LPOLESTR pwszDisplayName, REFIID riid, LPVOID *ppunk)
{
    HRESULT hr;
    IBindCtx *pbc;
    ULONG chEaten;
    IMoniker *pmk;

    *ppunk = NULL;

    hr = CreateBindCtx(0, &pbc);

    if (hr == S_OK) {

        hr = MkParseDisplayName(pbc, pwszDisplayName, &chEaten, &pmk);

        if (hr == S_OK) {
            hr = pmk->BindToObject(pbc, NULL, riid, ppunk);
            pmk->Release();
        }

        pbc->Release();
    }

    return hr;
}

void main(int argc, char *argv[])
{
    HRESULT hr;
    IUnknown *punk;

    hr = CoInitialize(NULL);

    if (hr == S_OK) {

        hr = BindToObject(L"java:TestObject", IID_IUnknown, (LPVOID *) &punk);

        if (hr == S_OK) {

            punk->Release();

        } else {
            printf("failed to bind to java object (hr=%08x)\n", hr);
        }

        CoUninitialize();
    }
}

TestObject.java

import java.io.*;
import java.net.*;
import com.ms.com.*;

public class TestObject
{
    public TestObject() {
        System.out.println("created java object!");
    }
}
Using the HTML 4.0 OBJECT Tag

If you want to treat the Bean as an ActiveX control in Internet Explorer 4.0, to gain access to COM interfaces on that object for example, you can skip the javareg process and just use the HTML 4.0 OBJECT tag (Internet Explorer 4.0 queries the object directly for its Typeinfo data rather than having to rely on the Typelib information generated by javareg).

The HTML 4.0 OBJECT tag specification is supported by the Microsoft VM in Internet Explorer 4.0 so that you can use the OBJECT tag instead of the APPLET tag to run Java applets from a local or remote codebase. For example, the following code fragment could be used to load the Java class myprogram.one from http://www.one.come/two/three/.

<OBJECT classid="java:myprogram.one">
        codebase="http://www.one.come/two/three/">
</OBJECT>

Note that the Microsoft VM only provides access to COM interfaces for Java classes loaded using the OBJECT tag. The APPLET tag is handled in a different manner internally. For more information on HTML 4.0 and the OBJECT tag, see http://www.w3.org/TR/WD-object.

Exposing JavaBeans Methods through IDispatch

By default, the Microsoft VM for Java uses JavaBeans introspection to enumerate the methods and properties that are exposed through IDispatch. Unless a Bean provides its own BeanInfo, all public methods are exposed, as well as properties discovered using standard design patterns (such as setText and getText).

Mapping JavaBeans Events to ActiveX

In addition to exposing event interfaces, ActiveX controls have the concept of a default, outgoing set of events. A control developer defines this default event set, which is often the only event source connected to by ActiveX containers. To provide the greatest flexibility to Java developers, the ActiveX control framework allows use of design patterns to define this default event interface.

Since the JavaBeans eventing model is sufficient for many eventing needs and maps well to the ActiveX IConnectionPointContainer model, Microsoft recommends that events be exposed using the JavaBeans eventing specification.

When an ActiveX component attempts to connect to the default event interface of an ActiveX control for Java, the Microsoft VM introspects that control and looks for event listener interfaces. Unless a Bean provides its own BeanInfo, all outgoing events are in the default event set. For example, a developer could define the following interfaces in Java to define its outgoing default event set.

interface mouseListener
{
    public void mouseEvent( int ButtonState, int x, int y );
}

interface buttonListener
{
    public void clickEvent( Object ButtonSource );
}

interface keyListener
{
    public void keyEvent( int shiftState, int key );
}

These interfaces define events that could be sourced from three different JavaBeans event connections in a Java control. The Microsoft VM will combine them into one interface that is exposed through ActiveX. Be aware that the methods in the interface freely define parameters that are not event objects. The JavaBeans specification states that this free-form method specification is fully supported, but not necessary. Microsoft encourages its use because it can improve performance in passing events in and out of Java.

To attach an event sink to the Java control, the Microsoft VM calls the addListener methods of the outgoing event sources and passes the instance of an object, which implements the appropriate interface.

Mapping JavaBeans Properties to ActiveX

Properties allow control developers to expose state variables that can be queried, set, and monitored by other controls or control containers. Again, the JavaBeans model provides a one-for-one mapping with ActiveX property concepts and change notifications. The Microsoft VM exposes ActiveX properties based on design patterns and BeanInfo information as detailed in the JavaBeans specification.

To source property change events (equivalent to ActiveX OnChanged events) a developer can simply support the JavaBeans addPropertyChangeListener and removePropertyChangeListener methods, which accept the propertyChangeListener interface as a parameter. Likewise, to source vetoable property change events (equivalent to OnRequestEdit events), a developer just supports addVetoableChangeListener and removeVetoableChangeListener methods, which accept the vetoableChangeListener interface as parameters. The Microsoft VM will automatically connect to these property change event sources and handle them appropriately. To ActiveX clients of the object, these events will map to IPropertySinkNotify and IPropertySinkNotify::OnRequestEdit.

Hosting an ActiveX Control in Java

ActiveX controls are Automation-enabled controls that support the IDispatch COM interface, which enables the control to be scripted. These controls can also be dropped into containers, such as Visual Basic.

Hosting an ActiveX control in Java is a four-step process:

  1. Develop or obtain an ActiveX control and its associated type library.
  2. Run a tool called jactivex on the ActiveX control or its type library.

    This tool will emit Java source code wrappers for the IDispatch interface implemented by the ActiveX control. The emitted Java code will include Bean-like code for adding and removing listeners for the events originating from the ActiveX control. Also, the tool produces code to appropriately manage the lifetime of the ActiveX control.

    The source code will contain compiler directive code, similar to that used by J/Direct, of the form:

/** @com */
  3. Compile this Java source code using a compiler, such as jvc, that can interpret the @com syntax. The compiler will add some attributes to the class file.
  4. Import these classes and use the ActiveX control like any other Bean in Java code. The Microsoft VM will use these attributes in the class file to expose the ActiveX control as a Bean to any Java code. The Microsoft VM provides the necessary bridge between the invoking Java code and the corresponding IDispatch interface in the ActiveX control. Note that this only works with virtual machines that understand these attributes.

    This is best illustrated with an example. The following sample uses the Microsoft Calendar ActiveX control that ships with Microsoft Office. Running the tool jactivex on the Calendar control produces Java source classes, which are then compiled into the calendar classes imported below. A Java programmer would use the control with code similar to the following:

import java.awt.*;
import com.ms.activex.*;
import calendar.*;  // Classes from JActiveX when run on Calendar control or typelib

public class UseCalendar extends Frame implements ActiveXControlListener
{
    Calendar c;
    public UseCalendar()
    {
        c = new Calendar();

        c.addActiveXControlListener(this);
        add(c);
    }

    // Implementation of ActiveXControlListener interface method(s)
    public void controlCreated(Object o);
    {
        if (o instanceof Calendar)
        {
            c.today();
        }
    }
}

Notice that the control is manipulated like any other Bean. The constructor code creates the Bean, registers a listener (in this case, one defined by the ActiveXControlListener interface), and then adds itself to the layout. The single method of the ActiveXControlListener interface is controlCreated. When the control is created, the Microsoft VM fires an event defined by the ActiveXControlListener interface and, if the ActiveX control supports events as this example does, the corresponding listener method on the Bean is called. The code necessary to sink the event to the corresponding listener is provided automatically by the Microsoft VM.

The result is that when the Calendar control is created, and the controlCreated method is called, which displays the month corresponding to the current date.

Raw Native Interface

The Raw Native Interface (RNI) is a high-performance interface supported by the Microsoft VM for Java. This interface is meant for "pedal-to-the-metal" kind of performance programming. It provides an efficient way of both traversing between Java and native code, and manipulating objects while in native code. The native code must be an active participant when running in or interfacing with a Java environment; it has certain responsibilities, which include following naming conventions, adapting to Java data representations, and dealing with the garbage collection process of the Java environment.

For example, if the native code is going to be in a long loop, the garbage collector should be called periodically. Similarly, if the code is going to block on user input or call a thread that will block, it should call the garbage collector around the code that can block. Furthermore, objects need to be protected by garbage collection frames when calling back into Java.

The required knowledge of garbage collection and other issues increases the complexity of programming using RNI for the benefit of increasing performance. For this reason, this interface should be used only in cases where high performance is needed and therefore justifies the extra effort.

For more information about using the raw native interface, see Introduction to Using the Raw Native Interface and see the samples in the Microsoft SDK for Java.

Low-Level Java/COM Integration

ActiveX objects can be implemented as dual-interface objects, meaning that they support both the IDispatch interface for automation and also vtable access to COM interface methods. Like C and C++, Java can access the vtable methods directly. When accessed this way, these objects do not have many of the restrictions as to the type of data they can pass and the type of interfaces they must support as do ActiveX controls that use automation. Also, some COM objects do not support IDispatch and can only be accessed through vtable methods.

The tool that enables this access is jactivex, the same tool used for hosting ActiveX controls as JavaBeans components, but using the -javatlb switch. Because this is a much lower-level approach than the ActiveX/Beans integration, and data types are less restricted, there may be additional steps involved. This is especially true if there are complex data types passed through the interfaces exposed by the COM object. In particular, custom marshaling techniques might have to be used to manipulate these data types. It should also be noted that this approach does not create a JavaBeans object from the COM object. Instead, it creates a class that exposes the methods in the COM interfaces as its own class methods and calls the COM object for implementation.

See the Using Jactivex to Create a User-Defined Type for Java/COM Marshaling article for more information on Custom Marshaling, the Low-Level Java/COM Integration article for an overview of Java/COM integration, and the Jactivex Reference for detailed information about the JactiveX tool. Also, see the samples in the SDK for Java. Samples pertaining to low-level COM integration can be found in subdirectories under the /MsVmJava/Samples/ directory in the SDK.

Summary

The Microsoft VM provides various ways to call non-Java code from Java. The programmer can choose the best way depending on the issue at hand. The approach taken can be one of the following:
J/Direct | Functionality that enables a Java programmer to call APIs in other DLLs (such as Win32 API). This exposes the full richness of the Win32 platform to the Java programmer. Details of interfacing the DLL with the Java environment are handled automatically.
ActiveX/JavaBeans integration | Automatic bidirectional support for ActiveX control and JavaBeans integration. An ActiveX control will appear as a Bean to a Java programmer. A Bean will appear as an ActiveX control to an ActiveX control programmer.
RNI | Powerful performance-driven interface where the programmer is aware of the Java environment. However, the programmer must be aware of garbage collection issues.
Low-level Java/COM integration | More sophisticated COM object manipulation, which might require techniques such as custom marshaling.

Most programmers will use the first two approaches listed above: J/Direct and ActiveX/JavaBeans integration. The support provided by the Microsoft VM is both broad and complete: broad, in that it covers most scenarios for accessing native code, and complete in that it provides full access to the immense feature set of native code on the Win32 platform.


Introduction

The Microsoft Virtual Machine for Java (Microsoft VM) supports integration between Java and the Component Object Model (COM), which is the protocol underlying the Microsoft® ActiveX® platform, Automation, and Object Linking and Embedding (OLE). With Java/COM integration, you can give your Java program access to any software component that supports COM, including thousands of ActiveX controls and Automation objects.

Java/COM integration is available at two levels, corresponding to the dual-interface nature of the ActiveX Automation model. At the highest level, ActiveX controls are converted directly to JavaBeans components (Beans) by the Microsoft VM, and Beans are converted to ActiveX controls. The type mapping for parameters is done automatically in this case, based on the standard IDispatch types used by all ActiveX controls to communicate with their containers.

On the other hand, since ActiveX controls are dual-interface objects, they can also be accessed by their vtable methods. This is how C programs typically access these controls and what is referred to as low-level Java/COM integration in this article. This mode of access is particularly useful when you need to marshal data types that are not handled by IDispatch between Java and COM objects.

New Features

If you have used earlier versions of the SDK for Java and Visual J++, you might be interested to learn about several new features that can make it easier (or more efficient) to accomplish certain tasks that involve COM objects. These tasks previously required the use of javatlb, which has been replaced by the jactivex tool (called jcom in previous releases):

  • Hosting an ActiveX control within a Java component.

    You can use the jactivex tool to expose an ActiveX control as a JavaBeans component (a Bean). This tool also generates listener interfaces for catching events.

  • Exposing a JavaBeans component as an ActiveX control.

    The Microsoft VM now does this for you automatically. Every Java object is, by default, exposed as an ActiveX control whose IDispatch interface is generated using JavaBeans introspection on the Java class. For more information, see the article on ActiveX/Beans Integration.

  • Calling a DLL from Java

    Previously this required wrapping the DLL inside a COM interface for the purpose of calling the DLL from Java. You can now make direct calls to a DLL function using Microsoft® J/Direct™. To learn how to use J/Direct, see the About J/Direct article.

The following topics are available in this article:
Using a COM Object From Java
Implementing COM Objects
Type Mappings Between Java and COM
Handling COM Errors in Java
COM Programming in Java and C++ Compared
Apartment Model and Threading Issues

You can find more information about COM in the Component Object Model Specification that is included in the Win32 Software Development Kit.


Using a COM Object From Java

The jactivex tool allows you to load and invoke OLE Automation objects directly from your Java source. There is also some limited support for types not supported by Automation using the Custom Marshaling feature. This section includes the following topics:

New Features
Importing a COM Class Using the Jactivex Tool
Using a COM Object in Your Java Code

Importing a COM Class Using the Jactivex Tool

To use a COM class from Java, you must first import it into Java using the jactivex command-line tool. The jactivex tool, when used with the /javatlb switch, generates .java files for the classes and interfaces described by a type library. These .java files, once compiled into .class files, allow Java programs to use COM services.

The typical way to use the jactivex tool to import a COM class is as follows:

        jactivex /javatlb filename

where filename is the name of the type library that defines the class that you want to import. The filename should have one of the following extensions: .tlb, .olb, .ocx, .dll, or .exe.

Suppose you ran jactivex using the following command:

        jactivex /javatlb  widgets.tlb

This command first creates a \Widgets subdirectory underneath the trusted library directory specified by the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\TrustedLibsDirectory. If the trusted library directory is \Windows\Java\Trustlib, the preceding command creates the directory \Windows\Java\Trustlib\Widgets, and fills it with .java files—one for each class, structure, enumeration, and interface described by the widgets.tlb type library. If the type library contains an importlib statement, jactivex creates a separate Java package in a separate directory for the imported type library.

For more information about installing and using the jactivex tool, see the description of jactivex in the Introduction to Jactivex section of the Tools article.

Using a COM Object in Your Java Code

The following example is presented to help you understand how to use COM objects in your code. Suppose comserver.dll, which defines a CComBeeper class and an IComBeeper interface, is registered as having type library information. Running the jactivex tool (with the /javatlb switch) on comserver.DLL would create a package named comserver, containing the Java class CComBeeper and the Java interface IComBeeper.

Once you've run jactivex on comserver.dll, you can use the import statement in your Java source code to easily refer to classes in the comserver package. For example:

import comserver.*;   // import comserver package

This statement is identical to Java's syntax for importing an entire package. It is not strictly necessary, however. In Java, any class can be referenced using its fully qualified name (for example, java.awt.Canvas), as long as a class fitting that name can be found when searching the class path. The import statement allows you to refer to the class using its short name (for example,Canvas).

The same rule applies to importing COM classes. The import statement is not required to use the COM class. It simply allows the class to be referenced using its short name. Any COM class can always be referenced using its fully qualified name.

Instead of importing the entire package, you could explicitly import individual classes within a type library. To import individual classes, use the following syntax, which is identical to Java's syntax for importing a single class:

import comserver.IComBeeper;
import comserver.CComBeeper;

The Java classes that wrap COM classes can be used the same way you use other Java classes. For example, the following code declares a reference of type IComBeeper, initializes it by creating an instance of the COM class CComBeeper, gets and sets the value of a property of the object, and then calls two methods on the object:

IComBeeper testBeep = (IComBeeper)new CComBeeper();
int myTone = testBeep.getSound();
testBeep.putSound(64);
testBeep.Beep();

Because CComBeeper is a COM class, you must use one of its interfaces to manipulate an instance of the class. COM does not support accessing properties or methods on a class independently from its interfaces. For example, the following statements would be legal Java code, but will cause errors when used with a COM class:

CComBeeper testBeep = new CComBeeper(); // Don't do with COM class.
int myTone = testBeep.getSound();       // Causes runtime error with COM class.

Note An important restriction on using Java classes that wrap COM classes is that you cannot use an instance of the class directly; you must use the instance through an interface. However, if you generate the .java files by using the jactivex tool with its /javatlb /xi option, you can call methods on the object directly without first casting to an interface pointer. For more information on using the jactivex tool, see the Introduction to Jactivex.


Implementing COM Objects

Low-Level Java/COM Integration
In this topic

* Reference Counting

* Supporting Multiple Interfaces

* How IDispatch Is Implemented

* Implementing COM Interfaces

* Parameters Passed by Reference

Java & Native Code | Previous | Java/Com | Next
Low-Level Java/COM Integration | Previous | Java/Com | Next

Implementing COM Objects

Suppose you want to implement a COM object in Java. You need to understand how the VM for Java takes care of reference counting, how you can implement multiple interfaces on a Java object, and how QueryInterface and IDispatch are implemented. These topics are discussed in the sections that follow.

Reference Counting

Reference counting is handled automatically in Java. There is no need to call IUnknown::AddRef when creating a new reference to an object, nor do you need to call IUnknown::Release when you're finished using a reference to an object. The Java garbage collector automatically keeps track of how many references there are to an object. In practice, however, you may need to explicitly release some COM objects to ensure a timely release of shared resources. You can use the com.ms.com.ComLib.release method to force Java to release all its reference counts on a COM object.

Supporting Multiple Interfaces

COM objects can support multiple interfaces and Java supports multiple interfaces on objects. This is probably the most important reason that Java/COM integration works so well. Consider the previous robot example, but the COM Robot class (CLSID_Robot) implements an interface called IRobotDiagnostics in addition to IRobot. The IRobot interface is used to control what the robot does and IRobotDiagnostics determines the status of the robot.

The following C++ code makes use of both interfaces. First, the robot is instructed to move forward 10 units, and then turn left 90 degrees, using the IRobot interface. The following example then uses QueryInterface for IRobotDiagnostics, and uses that interface to tell the robot to display a status message:

//  Error handling has been omitted for brevity.
IRobot* probbie = NULL;
IRobotDiagnostics* probbieDiag = NULL;
CoCreateInstance(CLSID_Robot, NULL, CLSCTX_SERVER, IID_IRobot, (void**)&probbie);
probbie->GoForward(10);
probbie->Turn(-90);
probbie->QueryInterface(IID_IRobotDiagnostics, (void**)&probbieDiag);
probbie->OutputStatusMessage();
probbieDiag->Release();
probbie->Release();

The same code, written in Java, would look like this:

import robocorp.bots.*;
Robot robbie = new Robot();
IRobotDiagnostics robbieDiag = null;
robbie.GoForward(10);
robbie.Turn(-90);
robbieDiag = (IRobotDiagnostics)robbie;
robbieDiag.OutputStatusMessage();

Because the Microsoft VM provides the implementation of IUnknown, there is no need to implement QueryInterface. The assignment statement does the implicit QueryInterface for IRobotDiagnostics (this is very similar to how QueryInterface is supported in Visual Basic version 4.0).

An explicit cast to the interface is necessary just as it is necessary in normal Java interfaces. An exception is thrown if the object does not support the interface you want. The standard Java instanceof operator can be used to determine whether a given interface is supported.

How IDispatch Is Implemented

When implementing automation objects in Java, you can use automatic IDispatch. The VM implements IDispatch automatically for almost all Java objects. This means that a tool, such as jactivex, is no longer necessary simply to script a Java object from an automation controller such as Visual Basic or Microsoft® Visual Basic® Scripting Edition (VBScript). To implement a simple automation object in Java, you need to do the following things:

  1. Implement the Java object and compile it.
  2. Register it using javareg.
  3. Ensure that the Java class is visible in the CLASSPATH environment variable.

Implementing COM Interfaces

Normally (in the absence of COM), when implementing an interface on a Java class, the interface being implemented is either declared within the code module (file) where the implementation occurs or in an external .class file, which is imported through the import statement. You cannot define an interface using the interface declaration and import the same interface's declaration from a .class file. This rule also holds true for COM interfaces. Therefore, you will never see a COM interface defined by Java. Instead, a COM interface is defined in IDL, compiled into a type library, and imported into Java as though it were a standard Java .class file.

To implement COM interfaces on a Java class, use the implements modifier on the class declaration with a list of interface names and provide method bodies for each method in the interfaces (excluding QueryInterface, AddRef, and Release).

The following example shows the IRobot interface described in IDL:

[ object, uuid(6C6971D5-8E69-11cf-A54F-080036F12502)]
interface IRobot : IUnknown
{
    ...
    HRESULT OutputStatusMessage([out, retval]BOOL* pRetVal);
    ...
};

If the IDL file was compiled into the robocorp/bots.tlb type library, the following Java code could be written to implement a robot object:

import robocorp.bots.*;
class RogerRobot implements IRobot
{
    ...
    boolean OutputStatusMessage(void)
    {
        return VoiceBox.Speak(CurrentStatus());
    }
    ...
}

Every Java class automatically implements IUnknown and IDispatch. The dispinterface implemented by the IDispatch interface, which Java provides, contains the public methods that are on the default interface for the class. For example, the following Java class implements an IDispatch interface, which supports MethodA and MethodB:

class Example
{
    public void MethodA(void)
        { ... }

    public void MethodB(int x)
    { ... }
}

At run time, the Microsoft VM automatically provides type information for this IDispatch implementation (using IDispatch::GetTypeInfo), so clients can avoid the overhead of using IDispatch::GetIDsOfNames to do late binding. Since all Java objects are COM objects, nothing else is required.

Parameters Passed by Reference

COM interface methods can have parameters that pass simple types such as integers, floating point values, and characters by reference. In most cases these parameters are "out" parameters. For example, the COM method MySample has the following signature:

HRESULT MySample([in] long l, [out] long* Out1, [out, retval] long* retval);

However, Java does not support parameters that are references to the intrinsic data types, and it does not support pointers. But you can still call MySample from Java. Reference types are mapped to one-element arrays by the Microsoft VM. Therefore, you can retrieve a reference in the following way:

int A;
int B[] = new int[1];
A = MySample(42, B);
System.out.println("A = " + A + " and B = " + B[0]);


Type Mappings Between Java and COM

Low-Level Java/COM Integration
In this topic

* Element Types Defined in Type Libraries

* Interface Methods

* Types Supported as Parameters

* Sample Declarations

Java & Native Code | Previous | Java/Com | Next
Low-Level Java/COM Integration | Previous | Java/Com | Next

Type Mappings Between Java and COM

The Microsoft VM for Java allows most constructs that can be specified in a type library to be accessed from Java. However, only OLE Automation-compatible types are supported fully. Most other types will require Custom Marshaling. COM constructs that cannot be described in a type library are inaccessible from Java. This limitation is in place mainly because the current type library model is not rich enough to describe all interfaces. To learn more about type libraries, see the OLE SDK.

Element Types Defined in Type Libraries

There are five basic types of elements that can be defined in Object Description Language (ODL), and thus in a type library. These elements are mapped to Java as follows:
ODL element | Java element
coclass | public class
interface | public interface
dispinterface | public interface
typedef (struct, enum or union) | public final class
module | public final interface with public static final members

The interface keyword in ODL is used to define custom (that is, vtable based) interfaces.

The dispinterface keyword in ODL is used to define dispatch interfaces. Properties in the dispatch interface are accessible in Java through two methods named get<property> and put<property> in the Java interface.

Interface Methods

The methods generated for an interface do not include those it inherits from IUnknown or IDispatch. Methods declared with the propget or propput attributes are exposed with get or put prepended to their names.

Types Supported as Parameters

The following table lists the ODL types that are supported and the Java type that each ODL type maps to:
ODL Type | Java Type
boolean | boolean
char | char
double | double
int | int
int64 | long
float | float
long | int
short | short
unsigned char | byte
BSTR | class java.lang.String
CURRENCY/CY | long (divide by 10,000 to get the original value as a fixed-point number)
DATE | double
SCODE/HRESULT | int (see also class ComException)
VARIANT | class com.ms.com.Variant
IUnknown * | interface com.ms.com.IUnknown
IDispatch * | class java.lang.Object
SAFEARRAY(typename) | class com.ms.com.SafeArray
typename * | single-element array of typename on [out], error on [in]
void | void

For information on accessing the contents of a VARIANT structure, see the class Variant.

IUnknown is the interface from which all COM interfaces are derived. The Java versions of COM interfaces are derived from com.ms.com.IUnknown. Because IUnknown is simply a placeholder for COM interfaces, you never have to call any methods on com.ms.com.IUnknown. If your Java program calls a COM method that takes a parameter of type com.ms.com.IUnknown, you can pass any COM interface. If your Java program calls a COM method that has com.ms.com.IUnknown as its return type, you can cast the return value to the COM interface you're expecting.

Certain ODL attributes cause parameters to be treated in a special manner:

  • VARIANT parameters marked with the optional attribute in ODL are exposed as ordinary parameters in Java. If you wish to omit a parameter when calling the method, call the noParam method on a Variant object and pass that as a placeholder.
  • A parameter marked with the retval attribute in ODL is treated as the return value in the corresponding Java method.

Sample Declarations

Following are some ODL declarations and their corresponding Java declarations:

Declarations with simple parameters:
HRESULT Func([in] int x); | void Func(int x);
HRESULT Func([in,out] int* x); | void Func(int[] x);
HRESULT Func([out,retval] int* x); | int Func();

Declarations with string parameters:
HRESULT Func([in] BSTR x); | void Func(java.lang.String x);
HRESULT Func([in,out] BSTR* x); | void Func(java.lang.String[] x);
HRESULT Func([out,retval] BSTR* x); | java.lang.String Func();

Declarations with VARIANT parameters:
HRESULT Func([in] VARIANT x); | void Func(com.ms.com.Variant x);
HRESULT Func([in] VARIANT* x); | void Func(com.ms.com.Variant x);
HRESULT Func([in,out] VARIANT* x); | void Func(com.ms.com.Variant x);
HRESULT Func([out,retval] VARIANT* x); | com.ms.com.Variant Func();
HRESULT Func([in,out] VARIANT** x); | void Func(com.ms.com.Variant[] x);

Declarations with interface pointer parameters:
HRESULT Func([in] IBar* x); | void Func(IBar x);
HRESULT Func([in,out] IBar** x); | void Func(IBar[] x);
HRESULT Func([out,retval] IBar** x); | IBar Func();

For more information on HRESULTs returned by COM functions, see Handling COM Errors in Java.


Handling COM Errors in Java

This section tells you what HRESULTs are and how they are wrapped in ComFailException objects. Then try-catch blocks are explained, and an example with error handling is presented.

HRESULTs

The primary way that COM methods communicate failure information back to their callers is through the HRESULT, which every COM interface method returns. COM methods return this value, which is a 32-bit error code, to indicate success or failure of a method call. In almost all cases, only one success code is defined (S_OK), but many failure codes are defined. For a list of the values of common system-defined HRESULTs, see the ComFailException class. For domain-specific errors, consult the documentation for the component you are using.

The documentation for many components describes errors in terms of Visual Basic Err.Number values rather than HRESULTs. However, some components use a convention where there is a correspondence between the HRESULT returned and the Err.Number value. For example, if you are using Data Access Objects (DAO) or Remote Data Objects (RDO), you can call the getHResult method on the ComFailException object, take the lower 16 bits of the returned HRESULT, convert that value to decimal, and check it against the errors described in the DAO or RDO documentation.

The Microsoft VM defines a class called com.ms.com.ComException. This class wraps the HRESULT error code, and is used to communicate error information from COM back to Java whenever a COM method fails. The ComException class defines a getHResult method that returns the error code, in the form of a Java int, describing the specific error. You can also use the getMessage method (defined by the Java class Throwable) to retrieve the detail message.

Try-Catch Blocks

The Microsoft VM throws an exception when a call to a COM interface method returns an HRESULT containing a failure code. To find out about errors that occur during method calls, Java programmers use try-catch blocks to catch exceptions thrown by the virtual machine. Because the ComException class is derived from the Java class RuntimeException, the compiler does not strictly require a throws clause in the method declaration. Nor does the compiler require try-catch blocks. Since runtime exceptions are unchecked by the compiler, you can use try-catch blocks when you decide they are needed.

Because ComException is an abstract class, a ComException object cannot be constructed directly. However, a ComFailException object or a ComSuccessException object can be constructed. Typically, you try to catch ComFailException objects so that you know when something has gone wrong during a call to a COM method. The following example demonstrates the use of a try-catch block:

try
{
    // Call COM method.
}
catch (com.ms.com.ComFailException e)
{
    System.out.println( "COM Exception:" );
    System.out.println( e.getHResult() );
    System.out.println( e.getMessage() );
}

An Error Handling Example

The following Java code is similar to the code we saw in the Implementing COM Objects section; however, error handling has been added.

import robocorp.bots.*;
...
try
{
    Robot robbie = new Robot();
    robbie.GoForward(10);
    robbie.Turn(-90);
}
catch(Throwable e)
{
    System.out.println("Something bad happened!");
}


COM Programming in Java and C++ Compared

Users who are familiar with COM programming in C++ might find it helpful to learn how C++ COM programming compares to Java COM programming. Since Java's notion of multiple interfaces on an object and its garbage collection facility map readily to COM's paradigm for managing objects, many aspects of COM programming are simpler in Java than in C++.

Object Allocation

In C++, you allocate a new COM object using the following syntax:

IDrawable pDrawable;
CoCreateInstance(CLSID_MyCircle, NULL, CLSCTX_SERVER,
                 IID_IDrawable, (void**)&pDrawable );

In Java, the equivalent code would look like this:

IDrawable drawable = (IDrawable)new MyCircle();

The preceding Java statement is identical to Java's syntax for allocating ordinary Java objects. Behind the scenes, the COM API function CoCreateInstance is called instead of allocating space in the runtime heap. However, this call is invisible to the Java programmer.

Object Release

In C++, you release a COM object using the following syntax.

pDrawable->Release();

In Java, the equivalent code would look like this.

import com.ms.com.*;
ComLib.release(drawable);

Calling the release method causes the drawable object to release all of its references to the COM object that it wraps. Because drawable may have cached one or more of the object's interfaces, this call may result in more than one release.

Note If you do not call ComLib.release, normal garbage-collection will attempt to perform the release for you. However, this mechanism is not guaranteed due to the threading limitations of many COM objects. That is, many COM objects can only be called on the thread on which they were created. Because garbage collection occurs at unpredictable times, the required thread may have expired or may be no longer responding to messages by the time garbage-collection reclaims the object. In addition, this unpredictability can obscure true memory leaks and/or tie up important system resources. For these reasons, it is recommended that you use explicit releases in order to free COM objects in a timely and predictable fashion.

Changing Interfaces

COM objects must implement the IUnknown::QueryInterface function to allow clients to access the object's supported interfaces. In Java, the details are handled by the VM, so that in your source code, you need only do a typecast.

For example, in C++ you might write code like this to access the IPrintable interface of the object that pDrawable points to:

// pDrawable points to an object that supports
// both IDrawable and IPrintable
IPrintable *pPrintable;
pDrawable->QueryInterface( IID_IPrintable,
                           (void **)&pPrintable );

In Java, the equivalent code would look like this:

// drawable refers to an object that supports
// both IDrawable and IPrintable
IPrintable printable;
printable = (IPrintable)drawable;

Notice that you use the same syntax that you would normally use to cast between Java object types. If the object does not implement the requested interface, a ClassCastException is thrown when you attempt the cast. If you want, you can use the instanceof operator to determine before the cast is attempted whether the object implements the requested interface.


Apartment Model and Threading Issues

Most existing COM objects are not thread-safe. That is, clients are required to make all calls to the COM object from a single thread. In addition, this thread is required to process Window messages on a regular basis so that other threads can marshal calls to objects on that thread and so that system message broadcasts do not get blocked. (A thread that processes Window messages regularly is said to have a message pump.)

Furthermore, some COM objects are not even apartment-aware. These objects are not only restricted to a single thread, but are restricted to a specific thread known as the main apartment thread. The first thread that calls CoInitialize becomes the main apartment thread for the process.

The following sections describe how the Microsoft VM instantiates COM objects and creates marshaling proxies while hiding the details from the Java programmer.

Instantiating New COM Objects

When a Java class representing a COM object is instantiated using new, the VM for Java obtains the COM object's threading model from the registry. What happens next depends on which threading model is in effect:

If the threading model is Both or Free, the object is assumed to be thread-safe and is instantiated on the calling thread. Any method call on this object will translate directly to a method call on the underlying COM object on the calling thread.

If the threading model is Single, the Microsoft VM automatically marshals to the process main apartment thread to create the object. Furthermore, it marshals all method calls on this object back to the main apartment thread. This represents additional overhead, but this is required for non–thread-safe objects.

If the threading model is Apartment, the Microsoft VM marshals the object creation and method calls in similar fashion. The choice of thread is determined as follows. If the creating thread is considered apartment-hostable, the object is created on that thread. Otherwise, the object is created on a special apartment thread created automatically by the Microsoft VM. All objects created in this fashion share one special apartment thread. The Microsoft VM does not create a new thread for every object.

How Marshaling Works

Java proxies are not only created when a COM object is instantiated using new. They are also created whenever a Java method is passed an object from COM and whenever Java receives an object from a COM method through a return value. In both cases (when a Java method is passed a COM object and when Java receives a COM object via a return value), there is no registry entry that provides the threading model of the object. The Microsoft VM for Java must be told explicitly whether the interface can be assumed to be thread-safe. If the interface is not thread-safe, the Microsoft VM must marshal all calls to the thread on which the interface was received. The jactivex tool adopts a conservative policy and marks all interface parameters as requiring marshaling.

Even when the interface parameter is marked as requiring marshaling, the Microsoft VM will produce a non-marshaling proxy if the COM object indicates that it is thread-safe by aggregating the free-threaded marshaler (using CoCreateFreeThreadedMarshaler).

The VM can only create a marshaling proxy on a thread that is apartment-hostable. If a call is made to a Java proxy, which is itself hosted on an apartment thread, proxies for the parameters to that call are made on that apartment thread. Hence, this requirement is automatically satisfied. If the thread is not apartment-hostable, the proxy creation will fail with a ClassCastException.


Introduction

This article outlines the Microsoft Raw Native Interface (RNI) for implementing native code with the Microsoft Win32 VM for Java (Microsoft VM). The goal of RNI was to allow as much code as possible to be re-used between the various available virtual machines (VMs) and hence it mirrors much of the features (both good and bad) of the original JDK. Typically, the only changes have been to better support the VM's internal object model (for speed) and to allow non-conservative garbage collection (to reduce the working set).
Raw Native Interface Enhancements for SDK 2.5
A Simple Example
Accessing Fields
Garbage Collection Issues
Calling Java Methods
Object Creation
Throwing Java Exceptions from Native Code
Synchronization
Miscellaneous


Raw Native Interface Enhancements

Introduction to Using the Raw Native Interface
In this topic

* Reflection APIs

* Future Garbage Collection Performance Enhancements

* RNIGetCompatibleVersion Requirement

* RNI Invocation APIs

* Details of the New GC Model

Java & Native Code | Previous | RNI | Next
Introduction to Using the Raw Native Interface | Previous | RNI | Next

Raw Native Interface Enhancements

The Raw Native Interface (RNI) has been extended as a result of feedback and performance enhancements. The enhancements made to RNI are in the following four primary areas:

  • Additional APIs to enable reflection from native code
  • Changes to support future garbage collection performance enhancements
  • RNIGetCompatibleVersion requirement for RNI DLLs
  • RNI invocation APIs

Reflection APIs

A number of native reflection APIs have been added to improve accessibility of an object's methods and fields. Using these APIs insulates DLLs from changes to the underlying object model or changes in the class hierarchy.

Users of RNI should use the new write barrier support functions to set an object field inside another object. These APIs are GCSetObjectReferenceForObject and GCSetObjectReferenceForHandle. Also, Field_SetValue, already in RevE (the VM version in SDK 1.5), will support the write barrier. RNI developers are encouraged to use the "Field_" reflection APIs added in RevE because these APIs abstract the object layout. Since these APIs are available on RevE, it should be possible to make a single DLL that will work on RevE and Internet Explorer 4.0.

Future Garbage Collection Performance Enhancements

To support future garbage collection enhancements, the internal object model was changed to enable more effective garbage collection, and enable future write-barrier support in the garbage collector (see Details of the New GC Model below for details). To insulate code from these or future changes to the object model, developers are encouraged to use the reflection APIs described previously. A Java object may still be accessed as a C structure, but code will need to be recompiled using the updated msjavah tool provided in this SDK.

RNIGetCompatibleVersion Requirement

Due to the object model changes described previously, many RNI DLLs designed for earlier versions of the Microsoft virtual machine need to be recompiled. To identify whether an RNI DLL is compatible with the current version of the VM, it will call the RNI DLL's RNIGetCompatibleVersion export. RNI DLLs that do not export this API will not be loaded by the current VM.

RNI Invocation APIs

The virtual machine supports two new invocation APIs, PrepareThreadForJava and UnprepareThreadForJava, which can be used to execute RNI APIs on any Win32 thread. An invocation sample is provided in this SDK.

Details of the New GC Model

The ordering of values laid out within objects has changed.

Previously, if you had a class A with a string, an int and a string, followed by class B with an int and a string, the object layout in memory is as follows:

From A string (can be garbage collected)
    int (atomic non-collectable)
    string
From B int
    string

The new Garbage Collection model reduces the number of GC roots (in this example there are three).

The new object layout coalesces collectable objects within a class, and alternates object location from beginning to end, to coalesce between classes. The object layout for this would be as follows:

From A  int (atomic non-collectable)
    string (can be garbage collected)
    string
From B  string
    int

This gives just one GC root rather than three.

Because of this model change, all code that uses RNI needs to be rebuilt and recompiled with the new msjavah tool. Existing code that hasn't been recompiled will not run on existing VMs. Also, existing code that relies on accessing strings directly, rather than using a provided API, will not function.


A Simple Example

Export the RNIGetCompatibleVersion method from your DLL. All RNI DLLs must export this method; otherwise, an UnsatisfiedLinkError exception is thrown when the method is called. This is a new requirement for the Microsoft VM for Java. Previous releases did not require this export. The following example shows how to export this method.

        #include "native.h";  // RNI declarations (part of Microsoft SDK for
                              // Java)

        __declspec(dllexport)
        DWORD __cdecl RNIGetCompatibleVersion()
        {
            return RNIVER;
        }

Another example is a simple Java class that performs a prime-number sieve. You perform the calculation in C implemented in a DLL called SieveDemo.dll. In Java, the class might look like the following:

    class Sieve
    {
        native static int CountPrimes(byte[] abFlags);

        static
        {
            System.loadLibrary("SieveDemo");
        }
    }

Here, CountPrimes is declared native and the loadLibrary call is added in a static block to make sure the DLL that implements the API will be loaded.

Use the Java Language Compiler from Microsoft (jvc) to compile this Java source into a class file with the following:

    jvc Sieve.java

    Microsoft (R) Visual J++ Compiler Version 1.00.XXXX
    Copyright (C) Microsoft Corp 1996. All rights reserved.

Next, use msjavah to produce a header file used by the native code:

    msjavah Sieve

Which will look like the following:

    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <native.h>
    /* Header for class Sieve */

    #ifndef _Included_Sieve
    #define _Included_Sieve

    typedef struct ClassSieve {
    #pragma pack(push,1)
        int32_t MSReserved;
        char PAD;	/* ANSI C requires structures to have a least one member */
    #pragma pack(pop)
    } ClassSieve;
    #define HSieve ClassSieve

    #ifdef __cplusplus
    extern "C" {
    #endif
    __declspec(dllexport) long __cdecl Sieve_CountPrimes(struct HSieve *,HArrayOfByte *);
    #ifdef __cplusplus
    }
    #endif
    #endif

This header file defines a structure ClassSieve that represents the data members of Sieve and a declaration for the native API that is implemented. Since Sieve doesn't have any data members, ClassSieve only contains some housekeeping fields. Native APIs are of the form Package_Class_Member(...) and, since Sieve is not in an explicitly named package, the API that is implemented is Sieve_CountPrimes(). The first parameter to the API is the this pointer, which, for static functions, will always be NULL. The second parameter is the byte array that is manipulated.

Note One useful feature of msjavah is that primitive types (int, boolean, long, and so on) marked static and final become #defines in the resulting header file, making it much easier to share constants.

Next, we implement the C we need:

    #include <varargs.h>
    #include <native.h>
    #include "Sieve.h"

    long cdecl Sieve_CountPrimes(struct HSieve *phThis, HArrayOfByte *phFlags)
    {
        unsigned long count = 0;
        unsigned long i;

        for (i = 0; i < obj_length(phFlags); i++)
            (phFlags->body)[i] = 1;

        for (i = 2; i < obj_length(phFlags); i++)
        {
            if ((phFlags->body)[i] != 0)
            {
                unsigned long k;
                for (k = i + i; k < obj_length(phFlags); k += i)
                    (phFlags->body)[k] = 0;

                count++;
            }
        }

        return count;
    }

This is a fairly standard implementation of a sieve with several helpers from native.h to access to the data of the array (phFlags->body) and to query its length (obj_length(phFlags)).

Next, a .def file to export this API is added:

    LIBRARY         SieveDemo
    DESCRIPTION     'Native DLL for SieveDemo'

    EXPORTS
        Sieve_CountPrimes
        RNIGetCompatibleVersion

Finally, build everything, and then copy the resulting DLL to the system directory and test it.


Accessing Fields

In many real-world examples, the Java class will have fields that you want to modify from native code; this is fairly straightforward. The following simple class demonstrates this.

    class FieldDemo
    {
        int x;
        int y;
        int z;

        public native void SetFields();
    }

Produces the following msjavah generated header file:

    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <native.h>
    /* Header for class FieldDemo */

    #ifndef _Included_FieldDemo
    #define _Included_FieldDemo

    typedef struct ClassFieldDemo {
    #pragma pack(push,1)
        int32_t MSReserved;
        long x;
        long y;
        long z;
    #pragma pack(pop)
    } ClassFieldDemo;
    #define HFieldDemo ClassFieldDemo

    #ifdef __cplusplus
    extern "C" {
    #endif
    __declspec(dllexport) void __cdecl FieldDemo_SetFields(struct HFieldDemo *);
    #ifdef __cplusplus
    }
    #endif
    #endif

The ClassFieldDemo structure defines fields for modifying x, y, and z. If you wanted to set x, y, z to 42, 43, and 44, you would call the following function.

    void cdecl FieldDemo_SetFields(struct HFieldDemo *phThis)
    {
        phThis->x = 42;
        phThis->y = 43;
        phThis->z = 44;
    }

Notice how the Java int type maps to a long type on the native side. The following table shows how all the types map from Java to C.
Java | C
boolean | long
byte | long
char | long
double | double
float | float
int | long
long | int64_t
short | long


Garbage Collection Issues

These sections describe the issues associated with garbage collection.

Protecting Objects on the Stack

By default, garbage collection cannot occur while native code is executing (other threads that try to do any garbage collection will block until the thread in native code returns to Java). This is probably the most important issue as far as native code and garbage collection are concerned. The reason for this is so the VM can avoid conservative scanning of native stacks, which is often unreliable and can be a "bottleneck" to performance.

A lot of native code does some quick calculation and returns, so this isn't a problem. However, if the native code is going to perform some operation that takes some time, explicitly enable and disable garbage collection around the slow code.

Of course, enabling garbage collection means that any objects could move at any time, invalidating any pointers to those objects in native code. The simplest way to handle this is to inform the garbage collector of objects you're interested in before enabling garbage collection using a GCFrame() with GCFramePush(). Object pointers kept in a GCFrame will be automatically updated if the object gets moved. When you're done, you can inform the garbage collector using GCFramePop(). The following is a typical example.

    void some_java_method(HObject *phobj1Unsafe, HObject *phobj2Unsafe)
    {
        // Keep a structure with all the objects we're interested in.
        struct
        {
            HObject *phobj1Safe;
            HObject *phobj2Safe;
        } gc;

        // Declare a GCFrame;
        GCFrame gcf;

        // Tell the garbage collector about our structure, it will initialize this
        // structure to null.
        GCFramePush(&gcf, &gc, sizeof(gc));

        // Set the object ptr.
        gc.phobj1Safe = phobj1Unsafe;
        gc.phobj2Safe = phobj2Unsafe;

        // It's now safe to enable garbage collection.
        GCEnable();

        // ...time passes...garbage collection occurs...objects move...

        // Disable gargbage collection so we can access objects safely.
        GCDisable();

        // If GC moved our object then gc.hobjSafe will have been automatically
        // updated.

        gc.phobj1Safe->x = 42;
        gc.phobj2Safe->y = 33;

        // We're done.
        GCFramePop(&gcf);
    }

Note

  • You must enable GC as many times as you disabled it.
  • Call GCFramePop() before returning from native code back in to Java.
  • GCFrames are "strong", in the sense that having an object in GCFrame is considered to be equivalent to having a reference to that object so it won't be released by the garbage collector.

Protecting Objects in Allocated Memory

GCFrames are ideal for protecting objects on the stack, but not in situations where you want to keep an object pointer longer than the lifetime of the function in global memory. For situations like this, use GCGetWeakPtr() and GCFreeWeakPtr() instead:

    HObject **pphobjSafe = NULL;

    void some_java_methodA(HObject *phobjUnsafe)
    {
        // Allocate a weak ptr that we want to use later.
        pphobjSafe = GCGetWeakPtr(phobjUnsafe);
    }

    void some_java_methodB()
    {
        // Use the weak ptr we saved previously.
        *pphobjSafe->x = 42;
        GCFreeWeakPtr(pphobjSafe);
    }

As their names imply, these APIs create "weak" pointers to objects so that they can be freed by the garbage collector if no more references exist. At this point, the weak pointer becomes automatically invalid: Do not call GCFreeWeakPtr() on it. If you know the object is not freed by the garbage collector, call GCFreeWeakPtr() when you no longer need to keep track of it.

Calling Back To Java

If you call back to Java from native code, garbage collection may automatically be enabled by the Virtual Machine if memory needs to be allocated. This means that any object pointers you want to use after the call must be protected, either in a GCFrame or tracked by a weak pointer.


Calling Java Methods

These sections show how to call Java methods.

Common

The most common method for calling a Java API from native code is execute_java_dynamic_method (see also execute_java_dynamic_method64 and execute_java_dynamic_methodV). The following example shows how to call move on a Rectangle object:

    execute_java_dynamic_method(NULL, phRectangle, "move", "(II)V", x, y);

The parameters should be as follows:

  • The first should always be NULL
  • The second is the object whose method you want to call
  • The third is the name of the method
  • The fourth is its signature
  • Finally, pass the parameters. The signature specifies the types of the parameters surrounded by parentheses followed by the return type. In this case, "(II)V" translates to "param 1 is an integer, param 2 is an integer, and the return type is void."

The following is a table of how each type maps to its signature character:
Parameter | | Signature Char
array | [
boolean | Z
byte | B
char | C
double | D
float | F
int | I
long | J
object | L
short | S
void | V

For arrays, the signature char is followed the signature char of the type of the array. For example, an array of bytes would be "[B".

For objects, the signature is followed by the object class name and ends with a semicolon(;). For example, the signature for a Rectangle is "Ljava/awt/Rectangle;".

To call a static method, you can use execute_java_static_method (execute_java_static_method64 or execute_java_static_methodV). For example, to call System.gc(), write the following:

    ClassClass *pcc = FindClass(NULL, "java/lang/System", FALSE);
    execute_java_static_method(NULL, pcc, "gc", "()V");

FindClass() is used to get a pointer to the class object. The first parameter should be NULL, the second is the class name, and the third should be FALSE. You can call execute_java_static_method with the returned class pointer. The first parameter should be NULL, the second is the class pointer, the third is the method name, the fourth is the method signature. Finally call any arguments (but in this case, there aren't any).

Repeated Calls

For performing repeated calls to the same method of a particular object, you can use the more low-level do_execute_java_method API to avoid repeated name-lookups. The following is an example of to move on a Rectangle 10 times:

    struct methodblock *pmb = get_methodblock(phRectangle, "move", "(II)V");

    for (i = 0; i < 10; i++)
    {
        do_execute_java_method(NULL, phRectangle, NULL, NULL, pmb, FALSE, x, y);
    }

get_methodblock is used to get a pointer to a cached data structure that represents the object and the method. The first parameter is the object pointer, the second is the method name, and the third is the method signature. You can call execute_java_static_method with the returned methodblock pointer. The first parameter should be NULL, the second is the object pointer, the third and fourth parameters should also be NULL, the fifth should be TRUE for a static call and FALSE for a non-static call. Finally, pass any arguments.


Object Creation

These sections describe the creation of objects, arrays, and strings.

Basic Objects

Creating Java objects from native code is simple using the execute_java_constructor API. For example, to effectively create a "new Rectangle(0, 0, 10, 10)", you write the following:

    HObject *phobj = execute_java_constructor(NULL, "java/awt/Rectangle", NULL,
                                   "(IIII)", 0, 0, 10, 10);

The first parameter should always be NULL, the second parameter is the full class name, but uses "/" instead of "." as the package delimiter. The third parameter should NULL. The fourth parameter is the signature of the particular constructor to call (since there may be many), but without the return type (since constructors can't return values). Finally, pass any arguments. The return value will either be a pointer to the newly constructed Java object, or NULL if an error has occurred.

Creating Arrays

To allocate an array, you can use ClassArrayAlloc. For example, to create an array of 200 bytes, you would use the following:

    HObject *phobj = ClassArrayAlloc(T_BYTE, 200, NULL);

The first parameter is the type of array to allocate, the second is the number of elements to allocate, and the third is only used when allocating arrays of non-primitive objects. For example, to allocate an array of 200 Rectangles, you would use the following:

    HObject *phobj = ClassArrayAlloc(T_CLASS, 200, "java/awt/Rectangle");

Note that this just allocates space for the array itself. Each object in the array needs to be individually allocated.

The following is a table that shows all the types supported by ClassArrayAlloc:
T_BOOLEAN
T_BYTE
T_CHAR
T_CLASS
T_DOUBLE
T_FLOAT
T_INT
T_LONG
T_SHORT

Creating Strings

Since Java string creation is such a common operation in native code, there are some string specific functions to make life a little easier. For example, use the following to create a Java string of "Hello":

    HJava_lang_String *phString = makeJavaString("Hello", 5);

The first parameter is the C character array to use and the second parameter is the number of characters in the string (not including the terminating NULL).

Be aware that the JDK makeCString function is not supported in the Microsoft Raw Native Interface API. It is recommended that you use the javaString2Cstring function in place of this.


Throwing Java Exceptions from Native Code

To throw Java exceptions from native code, you can use the SignalError API. This creates a Java exception object that will be thrown upon return from the native code (the normal execution of the native code is not interrupted). This is shown in the following example:

    if (makeJavaString("Hello", 5) == NULL)
    {
        SignalError(NULL, "java/lang/OutOfMemoryError", "Failed to create string.");
        return;
    }

The first parameter is the environment (which should always be NULL), the second is the class name of the Java exception you want to throw (this must be a Java Throwable or a subclass of Throwable), and the third is the "detail string" (which can be NULL).

If you call into Java using something like execute_java_dynamic_method, it's possible that an uncaught exception was thrown during its execution. To test for this case, you can use the exceptionOccured API. It takes NULL as its only parameter and returns TRUE if an exception was thrown and FALSE otherwise. You can produce a stack trace of the exception (to the System.err PrintStream) using exceptionDescribe. You can destroy the exception using exceptionClear.

For example:

    // Make sure there isn't already a pending exception.
    exceptionClear(NULL);

    // Call method.
    execute_java_dynamic_method(...);

    // Check if something bad happened.
    if (exceptionOccurred(NULL))
    {
        // Make sure people are aware of the problem.
        exceptionDescribe(NULL);

        // Stop the exception from being propergated.
        exceptionClear(NULL);
    }


Synchronization

Native methods that are synchronized don't automatically lock\unlock the object. As a result, you must do any necessary synchronization on the native side.

  • ObjectMonitorEnter takes an object monitor
  • ObjectMonitorExit leaves an object monitor
  • ObjectMonitorNotify is analogous to Object.notify()
  • ObjectMonitorNotifyAll is analogous to Object.notifyAll()

For example, a typical synchronized method will look like the following:

    long cdecl Some_Java_SynchronizedMethod(struct HSomeJava *phThisUnsafe)
    {
        // Normal GC protection stuff.
        HSomeJava *phThisSafe;
        GCFrame gcf;

        GCFramePush(&gcf, &phThisSafe, sizeof(phThisSafe));
        phThisSafe = phThisUnsafe;

        ObjectMonitorEnter(phThisSafe);

        // Code here executes synchronized on this object.

        ObjectMonitorExit(phThisSafe);

        GCFramePop(&gcf);
   }


Miscellaneous

To check if an object is of a particular type, you can use isInstanceOf, as shown in the following example.

    if (isInstanceOf(phSomeObject, "java/awt/Rectangle"))
    {
        // Object is a Rectangle...
    }

The first parameter is an object pointer and the second parameter is the full class name you want to test against.

Given a Java String type, you can query the number of Java characters it contains with javaStringLength(). For example:

    int cchString = javaStringLength(phString);

You can copy a Java String type to a C string buffer (converting from Unicode to multi-byte characters) using the javaString2CString function. This is shown in the following example.

    char szMBCS[256];

    javaString2CString(phString, szMBCS, sizeof(szMBCS);

The first parameter is the String object, the second is the destination buffer, and the third is the size of the buffer (in bytes), including the terminating NULL.

You can copy from one array to the other using the ArrayCopy function. The following is an example of copying 10 elements from one array (starting at position 3) to another (starting at position 5).

    ArrayCopy(phabSrc, 3, phabDst, 5, 10);

The first parameter is the source array, the second parameter is the source offset, the third is the destination array, the fourth is destination offset, and the fifth is the number of elements to copy.


Overview

These topics explain the raw native interface and show how to implement this interface in your Java programs:
Introduction to Using the Raw Native Interface
Raw Native Interface Functions
Raw Native Interface Structures


Raw Native Interface Functions

Java & Native Code | RNI
Raw Native Interface Functions | RNI

Raw Native Interface Functions

This reference describes the functions and structures defined in the native.h and nativcom.h header files (unless noted, prototype is found in native.h). These functions are used by the Raw Native Interface defined by the Microsoft® Virtual Machine for efficiently interfacing Java code with native code.

To learn how to use the API, see the overview information in Raw Native Interface.

The following functions are defined in native.h:
ArrayAlloc | Creates an array of primitive type objects.
ArrayCopy | Copies an array using the Java System.ArrayCopy method.
ClassArrayAlloc | Creates an array of objects.
Class_GetAttributes | Returns a combination of the ACC_XXX flags for a class as they appear in the Java class file.
Class_GetField | Returns a handle to a field explicitly specified by name.
Class_GetFieldByIndex | Returns a handle to a field specified by index.
Class_GetFieldCount | Retrieves the total number of fields in the class, including super and static fields.
Class_GetInterface | Retrieves an interface specified by index.
Class_GetInterfaceCount | Retrieves the total number of interfaces that are implemented by the class.
Class_GetMethod | Returns a handle to a method explicitly specified by name.
Class_GetMethodByIndex | Returns a handle to a method specified by index.
Class_GetMethodCount | Retrieves the total number of methods in the class, including super and static methods.
Class_GetName | Retrieves the class name.
Class_GetSuper | Retrieves the superclass name.
do_execute_java_method | Calls a Java method or constructor.
exceptionClear | Clears any pending exceptions.
exceptionDescribe | Invokes printStackTrace on the pending exception.
exceptionOccurred | Determines if an exception has occurred in the called Java method without exiting the native code.
exceptionSet | Sets a pending exception.
execute_java_constructor | Allocates a new Java object and invokes a constructor.
execute_java_constructorV | Allocates a new Java object and invokes a constructor.
execute_java_dynamic_method | Invokes a Java dynamic method.
execute_java_dynamic_method64 | Invokes a Java dynamic method and returns a 64 bit int.
execute_java_dynamic_methodV | Invokes a Java dynamic method using a va_list as a parameter instead of ellipses.
execute_java_interface_method | Invokes a Java interface method.
execute_java_interface_method64 | Invokes a Java interface method and returns a 64 bit int.
execute_java_interface_methodV | Invokes a Java interface method using a va_list as a parameter instead of ellipses.
execute_java_static_method | Invokes a Java static method.
execute_java_static_method64 | Invokes a Java static method and returns a 64 bit int.
execute_java_static_methodV | Invokes a Java static method using a va_list as a parameter instead of ellipses.
Field_GetXXX | Retrieves the value of the specified field.
Field_GetOffset | Returns the offset of dynamic fields in the class.
Field_GetStaticPtr | Returns a pointer to the static data.
Field_SetXXX | Sets the value of the specified field.
FindClass | Retrieves a class object pointer for a named class.
FindClassEx | Retrieves a class object pointer according to specified flags.
GCDisable | Increments the block count and disables garbage collection.
GCDisableCount | Disables the counting used by GCEnable and GCDisable.
GCDisableMultiple | Increments the block count a specified number of times.
GCEnable | Decrements the block count and enables garbage collection by the VM.
GCEnableCompletely | Decrements the block count to zero and enables garbage collection by the VM.
GCFramePop | Restores the GCFrame with current values for members of the structure.
GCFramePush | Informs the VM garbage collector of a GCFrame to track.
GCFreeHandle | Frees a "strong pointer" originally obtained using GCNewHandle.
GCFreePtr | Frees a pointer originally allocated using GCGetPtr.
GCGetPtr | Allocates a "weak" pointer for an object and updates it when GC occurs.
GCNewHandle | Creates a "strong pointer" to an object.
GCSetObjectReferenceForHandle | GC-safe method for updating contents of a handle.
GCSetObjectReferenceForObject | GC-safe method for updating the fields in an object.
get_methodblock | Retrieves a pointer to a method block structure containing the class name, method name, and parameter and return types of a method.
GetNativeMethodCallersClass | Determines the class type of the caller.
GetNativeMethodCallersMethodInfo | Gets information about the caller's method.
getPendingException | Retrieves a pending exception.
HResultFromException | Creates an HRESULT return type from a Java exception object.
is_instance_of | Determines if an object is an instance of a specified class type.
is_subclass_of | Determines if a class is a subclass of the second specified class type.
ImplementsInterface | Determines if a class type implements the interface represented by the second class type.
isInstanceOf | Determines if a specified Java object is an instance of a particular class.
javaString2CString | Copies the characters of the String object into a C string buffer.
javaStringLength | Retrieves the length of the Java String object.
javaStringStart | Returns a temporary pointer to the first character of the Java String object.
jio_snprintf | Prints to a string with a buffer limit.
jio_vsnprintf | Prints to a string with a buffer limit using a va_list macro for arguments.
makeJavaString | Returns a string formatted as a Java String object.
makeJavaStringW | Constructs a Java string from a Unicode C string.
makeJavaStringFromUtf8 | Creates a new Java String object, initialized from a null-terminated, UTF8-formatted, C string.
MakeByteString | Create and return a new array of bytes initialized from the C string.
Member_GetAttributes | Returns a combination of the ACC_XXX flags for a field or method, as they appear in the Java class file.
Member_GetClass | Retrieves the name of the class that the field or method is implemented in.
Member_GetName | Retrieves the member name.
Member_GetSignature | Retrieves the signature of the field or method.
monitorEnter | Enters a synchronization object.
monitorExit | Exits a synchronization object.
monitorNotify | Wakes up a single thread that is waiting on this object's monitor.
monitorNotifyAll | Wakes up all threads that are waiting on this object's monitor.
monitorWait | Waits to be notified by another thread of a change in this object.
Object_GetClass | Retrieves the class that the object points to.
PrepareThreadForJava | Thread entry function for calls into the VM.
RNIGetCompatibleVersion | Exported by the DLL to allow the VM to check compatibility.
SignalError | Creates a Java exception object, which is thrown once it returns from the native code.
SignalErrorHResult | Creates a Java exception object from an HRESULT return type.
SignalErrorPrintf | Creates a Java exception object and specifies format string for exception description to be printed when thrown.
UnprepareThreadForJava | Thread exit function for calls into the VM.

ArrayAlloc

HObject* __cdecl ArrayAlloc(int type, int cItems);

Creates an array of primitive type objects.

Return Value:

Returns an allocated object array.

Parameter | Description
type Primitive data type as defined in native.h. The following types are supported:
T_BOOLEAN | A Boolean object.
T_BYTE | A Byte object.
T_CHAR | A Character object.
T_CLASS | A Class object.
T_DOUBLE | A Double object.
T_FLOAT | A Float object.
T_INT | An Integer object.
T_LONG | A Long object
T_SHORT | A Short object.
cItems | Number of items in the array.

ArrayCopy

void __cdecl ArrayCopy(HObject *srch, long src_pos, HObject *dsth,
        long dst_pos, long length);

Copies an array using the Java System.ArrayCopy method.

Parameter | Description
srch | Source object.
src_pos | Starting position in the source object array to copy.
dsth | Destination object.
dst_pos | Position in the destination object array to copy to.
length | Number of objects in the array to copy.

Class_GetAttributes

int __cdecl   Class_GetAttributes(ClassClass *cls);

Retrieves a combination of the ACC_XXX flags for a class as they appear in the Java class file.

Return Value:

Returns attributes flags.

Parameter | Description
cls | Address of the class object.

Remarks:

The following attributes are defined for use in a Java class file and can be retrieved using this function:
Flag | Value
ACC_PUBLIC | 0x0001
ACC_PRIVATE | 0x0002
ACC_PROTECTED | 0x0004
ACC_STATIC | 0x0008
ACC_FINAL | 0x0010
ACC_SYNCH | 0x0020
ACC_SUPER | 0x0020
ACC_THREADSAFE | 0x0040
ACC_VOLATILE | 0x0040
ACC_TRANSIENT | 0x0080
ACC_NATIVE | 0x0100
ACC_INTERFACE | 0x0200
ACC_ABSTRACT | 0x0400

Class_GetField

struct fieldblock * __cdecl Class_GetField(ClassClass *cls, const char *name);

Retrieves a handle to a field explicitly specified by name. This handle is needed to get any further information about the field.

Return Value:

Returns a pointer to the field block.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.
name | Name of the field in the class.

Class_GetFieldByIndex

struct fieldblock * __cdecl Class_GetFieldByIndex(ClassClass *cls, unsigned index);

Retrieves a handle to a field specified by index.

Return Value:

Returns a field block pointer.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.
index | Index value of the field in the class. The index must be between 0 and the field count (returned from Class_GetFieldCount) minus 1, inclusive.

Class_GetFieldCount

unsigned __cdecl  Class_GetFieldCount(ClassClass *cls);

Retrieves the total number of fields in the class, including super and static fields.

Return Value:

Returns the number of fields.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.

Remarks:

This function is intended to be used with Class_GetFieldByIndex to enumerate fields on a class.

Class_GetInterface

ClassClass * __cdecl   Class_GetInterface(ClassClass *cls, unsigned index);

Retrieves an interface specified by index.

Return Value:

Returns a pointer to a class interface object.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.
index | Index value of the interface in the class. The index must be between 0 and the interface count (returned from Class_GetInterfaceCount) minus 1, inclusive.

Class_GetInterfaceCount

unsigned __cdecl            Class_GetInterfaceCount(ClassClass *cls);

Retrieves the total number of interfaces implemented by the class.

Return Value:

Returns the number of interfaces.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.

Class_GetMethod

struct methodblock* __cdecl Class_GetMethod(ClassClass *cls, const char *name, const char *signature);

Retrieves a handle to a method explicitly specified by name. This handle is needed to get any further information about the method.

Return Value:

Returns a handle to a method in the given class specified by name and signature.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.
name | Name of the method in the class.

Class_GetMethodByIndex

struct methodblock* __cdecl Class_GetMethodByIndex(ClassClass *cls, unsigned index);

Retrieves a handle to a method specified by index.

Return Value:

Returns a method block pointer.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.
index | Index value of the method in the class. The index must be between 0 and the method count (returned from Class_GetMethodCount) minus 1, inclusive.

Class_GetMethodCount

unsigned __cdecl            Class_GetMethodCount(ClassClass *cls);

Retrieves the total number of methods in the class, including non-static super methods.

Return Value:

Returns the number of methods.

Parameter | Description
cls | Address of the class object. Use FindClass to determine.

Remarks:

This function is intended for use with Class_GetMethodByIndex to enumerate methods in a class.

This function returns the total count of all members, not just the count of those declared in the class specified. To find declared members, you must enumerate methods and call Member_GetClass on each to determine where the method is implemented.

Class_GetName

const char * __cdecl        Class_GetName(ClassClass *cls);

Retrieves the class name.

Return Value:

Returns class name.

Parameter | Description
cls | Address of the class object.

Class_GetSuper

ClassClass * __cdecl        Class_GetSuper(ClassClass *cls);

Retrieves the superclass.

Return Value:

Returns the superclass.

Parameter | Description
cls | Address of the class object.

ClassArrayAlloc

HObject* __cdecl ClassArrayAlloc(int type, int cItems, char *szSig);

Creates an array of objects.

Return Value:

Returns an allocated object array.

Parameter | Description
type Type of objects in the array. The following types are supported:
T_BOOLEAN | A Boolean object.
T_BYTE | A Byte object.
T_CHAR | A Character object.
T_CLASS | A Class object (use szSig to specify the class).
T_DOUBLE | A Double object.
T_FLOAT | A Float object.
T_INT | An Integer object.
T_LONG | A Long object.
T_SHORT | A Short object.
cItems | Number of elements in the array to allocate.
szSig | Signature of the class if type is T_CLASS. (For example, "java/awt/Rectangle".)

do_execute_java_method

long __cdecl do_execute_java_method(ExecEnv *ee, void *obj, char *method_name,
        char *signature, struct methodblock *mb, bool_t isStaticCall, ...);

Calls a Java method.

Return Value:

Returns TRUE if successful, or FALSE otherwise.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. This parameter should be set to NULL.
obj | Object pointer.
method_name | Name of the method to invoke. Set to NULL if using a method block.
signature | Types of parameters passed to the constructor. See execute_java_dynamic_method for a description of signature characters. Pass NULL if using a method block.
methodblock | Address of the cached method block data structure. Use get_methodblock to retrieve this. The underlying structure of the method block is not defined; it is used only to prevent accidental type misuse using the alternative, PVOID.
isStaticCall | True if calling a static method, or false otherwise.

Remarks:

This is a helper function for the execute_java_static_method and execute_java_dynamic_method functions. It can be used when making repeated calls to a method to avoid the overhead of name lookup on each call. Note that invoking a Java method can cause garbage collections.

The following example demonstrates calling this function for repeated access to the Rectangle.move method:

struct {
    Hjava_awt_Rectangle *phRectangle;
} gc;

struct methodblock *pmb = get_methodblock(gc.phRectangle, "move", "(II)V");

for (i=0; i < 10; i++)
{
  do_execute_java_method(NULL, gc.phRectangle, NULL, NULL, pmb, FALSE, x, y);
}

exceptionClear

void __cdecl exceptionClear(ExecEnv *ee);

Clears any pending exceptions.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.

exceptionDescribe

void __cdecl exceptionDescribe(ExecEnv *ee);

Invokes printStackTrace on the pending exception.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.

exceptionOccurred

bool_t __cdecl exceptionOccurred(ExecEnv *ee);

Determines if an exception has occurred in the called Java method without exiting the native code.

Return Value:

Returns TRUE if an exception occurred, or FALSE otherwise.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.

exceptionSet

void exceptionSet(ExecEnv *ee, HObject *phThrowable);

Sets the pending exception. Calling exceptionSet(ee, NULL) produces the same result as calling exceptionClear(ee).

Return Value:

No return value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
phThrowable | A pointer to the exception to set.

execute_java_constructor

HObject* __cdecl execute_java_constructor(ExecEnv *ee, char *classname,
        ClassClass *cb, char *signature, ...);

Allocates a new Java object and invokes a constructor.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. This parameter should be set to NULL.
classname | Name of the class if the cb parameter is NULL. Use forward slashes (/) instead of dots as package delimiters. (For example, "java/lang/System".)
cb | Address of the class object. Use NULL and provide classname if not known.
signature | Types of parameters passed to the constructor. See execute_java_dynamic_method for a description of signature characters. The return type for all constructors, 'V', is automatically appended and should not be specified.

execute_java_constructorV

HObject* __cdecl execute_java_constructorV(ExecEnv *ee, const char *classname,
        ClassClass *cb, const char *signature, va_list args);

Allocates a new Java object and invokes a constructor. This method accepts a va_list argument list as a paramenter instead of ellipses.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. This parameter should be set to NULL.
classname | Name of the class if the cb parameter is NULL. Use forward slashes (/) instead of dots as package delimiters. (For example, "java/lang/System".)
cb | Address of the class object. Use NULL and provide classname if not known.
signature | Types of parameters passed to the constructor. See execute_java_dynamic_method for a description of signature characters. The return type for all constructors, 'V', is automatically appended and should not be specified.
args | Additional arguments.

execute_java_dynamic_method

long __cdecl execute_java_dynamic_method(ExecEnv *ee, HObject *obj, char
        *method_name, char *signature, ...);

Invokes a Java dynamic method.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
obj | Address to the Java object containing method.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method (see below) .

Remarks:

The signature parameter specifies the parameters and return type of the method by enclosing the character codes for parameter types in parentheses, followed by the character code for the return type. The following table shows the mapping of types to signature characters:
Character | Java Type
[ array
Z | boolean
B | byte
C | char
D | double
F | float
I | int
J | long
L | object
S | short
V | void

Arrays must be followed by the array type. For example, "[C" for a character array. For multidimensional arrays, repeat "[" for the number of dimensions. For example, "[[Z" signifies a two-dimensional boolean array.

For objects, the signature is followed by the object class name and ends with a semicolon (;). For example, the signature for the a Rectangle object is "Ljava/awt/Rectangle;"

The following example uses this function to call the Rectangle.move method with two integer parameters to the method, x and y:

long lrval = execute_java_dynamic_method(NULL, phRectangle, "move","(II)V", x, y);

execute_java_dynamic_method64

int64_t __cdecl execute_java_dynamic_method64(ExecEnv *ee, HObject *obj, char
        *method_name, char *signature, ...);

Invokes a Java dynamic method. This method is equivalent to the execute_java_dynamic_method except it returns a 64 bit value instead of a 32 bit long.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
obj | Address to the Java object containing method.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method.

execute_java_dynamic_methodV

int64_t __cdecl execute_java_dynamic_methodV(ExecEnv *ee, HObject *obj, const char
        *method_name, const char *signature, va_list args);

Invokes a Java dynamic method. This method is equivalent to the execute_java_dynamic_method except it returns a 64 bit value instead of a 32 bit long, and accepts a va_list argument list as a parameter.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
obj | Address to the Java object containing method.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method.
args | Additional arguments.

execute_java_interface_method

long __cdecl execute java_interface_method(ExecEnv *ee, HObject *pobj, ClassClass j_interface,
 const char *method_name, const char *signature, ...);

Invokes a Java interface method.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
pobj | Address to the Java object containing method.
j_interface | A java class interface.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method.

execute_java_interface_method64

int64_t __cdecl execute java_interface_method64(ExecEnv *ee, HObject *pobj, ClassClass j_interface,
 const char *method_name, const char *signature, ...);

Invokes a Java interface method. This method is equivalent to the execute_java_interface_method, except it returns a 64 bit value instead of a 32 bit long.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
pobj | Address to the Java object containing method.
j_interface | A java class interface.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method.

execute_java_interface_methodV

int64_t __cdecl execute_java_interface_methodV(ExecEnv *ee, HObject *pobj,
        ClassClass j_interface, const char *method_name, const char *signature, va_list args);

Invokes a Java interface method. This method is equivalent to the execute_java_interface_method, except it returns a 64 bit value instead of a 32 bit long and accepts a va_list argument list as a a parameter.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
pobj | Address to the Java object containing method.
j_interface | A java class interface.
method_name | Name of the method to be called.
signature | Types of parameters and return type of the method.
args | Additional arguments.

execute_java_static_method

long __cdecl execute_java_static_method(ExecEnv *ee, ClassClass *cb,
        char *method_name, char *signature, ...);

Invokes a Java static method.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. Pass NULL.
cb | Address of the class object, obtained with the FindClass function.
method_name | Name of the method to be called.
signature | Types of parameters passed to the constructor. For a description of signature characters, see execute_java_dynamic_method.

execute_java_static_method64

int64_t __cdecl execute_java_static_method64(ExecEnv *ee, ClassClass *cb,
        char *method_name, char *signature, ...);

Invokes a Java static method. This method is equivalent to the execute_java_dynamic_method, except it returns a 64 bit value instead of a 32 bit long.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.
cb | Address of the class object, obtained with the FindClass function.
method_name | Name of the method to be called.
signature | Types of parameters passed to the constructor. For a description of signature characters, see execute_java_dynamic_method64.

execute_java_static_methodV

int64_t __cdecl execute_java_static_methodV(ExecEnv *ee, ClassClass *cb,
        const char *method_name, const char *signature, va_list args);

Invokes a Java static method. This method is equivalent to the execute_java_dynamic_method, except it returns a 64 bit value instead of a 32 bit long, and accepts a va_list argument list as a parameter.

Return Value:

A 64 bit value.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.
cb | Address of the class object, obtained with the FindClass function.
method_name | Name of the method to be called.
signature | Types of parameters passed to the constructor. For a description of signature characters, see execute_java_dynamic_method64.
args | Additional arguments.

Field_GetXXX

__int32 __cdecl             Field_GetValue(HObject *obj, struct fieldblock * field);
__int64 __cdecl             Field_GetValue64(HObject *obj, struct fieldblock * field);
float __cdecl                  Field_GetFloat(HObject *obj, struct fieldblock * field);
double __cdecl              Field_GetDouble(HObject *obj, struct fieldblock * field);
#define Field_GetBoolean(obj,field)     ((bool_t)       Field_GetValue(obj,field))
#define Field_GetByte(obj,field)        ((signed char)  Field_GetValue(obj,field))
#define Field_GetChar(obj,field)        ((unicode)      Field_GetValue(obj,field))
#define Field_GetShort(obj,field)       ((short)        Field_GetValue(obj,field))
#define Field_GetInt(obj,field)                         Field_GetValue(obj,field)
#define Field_GetLong(obj,field)                        Field_GetValue64(obj,field)
#define Field_GetObject(obj,field)      ((HObject*)     Field_GetValue(obj,field))
#define Field_GetFloat(obj,field)                       Field_GetFloat(obj,field)
#define Field_GetDouble(obj,field)                      Field_GetDouble(obj,field)

Retrieves the value of the specified field.

Return Value:

Returns a value of a type determined by the function.

Parameter | Description
obj | Address of the object that the field belongs to.
field | Field block of the field.

Remarks:

These functions operate on static or non-static fields, including both of the component object model (COM) MapsTo fields and the fields in Java objects.

Field_GetOffset

unsigned __cdecl Field_GetOffset(struct fieldblock * field);

Returns the offset of dynamic fields in the class.

Return Value:

Returns the offset of the field relative to the object for non-static fields. Returns 0 for static fields.

Parameter | Description
field | Field block of the field. The underlying structure of field block is not defined; it is used only to prevent accidental type misuse using the alternative, PVOID.

Remarks:

Note that this function accounts for the 'MSReserved' value at the top of structures generated by msjavah. This means you can just add this value to the base of the object to get to the data.

Field_GetStaticPtr

PVOID __cdecl  Field_GetStaticPtr(struct fieldblock * field);

Returns an address of the static data.

Return Value:

Returns an address to the data for static fields, or NULL for non-static fields.

Parameter | Description
field | Field block of the field. The underlying structure of field block is not defined; it is used only to prevent accidental type misuse using the alternative, PVOID.

Field_SetXXX

void __cdecl                Field_SetValue(HObject *obj, struct fieldblock * field, __int32 value);
void __cdecl                Field_SetValue64(HObject *obj, struct fieldblock * field, __int64 value);
void __cdecl                Field_SetFloat(HObject *obj, struct fieldblock * field, float value);
void __cdecl                Field_SetDouble(HObject *obj, struct fieldblock * field, double value);
#define Field_SetBoolean(obj,field,value)               Field_SetValue(obj,field,(bool_t)(value))
#define Field_SetByte(obj,field,value)                  Field_SetValue(obj,field,(signed char)(value))
#define Field_SetChar(obj,field,value)                  Field_SetValue(obj,field,(unicode)(value))
#define Field_SetShort(obj,field,value)                 Field_SetValue(obj,field,(short)(value))
#define Field_SetInt(obj,field,value)                   Field_SetValue(obj,field,value)
#define Field_SetLong(obj,field,value)                  Field_SetValue64(obj,field,value)
#define Field_SetObject(obj,field,value)                Field_SetValue(obj,field,(__int32)(value))
#define Field_SetFloat(obj,field,value)                 Field_SetFloat(obj,field,value)
#define Field_SetDouble(obj,field,value)                Field_SetDouble(obj,field,value)

Sets the value of the specified field.

Parameter | Description
obj | Address of the object that the field belongs to.
field | Field block of the field.

Remarks:

These functions operate on static or non-static fields, including both of the COM MapsTo fields and the fields in Java objects.

FindClass

ClassClass* __cdecl FindClass(ExecEnv *ee, char *classname, bool_t resolve);

Retrieves a class object pointer for a named class.

Return Value:

Returns a pointer to the class.

Parameter | Description
ee | Placeholder for execution environment, which is not needed by the Microsoft VM. Set this parameter to NULL.
classname | Name of the class to locate.
resolve | Ignored. Classes found will always be ignored.

Remarks:

Use this function to get a pointer to a class, named by classname. This pointer can be used in the execute_java_static_method function to identify the class.

FindClassEx

ClassClass* __cdecl FindClassEx(char *pszClassName,DWORD dwFlags);

Retrieves a class object pointer for a named class, according to the specified flags.

Return Value:

Returns a pointer to the class.

Parameter | Description
pszClassName | Name of the class to locate.
dwFlags One of the following flags:
FINDCLASSEX_NOINIT | If the class is a system class, will prevent the classes static initializer from running.
FINDCLASSEX_IGNORECASE | Will perform a case-insensitive validation of the class name, as opposed to the case-sensitive validation that normally occurs.
FINDCLASSEX_SYSTEMONLY | Will only look for the named class as a system class.

Remarks:

This method is similar to the FindClass method, but accepts arguments to control the class load operation.

GCDisable

int     __cdecl GCDisable();

Increments the block count and disables garbage collection.

Return Value:

Returns TRUE if successful, or FALSE otherwise.

Remarks:

Use this function to disable garbage collection after you have enabled it using GCEnable.

GCDisableCount

int     __cdecl GCDisableCount();

Disables the counting used by GCEnable and GCDisable.

Return Value:

Returns the current count.

Remarks:

Used for diagnostic purposes. Since the use of GCEnable and GCDisable requires a counter, this provides a way to verify that the count is what is expected.

GCDisableMultiple

void    __cdecl GCDisableMultiple(int cDisable);

Increments the block count a specified number of times.

Parameter | Description
cDisable | Number of times to increment the block count.

Remarks:

This function is useful when you have previously called GCEnableCompletely to allow garbage collection on all referenced objects, but later want to reinstate the block count with one call. The following example shows enabling garbage collection around a sleep call.

    int nEnable = GCEnableCompletely();
    Sleep( (int) millis );
    GCDisableMultiple(nEnable);

GCEnable

int     __cdecl GCEnable();

Decrements the block count and enables garbage collection by the VM.

Return Value:

Returns TRUE if successful, or FALSE otherwise.

Remarks:

When calling a native function from within Java, garbage collection is blocked by default. If the native function call is going to take some time, you can enable garbage collection with this call. However, you should first use the GCFramePush function to allow the garbage collector to track any Java objects that you care about during garbage collection.

GCEnableCompletely

int     __cdecl GCEnableCompletely();

Decrements the block count to 0 and enables garbage collection by the VM.

Return Value:

Returns the block count before entering this function.

Remarks:

This function enables garbage collection, regardless of the number of calls previously made to GCDisable, incrementing the block count.

GCFramePop

void    __cdecl GCFramePop(PVOID pGCFrame);

Restores the GCFrame with current values for members of the structure.

Parameter | Description
pGCFrame | Address of a garbage collection frame that references a structure with Java objects that are being tracked.

GCFramePush

void    __cdecl GCFramePush(PVOID pGCFrame, PVOID pObjects,
                DWORD cbObjectStructSize);

Informs the VM garbage collector of a GCFrame to track.

Parameter | Description
pGCFrame | Address of a garbage collection frame referencing the pObjects structure.
pObjects | Structure containing the Java objects to track during garbage collection.
cbObjectStructSize | Size of pObjects structure.

Remarks:

The garbage collector initializes the structure referenced by pObjects to NULL.

GCFreeHandle

void __cdecl GCFreeHandle(HObject **pphobj);

Frees a strong pointer, originally obtained using GCNewHandle.

Parameter | Description
pphobj | Pointer to a pointer to be freed.

GCFreePtr

void __cdecl GCFreePtr(HObject **pphobj);

Frees a garbage collection pointer originally obtained using GCGetPtr.

Parameter | Description
pphobj | Pointer to a pointer to be freed.

GCGetPtr

HObject** __cdecl GCGetPtr(HObject *phobj);

Allocates a "weak" pointer for an object, and then updates it when garbage collection occurs.

Return Value:

Returns an address to a pointer to a Java object handle.

Parameter | Description
phobj | Address of a Java object.

Remarks:

Given a pointer to an object, this function allocates and returns the address of that object pointer, and then updates the contained pointer when GC occurs. Note that if the object gets freed during GC, the value of the contained pointer will be NULL. A "weak" pointer is different from a "strong" pointer (as allocated by GCNewHandle). A weak pointer will not block garbage collection (removal) of the referenced object, but a strong pointer will. (Strong pointers are scanned like any other object during GC; weak pointers are updated after the GC has been completed.)

GCNewHandle

HObject** __cdecl GCNewHandle(HObject *phobj);

Creates a "strong pointer" to an object.

Return Value:

Returns an address to the object pointer.

Parameter | Description
phobj | Object that is be referenced.

Remarks:

Using this function is similar to placing an object in a GCFrame; however, strong pointers can be stored statically across calls. A strong pointer prevents the object from being collected as garbage, whereas a weak pointer only tracks the object's movement.

GCSetObjectReferenceForHandle

void __cdecl GCSetObjectReferenceForHandle (HObject** handle, HObject* phobj);

GC-safe method for updating the contents of a handle.

Return Value:

No return value.

Parameter | Description
handle | The result of calling GCGetPtr for a weak pointer or GCNewHandle for a strong handle.
phobj | The new object pointer.

Remarks:

If handles are not updated using a GC-safe method, the VM will fault during the next GC.

GCSetObjectReferenceForObject

void __cdecl GCSetObjectReferenceForObject (HObject** location, HObject* phobj);

GC-safe method for updating the fields in an object.

Return Value:

No return value.

Parameter | Description
location | Pointer to a field of an object.
phobj | The new object pointer.

Remarks:

The safest method to set a field in an object is to use the Field_SetValue method. If objects are not updated using a GC-safe method, the VM will fault during the next GC.

get_methodblock

struct methodblock* __cdecl get_methodblock(HObject *pjobj, char *method_name,
        char *signature);

Retrieves a pointer to a method block structure containing the class name, method name, and parameter and return types of a method.

Return Value:

Returns a handle to a method in the given object specified by name and signature. This is useful for functions like do_execute_java_method, which can use this information directly instead of having to look it up.

Parameter | Description
pjobj | Address of the structure.
method_name | Name of the method to invoke.
signature | Types of parameters passed to the constructor. For a description of signature characters, see execute_java_dynamic_method.

GetNativeMethodCallersClass

ClassClass * __cdecl GetNativeMethodCallersClass();

Determines the class type of the caller.

Return Value:

Returns a pointer to the class type of the caller.

GetNativeMethodCallersMethodInfo

struct methodblock* __cdecl GetNativeMethodCallersMethodInfo();

Retrieves information about the caller's method.

Return Value:

Returns a method block pointer.

getPendingException

HObject *getPendingException(ExecEnv *ee);

Retrieves a pending exception.

Return Value:

Returns the pending exception; if no exception is pending, NULL is returned.

Parameter | Description
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.

HResultFromException

HResult __cdecl HResultFromException(OBJECT* exception_object);

Creates an HRESULT return type from a Java exception object. This function prototype is found in the nativcom.h header file.

Return Value:

An HRESULT type.

Parameter | Description
exception_object | The exception object to covert to an HRESULT.

is_instance_of

BOOL is_instance_of(JHandle *phobj, ClassClass *dcb, ExecEnv *ee);

Determines whether the specified object phobj can be cast to the specified class type dcb.

Return Value:

Returns TRUE if the object can be cast to the class type; otherwise, returns false.

Parameter | Description
phobj | A pointer to an object.
dcb | A class type.
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.

is_subclass_of

BOOL is_subclass_of(ClassClass *cb, ClassClass *dcb, ExecEnv *ee);

Determines whether the class type cb is a subclass of type dcb.

Return Value:

Returns TRUE if the class is a subclass of dcb; otherwise, returns false.

Parameter | Description
cb | The class type that is being tested.
dcb | The class type to test against.
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.

ImplementsInterface

BOOL ImplementsInterface(ClassClass *cb, ClassClass *icb, ExecEnv *ee);

Determines whether the class type cb implements the interface represented by the icb class type.

Return Value:

Returns TRUE if the class implements the specified interface.

Parameter | Description
cb | The class type to test.
icb | The class type that represents an interface to test against.
ee | Placeholder for the execution environment, which is not needed by the Microsoft VM. Pass NULL.

isInstanceOf

BOOL __cdecl isInstanceOf(JHandle *phobj, char *classname);

Determines if a specified Java object is an instance of a particular class.

Return Value:

Returns TRUE if the handle is an instance of the class, or FALSE otherwise.

Parameter | Description
pohobj | Address of the Java handle.
classname | Name of the Java class.

javaString2CString

char* __cdecl javaString2CString(Hjava_lang_String *s, char *buf, int buflen);

Retrieves the characters of the Java String object into a C string buffer.

Return Value:

Returns the address of the C string.

Parameter | Description
s | Java String object.
buf | C string buffer.
buflen | Length of the C string buffer.

Remarks:

Use this function in place of the JDK makeCString function which is unsupported by the Microsoft Raw Native Interface. No allocation occurs with his function.

javaStringLength

int __cdecl javaStringLength(Hjava_lang_String *s);

Retrieves the length of the Java String object.

Return Value:

Returns the number of characters in the string.

Parameter | Description
s | Java String object.

javaStringStart

unicode * __cdecl javaStringStart (HString *string);

Returns a temporary pointer to the first character of the Java String object. It is important that you use this method rather than try to manipulate RNI structures that handle string types. The Microsoft VM for Java handles strings differently in certain situations, and strings may be stored with multiple objects.

Return Value:

Returns a string pointer.

Parameter | Description
string | The String handle to reference.

Remarks:

Note that this pointer may change following garbage collection.

jio_snprintf

int __cdecl jio_snprintf(char *str, size_t count, const char *fmt, ...);

Prints to a string with a buffer limit.

Return Value:

Returns the length of the string after printing to it.

Parameter | Description
str | String to print to.
count | Limit of the number of characters to print.
fmt | Format string (see sprintf).

jio_vsnprintf

int __cdecl jio_vsnprintf(char *str, size_t count, const char *fmt, va_list  args);

Prints to a string with a buffer limit using a va_list macro for arguments.

Return Value:

Returns the length of the string after printing to it.

Parameter | Description
str | String to print to.
count | Limit of the number of characters to print.
fmt | Format string (see sprintf).
args | Argument list.

makeJavaString

Hjava_lang_String* __cdecl makeJavaString(char *str, int len);

Constructs a Java string from a given ANSI C character buffer, converting it to UNICODE.

Return Value:

Returns a string formatted as a Java String object.

Parameter | Description
str | C string to convert.
len | Number of characters in the C string, excluding the terminating NULL.

makeJavaStringW

Hjava_lang_String* __cdecl makeJavaStringW( unicode *pszwSrc, int cch );

Constructs a Java string from a Unicode C character buffer.

Return Value:

Returns a string formatted as a Java String object.

Parameter | Description
pszwSrc | C string to convert.
cch | Number of characters in the C string, excluding the terminating NULL.

makeJavaStringFromUtf8

Hjava_lang_String* __cdecl makeJavaStringFromUtf8(const char *pszUtf8);

Creates a new Java String object, initialized from a NULL-terminated, UTF8-formatted, C string.

Return Value:

Returns a string formatted as a Java String object.

Parameter | Description
pszUtf8 | Initialization string.

Remarks:

Unlike the other RNI string conversion functions, makeJavaStringFromUtf8 does not require a character count but does requires NULL termination of the UTF8 string.

MakeByteString

HArrayOfByte* __cdecl MakeByteString(char *str, long len);

Creates a new array of bytes initialized from the C string.

Return Value:

Returns the converted byte string.

Parameter | Description
str | C string to convert.
len | Number characters in the string, excluding the terminating NULL character.

Member_GetAttributes

int __cdecl   Member_GetAttributes(PVOID member);

Retrieves a combination of the ACC_XXX flags for a field or method, as appears in the Java class file.

Return Value:

Returns attributes flags.

Parameter | Description
member | Method or field block of the member.

Member_GetClass

ClassClass * __cdecl  Member_GetClass(PVOID member);

Retrieves the name of the class that the field or method is implemented in.

Return Value:

Returns the name of a class.

Parameter | Description
member | Address of a method or field block.

Member_GetName

const char * __cdecl        Member_GetName(PVOID member);

Retrieves the method or field name.

Return Value:

Returns the method or field name.

Parameter | Description
member | Address of a method or field block.

Member_GetSignature

const char * __cdecl Member_GetSignature(PVOID member);

Retrieves the signature of the field or method.

Return Value:

Returns a signature.

Parameter | Description
member | Address of a method or field block.

monitorEnter

void __cdecl monitorEnter(unsigned int object);

Enters a synchronization object.

Return Value:

No return value.

Parameter | Description
object | Synchronization object (cast as an int) to enter.

Remarks:

You can use the ObjectMonitorEnter macro to automatically cast the synchronization object to an int and call this method.

monitorExit

void __cdecl monitorExit(unsigned int object);

Exits a synchronization object.

Return Value:

No return value.

Parameter | Description
object | Synchronization object (cast as an int) to exit.

Remarks:

You can use the ObjectMonitorExit macro to automatically cast the synchronization object to an int and call this method.

monitorNotify

void __cdecl monitorNotify(unsigned int object);

Wakes up a single thread that is waiting on this object's monitor.

Return Value:

No return value.

Parameter | Description
object | Synchronization object (cast as an int).

Remarks:

You can use the ObjectMonitorNotify macro to automatically cast the synchronization object to an int and call this method. This method is the native equivalent of the Java.lang.Object.notify method.

monitorNotifyAll

void __cdecl monitorNotifyAll(unsigned int object);

Wakes up all threads that are waiting on this object's monitor.

Return Value:

No return value.

Parameter | Description
object | Synchronization object (cast as an int).

Remarks:

You can use the ObjectMonitorNotifyAll macro to automatically cast the synchronization object to an int and call this method. This method is the native equivalent of the Java.lang.Object.notifyAll method.

monitorWait

void __cdecl monitorWait(unsigned int object);

Waits to be notified by another thread of a change in this object.

Return Value:

No return value.

Parameter | Description
object | Synchronization object (cast as an int).

Remarks:

You can use the ObjectMonitorWait macro to automatically cast the synchronization object to an int and call this method. This method is the native equivalent of the Java.lang.Object.wait method.

Object_GetClass

ClassClass * __cdecl    Object_GetClass(HObject *obj);

Retrieves class that the object points to.

Return Value:

Returns a class object pointer.

Parameter | Description
obj | Class object to retrieve.

PrepareThreadForJava

BOOL __cdecl PrepareThreadForJava(PVOID pThreadEntryFrame);

Thread entry function for calls into the VM.

Return Value:

Returns true if successful; otherwise, returns false.

Parameter | Description
pThreadEntryFrame | An instance of a thread entry frame. This pointer is maintained by the VM and the same pointer should be used in UnprepareThreadForJava when exiting the VM.

Remarks:

This method prepares a Java thread for entering the VM so that calls can be safely made from the thread to native methods.

The following code sample demonstrates the use of invocation APIs:

//  Demonstrates the use of the PrepareThreadForJava and UnprepareThreadForJava
//  invocation APIs.
//

#include <windows.h>
#include <stdio.h>
#include <native.h>

void main(int argc, char *argv[])
{
    ThreadEntryFrame threadEntryFrame;
    ClassClass *pClass;

    //  Call this API before calling into the Microsoft VM to allow it
    //  to allocate any per-thread structures and to do any first-time
    //  initialization. After return from this call, Java objects may be
    //  accessed or RNI APIs may be called.
    if (PrepareThreadForJava(&threadEntryFrame)) {

        pClass = FindClass(NULL, "TestClass", TRUE);

        if (pClass != NULL) {
            execute_java_static_method(NULL, pClass, "someMethod", "()V");
        } else {
            printf("Failed to find class!\n");
        }

        //  Detaches the "entry frame" from this thread.  After return from this
        //  call, it is no longer safe to directly touch Java objects or call
        //  RNI APIs.
        UnprepareThreadForJava(&threadEntryFrame);

    } else {
        printf("Failed to initialize thread!\n");
    }
}

RNIGetCompatibleVersion

DWORD __declspec(dllexport) __cdecl RNIGetCompatibleVersion();

Allows the VM to determine if the dynamic link library (DLL) is compatible.

Return Value:

Returns the version used by the DLL (defined as RNIVER in native.h).

Remarks:

All raw native interface DLLs must export this function to enable compatibility-checking by the VM.

SignalError

void __cdecl SignalError(struct execenv *ee, char *ename, char *DetailMessage);

Creates a Java exception object, which is thrown upon returning from the native code.

Parameter | Description
ee | Placeholder for executive environment, which is not needed. This parameter should be NULL.
ename | Name of a valid Throwable exception class or subclass.
DetailMessage | Message to display with the exception. Can be set to NULL.

SignalErrorHResult

void __cdecl SignalErrorHResult(HRESULT theHRESULT);

Creates a Java exception object from an HRESULT return type. This function prototype is found in the nativcom.h header file.

Return Value:

No return value.

Parameter | Description
theHRESULT | The standard return value that indicates whether a function call is a success.

SignalErrorPrintf

void __cdecl SignalErrorPrintf( char *ename, char *pszFormat, ...);

Creates a Java exception object and specifies a format string for exception description to be printed when thrown.

Parameter | Description
ename | Name of a valid Throwable exception class or subclass.
pszFormat | Format string. See C printf function.

UnprepareThreadForJava

VOID __cdecl UnprepareThreadForJava(PVOID pThreadEntryFrame);

Thread exit function for calls into the VM.

Return Value:

Returns true if successful; otherwise, returns false.

Parameter | Description
pThreadEntryFrame | An instance of a thread entry frame. This pointer is maintained by the VM and is the same pointer used in PrepareThreadForJava when entering the VM.

Remarks:

This method should be called from any thread when exiting the VM.


Raw Native Interface Structures

Java & Native Code | RNI
Raw Native Interface Structures | RNI

Raw Native Interface Structures

The following structures are found in the native.h header file. RNI uses these structures to access Java arrays and wrap native code for the Microsoft Virtual Machine.

The ThreadEntryFrame and GCFrame structures are used in several RNI functions but are not manipulated directly by the user.

The ClassArrayOf* structs all share the same architecture. The MSReserved field is reserved for the Microsoft Virtual Machine. Each struct contains a length and body field. The body field is a variable length array, with the array's length stored in the length field.

Structures that handle strings and arrays of strings have different architecture because the Virtual Machine handles strings differently in certain situations.

ThreadEntryFrame

typedef struct {
    DWORD	reserved[6];
} ThreadEntryFrame;

This structure is used in the PrepareThreadForJava and UnprepareThreadForJava functions. These functions are thread exit and entry functions that wrap calls into the VM.

Parameter | Description
reserved | Reserved for the Microsoft Virtual Machine.

GCFrame

typedef struct {
    DWORD	reserved[6];
} GCFrame;

This structure is used to wrap a garbage collection frame from native RNI code. It is used in the GCFramePush and GCFramePop methods. For more information on garbage collection issues, see Overview of the Garbage Collection Architecture and in the Raw Native Interface documentation.

Parameter | Description
reserved | Reserved for the Microsoft Virtual Machine.

ClassArrayOfByte

typedef struct ClassArrayOfByte
{
    int32_t MSReserved;
    unsigned long length;
    char body[1];
} ClassArrayOfByte;

This structure is used to access Java arrays of bytes from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in bytes).
body | A variable length array of chars (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfChar

typedef struct ClassArrayOfChar
{
    int32_t MSReserved;
    unsigned long length;
    unsigned short body[1];
} ClassArrayOfChar;

This structure is used to access Java arrays of chars from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in shorts).
body | A variable length array of shorts (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfShort

typedef struct ClassArrayOfShort
{
    int32_t MSReserved;
    unsigned long length;
    short body[1];
} ClassArrayOfShort;

This structure is used to access Java arrays of short type primitives from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in shorts).
body | A variable length array of shorts (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfInt

typedef struct ClassArrayOfInt
{
    int32_t MSReserved;
    unsigned long length;
    long body[1];
} ClassArrayOfInt;

This structure is used to access Java arrays of ints from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in longs).
body | A variable length array of longs (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfLong

typedef struct ClassArrayOfLong
{
    int32_t MSReserved;
    unsigned long length;
    __int64 body[1];
} ClassArrayOfLong;

This structure is used to access Java arrays of long type primitives from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in 64-bit ints).
body | A variable length array of 64 bit ints. (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfFloat

typedef struct ClassArrayOfFloat
{
    int32_t MSReserved;
    unsigned long length;
    float body[1];
} ClassArrayOfFloat;

This structure is used to access Java arrays of floats from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in floats).
body | A variable length array of floats (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfDouble

typedef struct ClassArrayOfDouble
{
    int32_t MSReserved;
    unsigned long length;
    double body[1];
} ClassArrayOfDouble;

This structure is used to access Java arrays of doubles from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in doubles).
body | A variable length array of doubles (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfObject

typedef struct ClassArrayOfObject
{
    int32_t MSReserved;
    unsigned long length;
    HObject *body[1];
} ClassArrayOfObject;

This structure is used to access Java arrays of Objects from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in object references).
body | A variable length array of HObject pointers (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfString

typedef struct ClassArrayOfString
{
    int32_t MSReserved;
    unsigned long length;
    HString  *(body[1]);
} ClassArrayOfString;

This structure is used to access Java arrays of String types from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in string pointers).
body | A variable length array of HString pointers (it is declared as one element because not all C compilers support [] declarations).

ClassArrayOfArray

typedef struct ClassArrayOfArray
{
    int32_t MSReserved;
    unsigned long length;
    JHandle *(body[1]);
} ClassArrayOfArray;

This structure is used to access Java two-dimensional arrays from native RNI code.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array (in elements).
body | A variable length array of JHandle pointers (it is declared as one element because not all C compilers support [] declarations).

ArrayOfSomething

typedef struct
{
    int32_t MSReserved;
    unsigned long length;
} ArrayOfSomething;

This structure serves as a base structure from which others that access Java arrays are derived.

Parameter | Description
MSReserved | Reserved for the Microsoft Virtual Machine.
length | The length of the array. Array lengths are measured in the unit of the array, not in bytes.


Native Code Interface

This article describes the mechanism of calling between Java and native (typically C or C++) code using the Microsoft Win32 VM for Java (Microsoft VM). This will include the native code DLL interface, as well as implications in the mechanism for garbage collection. This does not describe the Component Object Model (COM) interface, which is another method of interfacing the Microsoft VM with native code written in any other language that supports COM.
Existing Native Code Interface
New Native Code interface
Overview of the Garbage Collection Architecture

The purpose of this native code interface is to provide absolutely the fastest possible interface to native code. While using the COM model makes interfacing to the garbage collection system transparent to the programmer, this interface does not. Instead, it places the burden of interfacing with the garbage collection system on the programmer. If raw access to native code is not essential for performance reasons, using COM is the preferred method of accessing non-Java code.


Existing Native Code Interface

Typically when writing Java applications, developers may want to use existing libraries of native code, or call out to routines written in native code for performance reasons. The following is an example (using the current native code interface provided by in the Sun Java VM) of how this is done.

An example of a Java method declaration, which is implemeted in native code, is as follows.

package myPackage;

class  myClass {
    public static native int myMethod  (myOtherClass  myObj);
}

This example declares a static, native method named myMethod within the class myClass in the package myPackage. The method takes myObj (an object of type myOtherClass) as its parameter.

The following example shows how this method can be then be called from within the Java code by invoking (for example):

...
int i;
myOtherClass myObj = new myOtherClass;

i = myClass.myMethod (myObj);
...

The interfacing between Java and C is handled by a program called msjavah. It takes the previous native declaration and produces the following two pieces of code from it.

  1. A C header file that can be used in C code which defines an appropriate prototype method and structure declaration for the containing class.
  2. A stub function that is placed in the same file as the implementation.

The C native code implementation of the method myMethod looks like the following example:

int myPackage_myClass_myMethod (HObject *AlwaysNull, HmyOtherClass *myObj)
{
myOtherClass *mO = unhand (myObj);

    // body of the implementation of the function ...
    // e.g. mO->member;
}

The function is defined with an initial first parameter (AlwaysNull) that is present only for historical reasons (it is always 0 in current Microsoft VM implementations). Note that in the Microsoft Native Code Interface the convention is kept for source code compatibility.

The stub (which msjavah generates) would look like the following:

Java_myPackage_myClass_myMethod_stub (ExecEnv *, paramblock * pPB);

When the function myMethod is called from Java, it is this stub that is called. The parameter block in that stub is unwrapped, pushed onto the stack, and then the myPackage_myClass_myMethod function is called in C. The Java code passes the parameter block from the frame, the stubs unwrap it, and then the stubs pass it on to the actual function that you're interested in calling.

The final piece to calling is the unhand macro used in the C function previously mentioned. This macro relies on the internal object representation (a double indirection between the myObj handle and the data; see below) to provide an actual pointer to the data in C. It is necessary to use the unhand macro to access the object data. Microsoft recommends that unhand be used each time an object is accessed, since the object may have been garbage collected within Java, and a pointer reference to it obtained previously may then point to invalid data. Although existing virtual machines (VMs) other than the Microsoft VM attempt to find and ensure validity of all unhanded object references in any C code that may have been called, there are cases where this attempt may not be sufficient to prevent pointers from becoming invalid.

How Object References are Stored Internally

The following diagram describes the internal storage details of objects within the existing native code system.

Essentially, everywhere that a reference to an object is stored there is a pointer to the handle, which then references the object.

Implications for the Existing Native Code Interface

  • An extra indirection (using the unhand macro) is required to get to every object referenced.
  • Despite the use of unhand, if you have an unhanded value referencing an object, that object may be moved by garbage collection, and the reference that you have could become invalid. To avoid this, when garbage collection occurs under this model, the VM suspends all the threads that were running in Java code and tries to find out where the end of the native stacks are. It then conservatively scans the entire C stack and register set of all threads for any DWORDS that might possibly point into objects. If any are found, these objects are not moved when the garbage collection heap is compacted. Unfortunately, there are cases where this attempt could fail to find all outstanding unhanded references. It is also a somewhat time-consuming process.
  • If there are many different pointers, it's extremely difficult for a compiler to enregister unhanded pointers (given restrictions on the numbers of registers in certain machine architectures). As a result, there will constantly be memory reads, which is generally less efficient.

Conservative scanning, or garbage collection, is the term used when nothing is known about the data that is being checked. It may just be characters or some other simple data type, but if it looks like it may be a pointer, it is treated as such to err on the side of caution. Since the data is not known to be a pointer, it cannot be modified to refer to a new copy of the object that it seems to point to. Instead, the object in question must be fixed in memory and made immovable.

Consequences

The main consequences are loss in performance with native code (which is one of the reasons why native code is used in the first place), and potentially non-deterministic errors when unhand has been used unsafely.


New Native Code interface

In the design of the native code interface in the Microsoft VM, this article has addressed many of the implications of prior interfaces as discussed previously. Internally, object references are pointers directly to the object. The following diagram describes the internal storage details of objects within the Microsoft native code model.

A pointer to this object is a pointer directly to the method table pointer in the object that is located just under the Data. The data is directly above the method table (which is a different data structure than current implementations support). When the Microsoft VM calls native code, it calls the target function directly without going through stubs located in the DLL library. There are stubs, but they are optimized, CPU-specific code generated by the VM.

For source code compatibility and header compatibility, this native code model supports the unhand macro. All the unhand does is cast the handle to a pointer (and add 4 to its address). In the future, Microsoft will have another version of unhand that won't do any arithmetic (but should still be used). There will also be another header file generator that detects this extra method table element at the base and creates appropriate C structures representing this. This will ensure that everything is fully accessible.

Since the Microsoft VM does not conservatively garbage collect native stacks, if any native code has outstanding pointer references during a garbage collection, the same problems that exist with the current native code model could be encountered. To remedy this, while still providing maximum speed with minimum overhead, Microsoft has defined conventions to ensure a deterministic, low overhead solution with respect to outstanding native code pointers. These conventions rely on the fact that native code is responsible for enabling/disabling garbage collection as necessary, and informing the VM of locations in memory where object pointers exist.

Implications for Existing Code

This new native code interface is not binary compatible with the current interface. Existing Java applications that use the native keyword will need to consider the use they make of native code and how long they will be in native code functions. If you are calling native code and returning, it's all right to leave source code as it was with the previous model. If you are going to block or take an undetermined amount of time to perform some task before returning to the VM, you need to ensure that you allow garbage collection. By default, garbage collection is turned off when you enter native code.

Implications and Benefits

  • No extra level of indirection. Objects that are accessed don't require extra code to indirect through handles.

Benefit : performance improvement
  • No explicit stubs

The target method is called directly from the VM. On the fly, the VM creates an assembler stub, which sets up a frame appropriate for the calling convention of the current machine architecture. The process is as follows (the pushes are needed to transpose calling conventions).
setup native frame
push
push
push
call native method

In a way, this is similar to what happens in the existing native code interface, but it's carried out in a highly-optimized form within the VM. This allows the VM to share stubs among similar methods and reduce working set, or optimize absolutely for speed. In either case, the native code libraries themselves can be smaller because they don't contain additional code for parameter unwrapping.

Benefit :  VM chooses optimizations, performance improvement.
  • Using passed parameters is faster

Benefit : performance improvement
  • JIT code is internally more optimized

Benefit : performance improvement

C code is just as portable as before. For the existing native code interface, there is less computer-specific code within the VM to support the model, but there is always porting work required. Stubs are duplicated in every library (DLL or equivalent).


Overview of the Garbage Collection Architecture

These sections describe the goals and implementation details of garbage collection.

Goals

  1. Garbage collection should be transparent for replacing malloc-based C programs.
  2. Garbage collection overhead should be minimal (in terms of time and percentage execution) for most Java applets and applications.

Garbage Collection Mechanism

The key to countering the overhead that occurs while determining the difference between live and dead pointers is to make memory allocation very efficient. Most modern, high performance garbage collectors start with a simple way of allocating memory. To allocate, a current block of memory exists with a part that's used and a part that's free. The new object is added on the end of the used block, and the pointer in the used block is moved. Another block is dynamically allocated when the current block becomes full. The blocks are a fixed size. If you need a larger block ("large" is dependent on tuning; this will typically be between 4K and 8K), a custom block is allocated that has only that object. All the blocks are linked together. The decision about the size of the block is the same trade-off as page size within the operating system.

To distinguish live pointers from dead pointers, we start from a root set where we know there are live pointers. These pointers are followed by copying them into new blocks. Each object that these pointers point to in these roots is worked through recursively. When the end of scanning the new objects in the new copy is reached, every live object has been copied. This scheme can be fairly expensive if you always copy many objects that are very stable. This is improved by taking a snapshot of the last point that was garbage collected and the new point that is garbage collected and copy only the objects that are in between, leaving old objects alone. This is called generational GC, using two generations, in this case.

The large blocks are not copied, they're just logically moved from the old set to the new. Further improvements may be made by considering only roots between the phases the part of memory that has been modified.

Garbage collection is called on allocation of new objects. When a new object is allocated, the garbage collector detects memory threshold (a heuristic is used to decide if it needs to garbage collect and, if so, sets a flag). The VM looks at the flag and initiates the process of checking the block count.

Mark and compact are not used as a garbage collection method, because they are inherently less efficient in situations where you have lots of garbage, which will be typical in Java programs.


Using the Java Language Package Manager

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Package Manager | Welcome!
 | Welcome!

Using the Java Language Package Manager

The Java language supports the concept of Java packages to manage the name space of classes, but does not provide for installing or managing packages. The Microsoft Win32 VM for Java (Microsoft VM) provides package management services with the Java Language Package Manager. Internet Explorer 4.0 uses the Java Language Package Manager to provide code download services for Java applets.

The following articles provide overview information on package management as well as information on how to produce your own distribution units that will install using the Java Language Package Manager services.

  • Java Package Management and Code Download
  • Using DUBuild


Java Package Management and Code Download

The Java language supports the concept of Java packages to manage the namespace of classes, but does not provide for installing or managing packages. The Microsoft Win32 VM for Java (Microsoft VM) provides package management services with the Java Language Package Manager (JPM). Microsoft® Internet Explorer 4.0 uses the JPM to provide code download services for Java applets. This article provides an introduction to the Java Language Package Manager and Internet Explorer 4.0 code download services.

A Brief History of Package Management

A Java package is a collection of classes that share a common namespace. For example, if a class named "test.java" contains the line "package com.ms.fx", the full name of the compiled class will be "com.ms.fx.test". Packages are the building blocks of Java applications—the Java core libraries are a set of packages: java.lang, java.io, and so on.

Early adopters of Java realized that packages would be easier to work with if they could be encapsulated in a single file. The Java community chose to use the public-domain PKZIP archiving standard to encapsulate Java packages. The PKZIP archive format remains the de facto standard for delivering Java packages. Two other packaging standards have since arisen to address the packaging requirements of Java applications: the Sun Microsystems Java Archive (JAR) standard and the Microsoft Cabinet File (CAB) standard.

The Java Archive Standard

The Sun JAR standard appeared in Java Development Kit (JDK) version 1.1. JAR files continue to use the PKZIP archiving standard, but add a manifest component to the Java class files in the archive. The manifest file provides a way to individually digitally sign each class file. Signature files are added in a META-INF directory inside the JAR file.

Compression in JAR files is done on a file-by-file basis. This method of compression can be inefficient because Java class files are often too small to benefit from individual compression.

The Cabinet File Standard

The CAB standard was initially used to package Windows 95 and other products. Cabinet files have since become Microsoft's standard archive format. CAB compression first concatenates all files into a large block and compresses the block, a method similar to the TAR/GZIP archiving standard used on UNIX platforms. This method of compression significantly increases the compression of Java packages.

The Internet Explorer 3.0 Code Download Mechanism

Internet Explorer 3.0 includes a code download feature to allow web distribution of software using cabinet files. To use the code download feature, you first create an inner cabinet with all the files needed for the application. Next, you write a master .inf file to describe how to install the files in the cabinet file. Finally, you place both the .inf file and the inner cabinet file into an outer cabinet file, which you can then use for download.

The OBJECT tag in an HTML file specifies a cabinet file for download. When Internet Explorer sees the OBJECT tag, it checks to see if a current version of the cabinet file is present on the user's system. If not, Internet Explorer downloads the cabinet file and installs it according to the instructions in the enclosed .inf file.

CAB files should be digitally signed before being made available for download. The cabinet standard does not support individually signing each class file—the signature on the cabinet file is assumed to apply to all the files in the archive.

Note Code download is not limited to using the cabinet format. Other archive formats can be used as long as there is some method for digitally signing the archive.

The Internet Explorer 4.0 Solution—Distribution Units

Code download in Internet Explorer 3.0 relies on registry entries to determine if a particular archive (CAB) is installed and, if it is, what version is installed. Version information is maintained at the cabinet-file level—it does not extend to individual packages. The Internet Explorer 3.0 code download mechanism does not provide for uninstalling packages or for providing version information to the virtual machine.

Internet Explorer 4.0 addresses these limitations with a more advanced transport for code download: the Distribution Unit (DU). DUs have version numbers that are checked by browser's code download feature to see if the DU should be downloaded. Each DU contains a list of all of the packages and applications inside the DU. This list, called an Open Software Distribution manifest (OSD), also contains version and security information.

A powerful feature of OSDs is that they can be nested inside other OSDs. This allows a single DU to act as a front-end for a multicomponent application. DUs can also be delivered with push technology. A push channel can check to see if the client has the latest version of content and update the client, if necessary. The issues are largely the same from a package management viewpoint, but from the user's point of view, push is superior to standard browsing because the user does not have to actively check for updates.

The Microsoft SDK for Java includes a utility, dubuild, to create Distribution Units. See Using DUBuild for details on using dubuild to create Distribution Units.

The Java Language Package Manager

The Microsoft VM (the version included with Internet Explorer 4.0 and with the Microsoft SDK for Java 2.5) includes the JPM to handle package installation and management. The JPM's primary function is to find classes when they are needed by the Microsoft VM. When a class is needed, the JPM determines what package the class is in, and then refers to an internal database to determine where the package is stored. The following is a list of the features of the JPM.

  • Version Control. Package version numbers are tracked, allowing Java programs and installers to intelligently update the system.
  • Application Namespaces. Java applications are installed in private namespaces, shielding their classes from name collisions and use by other applications.
  • Improved Security. Instead of having to fully trust all installed classes, the package manager stores the allowed capabilities of each package, as verified by Authenticode.
  • Ease Of Use. Java applications can install packages without having to alter the CLASSPATH environment variable and without requiring a restart.
  • Compatibility. The JPM will install ZIP and JAR archives, as well as cabinet file archives.

Package Installation

Java classes installed on the class path can be used by any Java applet or application. In many cases, a small group of utility classes will be installed for only a few applications of a particular vendor, but because of current class path limitations, will be visible to all applications. This means that the class path gets cluttered quickly with toolkits and libraries that are only used for a few applications.

The JPM allows packages to be installed in an application namespace. These packages are visible only to applications and applets running in the namespace. Packages that need to be visible to all applications (such as the system classes and Application Foundation Classes) are installed in the global namespace. Only packages signed by the namespace's principal are allowed to be installed in the namespace. Applications that have classes in the anonymous package can run without the possibility of name collisions with other installed applications. Without this protection, Java applications cannot be installed. Application namespaces give vendors what is necessary to install Java applets and applications in the Java Language Package Manager.

Security

Security is handled on a package-by-package basis. Each package is in a separate archive, and each archive is digitally signed with a certificate. The certificate indicates which privileges the package requests from the VM and is stored in the JPM. This way, Java packages can be supplied and placed on the local disk without receiving the carte blanche trust of packages in the class path. See Security for more information on Microsoft's security model for Java applications.

FAQ

  • Q1. What is the Java Language Package Manager?
  • Q2. How do I use non-JPM-aware Java development tools?
  • Q3. What is an application namespace and how do I use it?
  • Q4. Can I extract individual packages from the Package Manager?
  • Q5. How can I list currently installed packages?
  • Q6. What is the order of a class search?
  • Q7. What is a Distribution Unit?
  • Q8. How do I make a Distribution Unit for my Java classes?
  • Q9. How do I provide updates for a Distribution Unit?
  • Q10. How do I install a Java applet using Internet Explorer 4.0?
  • Q11. How do I install a stand-alone Java application using Internet Explorer 4.0?

Q1. What is the Java Language Package Manager?

The version of the Microsoft VM included with Internet Explorer 4.0 and the Microsoft SDK for Java 2.5 includes the JPM to handle package installation and management. The JPM's primary function is to find classes when they are needed by the VM. When a class is needed, the JPM determines what package the class is in, and then refers to an internal database to determine where the package is stored. All the standard Java packages shipped with Internet Explorer 4.0 are installed in the Package Manager.

Q2. How do I use Java development tools with the JPM?

When a Java package is installed in the JPM, the original archive file is removed, and the classes are stored internally. You must use the clspack tool to generate the .zip files used by Java development tools. This tool enables you to take packages that are currently installed through the JPM, and write their contents into a .zip file.

The easiest way to use clspack is to type the following command:

clspack -auto

This will create a single classes.zip in your %WINDIR%\Java\Classes directory that contains all classes stored in the JPM. The Jvc compiler, which ships with the Microsoft SDK for Java, looks for classes in this directory by default, so there is no need to change your CLASSPATH environment variable.

If you're using a compiler that does not check this directory by default, set your CLASSPATH environment variable as shown below.

set CLASSPATH=%WINDIR%\Java\Classes\Classes.zip

Q3. What is an application namespace and how do I use it?

The Microsoft VM supports application namespaces—namespaces that are a layer above the namespace of packages and classes. If you have any anonymous classes (classes not in a package) in your DU, you must specify an application namespace when you create the DU—otherwise, the anonymous classes will not be properly installed.

To run a Java applet or stand-alone application that is installed in an application namespace, you must specify the namespace when you run the applet or application. To specify an application namespace when running an applet, add the following parameter to the <APPLET> tag:

<PARAM NAME=namespace value="namespace">

To specify an application namespace for an application, use the -n switch with the jview utility:

jview -n <namespace> <classname>

Q4. Can I extract individual packages from the JPM?

clspack can also be used to extract individual packages. The usage is:

clspack myzipfile.zip <listfile>

The listfile parameter specifies the name of a text file containing the list of packages to extract to the zip.

Q5. How can I list currently installed packages?

If you specify the -dump switch with clspack, it will list all of the packages currently installed in the package manager to the specified outputfile.

clspack -dump <outputfile>

Q6. What is the order of a class search?

When a class is requested, the VM normally searches for it in the following order:

  1. Check explicitly-specified path (typically supplied with the -classpath command-line option).
  2. Search JPM-installed classes.
  3. Check the HKLM\Software\Microsoft\Java VM\TrustedClasspath registry entry.
  4. Check the HKLM\Software\Microsoft\Java VM\TrustedLibsDirectory registry entry.
  5. Check the HKLM\Software\Microsoft\Java VM\Classpath registry entry.
  6. Check the HKLM\Software\Microsoft\Java VM\LibsDirectory registry entry.
  7. Check the CLASSPATH local environment variable.

However, if served from a web page with a trusted applet, the VM additionally searches for the class in the following locations:

  1. Check any cabinet files referenced by the 'cabinets' applet parameter (in the order in which they appear in the HTML).
  2. Check any cabinet file referenced by the 'cabbase' applet parameter.
  3. Check any zip or jar file referenced by the 'archive' tag.
  4. Check for any classes relative to the codebase of the HTML.

Untrusted applets will not search the previously mentioned trusted paths.

Q7. What is a Distribution Unit?

A Distribution Unit (DU) is a transport standard for downloadable archives. A DU is a cabinet file that contains an Open Software Distribution manifest (OSD), which contains details on what version the DU is, the versions of the contents of the DU, and how to install the contents of the DU. DUs are handled by the code download feature of Internet Explorer 4.0. You can create DUs that target Internet Explorer 3, but they are essentially wrapped cabinet files (you still need to work with MASTER.INF and procedures for creating cabinet files) with MSZIP compression. If you place your DU on an HTML page with the <OBJECT> tag, Internet Explorer will automatically install it onto client systems. If a DU contains Java packages, Internet Explorer will invoke the JPM to install them.

Q8. How do I make a Distribution Unit for my Java classes?

To make a DU for a set of Java packages, use the dubuild tool. Given a tree of Java classes, it will archive the tree into a cabinet file and create an Open Software Distribution (OSD) file that has an entry for each package in the tree. For example, consider the following directory tree.

C:\tree ------- tools
           |
           +--- image

The following commands will create c:\first.cab with the packages tree.tools and tree.image.

cd \
dubuild first.cab tree /N MyAppNamespace

Q9. How do I provide updates for a Distribution Unit?

It's possible to create delta DUs that consists only of changed packages and have pointers to a secondary DU that contains the other unchanged packages. The following command will create a cabinet named "second.cab" that has only the changed packages in the tree from the time first.cab was created.

dubuild second.cab tree /P first.cab

The OSD in second.cab points to first.cab for all unchanged packages. Note that a package is considered changed if any one of the files inside has been modified since the time first.cab was created.

Q10. How do I install a Java applet using Internet Explorer 4.0?

To install and run an applet, use the <APPLET> instead of the <OBJECT> tag:

<APPLET
  code=com.mycorp.AppletMain
  width=200
  height=200>
<PARAM NAME=useslibrary VALUE="MyApplet">
<PARAM NAME=useslibrarycodebase VALUE="applet.cab">
<PARAM NAME=useslibraryversion VALUE="1,1,23,0">
</APPLET>

Q11. How do I install a Java application using Internet Explorer 4.0?

You can install stand-alone applications as well as applets using the Internet Explorer 4.0 code download mechanism. Archiving a stand-alone application in a DU is similar to archiving an applet. You should specify an application namespace when creating the DU for your application to prevent possible namespace collisions.

It's a good idea to put an applet inside the DU to notify the user that the download is complete. Use the code parameter of the <APPLET> tag to point to this applet.


About Tools

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Tools | Welcome! | Next
 | Welcome! | Next

About Tools

You use the Microsoft SDK for Java tools to compile, run, and test Java programs and applets. This section provides a quick reference for command-line options of each of the tools and articles that provide more information on using them.

The following articles provide more information about the SDK for Java tools.

  • Tools Quick Reference
  • Introduction to Jexegen
  • Introduction to Jvc
  • Jvc Release Notes
  • Using Jactivex's JavaTLB Compatibility Support
  • Using Jactivex to Create a User-Defined Type for Java/COM Marshaling
  • Introduction to Jview
  • Using Javareg
  • Creating and Using Cabinet Files for Java Applets and Libraries
  • Using DUBuild
  • Signing a Cabinet File with Java Permissions Using Signcode
  • Using the Custom Permission Editor
  • Sample Permissions .INI File
  • Java Permissions .INI Values Reference
  • Jvc Errors and Warning Messages

Quick reference information is provided for the following tools:
Compiling and Debugging
AppletViewer | Runs Java applets.
Awt2afc | Parses source code and suggests changes needed to convert AWT code to use the Application Foundation Classes.
ClassVue | Displays compiled classes at the bytecode level.
Jexegen | Converts Java classes into native executables.
Jntsvc | Converts Java classes into a Microsoft® Windows NT® Service executable.
Jvc | Creates Java applications and applets by compiling Java source code.
Jview | Runs Java applets and applications from the command line.
Qvue | Prints out class method signatures and identifies .class files that were generated from a type library.
Wjview | Runs Java Frame applets and applications that create a frame window in a separate process.
Native Code and COM Tools
Guidgen | Generates globally unique identifiers (GUIDs).
Jactivex | Allows you to host automation-enabled Microsoft® ActiveX® controls in Java and create Java source from type libraries. Used for creating Java/COM interfaces. Replaces javatlb and jcom.
Javareg | Registers a Java class as implementing a COM interface.
Msjavah | Generates C language header files for Java classes.
Resmerge | Combines multiple Win32 resource (.res) files into a single file.
Software Distribution
Cabarc | Handles the archiving of multiple files in a compressed format.
Cert2spc | Creates a Software Publisher's Certificate from one or more X.509 certificates.
Certmgr | Manages and displays certificates, CTLs, and CRLs. Replaces the dumpcert utility.
Chkjava | Allows users to view security information placed in a cabinet file by signcode with the JavaSign DLL.
Chktrust | Checks the validity of a file.
Cprmedit | A Windows-based utility that enables end-users and developers to specify permissions that govern the download of unsigned and signed software when using Internet Explorer 4.0 (and later).
Dubuild | Writes Open Software Distribution files and creates Distribution Units for Java software distribution on Microsoft® Internet Explorer 4.0.
Makecert | Generates a test X.509 certificate.
Piniedit | A Windows-based tool that generates custom Java permissions .ini files for use with the signcode -jp command-line option.
Signcode | Signs cabinet files and gives developers more control over the security restrictions placed on an applet.
Package Manager
Clspack | Writes packages that are installed with package manager to a .zip file archive.
Javasrc | Extracts all java source files from a .zip file archive.


Introduction to Jvc

Working with MS VM
In this topic

* Description of Jvc Syntax

* File Name Syntax

* Using Jvc.exe

* Order of Jvc Options

* Jvc Command Files

* CLASSPATH Environment Variable

* Reference to Jvc Command-Line Options

Tools | Previous | Tools | Next
Jvc Reference | Previous | Tools | Next

Introduction to Jvc

Jvc.exe is the Microsoft compiler for Java (jvc). The compiler produces interpreted (.class) files that will run on any virtual machine.

Important For last-minute changes to jvc, see Jvc Release Notes.

For an alphabetic reference to jvc options, see Reference to Jvc Command-Line Options.

For a listing of error and warning messages produced by jvc, see JVC Errors and Warning Messages.

Description of Jvc Syntax

The Jvc.exe (jvc) command line uses the following syntax:

JVC [options] <filename>

The following table describes input to the jvc command.
Entry | Meaning
option | One or more jvc options. For more information, see Reference to Jvc Command-Line Options. Note that all options apply to all specified source files.
filename | Name of one or more source files.

You can specify any number of options and filenames, as long as the number of characters on the command line does not exceed 1024 or the limit dictated by the operating system.

Note There is no guarantee that future releases of Microsoft® Windows NT® (version 4.0 and later) and Microsoft® Windows® 95 will have the same input limit of 1024 characters for the command line.

Any options that you want to pass to jvc must be supplied before the name of the .class file, or they will be interpreted as command-line arguments to the .class file.

File Name Syntax

The jvc recognizes the following file name syntax:

  • Jvc accepts files with names that follow FAT, HPFS, or NTFS naming conventions.
  • Any filename can include a full or partial path.

    A full path includes a drive name and one or more directory names. Jvc accepts filenames separated either by backslashes (\) or forward slashes (/).

    A partial path omits the drive name, which jvc assumes to be the current drive. If you do not specify a path, jvc assumes the file is in the current directory.

Note If a file does not have an extension, jvc assumes the extension of .java.

Using Jvc.exe

You can use Jvc.exe (jvc) to compile specified .java source files into interpreted .class files. To compile without producing the .class files, use the /nowrite option. You can specify jvc options on the command line. If you are compiling your Java project from the command line, place the options you want to supply to jvc before the name of your .class file on the command line.

Order of Jvc Options

Command-line options can appear anywhere on the Jvc.exe (jvc) command line. Jvc reads the command line from left to right, processing command files in the order it encounters them. Each option applies to all files on the command line. If jvc encounters conflicting options, it uses the rightmost option.

Jvc Command Files

A command file, also referred to as a response file, is a text file that contains information you would otherwise type on the command line. Jvc accepts a command file as an argument on the command line. Unlike the command line, a command file allows you to use multiple filenames.

You should use the following criteria when using command files:

  • A command file can contain only filenames.
  • A command file must not invoke the jvc command.
  • A command file must not contain any jvc compiler options.

A command file is specified by an "at" sign (@), followed by a filename; the filename can specify an absolute or relative path.

CLASSPATH Environment Variable

Use the CLASSPATH environment variable to specify additional class path information when compiling from the command line. The CLASSPATH environment variable has the following syntax.

SET CLASSPATH = <path>

An understanding of where the Microsoft Win32 VM for Java (Microsoft VM) and the command line get class path information will explain why your Java program may behave differently, depending on where it runs. When the Microsoft VM installs, it enters the value C:\Windows\Java\Classes\Classes.zip;.; into the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\Classpath. When a Java program runs, the Microsoft VM first looks for the CLASSPATH value in the registry. If the application executes from the command line, the Microsoft VM also uses the CLASSPATH environment variable, if one has been set.

What this means is if you are executing from the:

  • Command line:

    Class path = C:\Windows\Java\Classes\Classes.zip;.; and the value set in the CLASSPATH environment variable

Reference to Jvc Command-Line Options

This section is an alphabetic reference to all the jvc command-line options. If a command-line option can take one or more arguments, its syntax is shown before its description. Click any option in the following table for information on the option.

Jvc options set from the command line
/cp | /g:l | /O:J
/cp:o | /g:t | /verbose
/cp:p | /nowrite | /w
/d | /O | /?
/g | /O:I

/cp

/cp classpath

Use the /cp option to set the CLASSPATH environment variable for the current compilation. Using this option specifies the path where the jvc or jview command-line tools can find system and user-defined classes. The Java interpreter uses a platform-dependent default location and the CLASSPATH environment variable to find system classes. (See CLASSPATH Environment Variable for more information.) The directories in the class path are separated by semicolons on a Microsoft Windows system; on UNIX, by colons.

Example:

For example, on Windows NT, the class path might be:

JVC /cp x:.;x:\java\classes

In this example, jvc searches in and beneath the directories on the path for system and user-defined classes.

/cp:o

Prints the class path to standard output. This option is especially useful for troubleshooting errors, like "class not found," when compiling from the command line.

Example:

The following example prints the class path to the screen.

JVC /cp:o

/cp:p

/cp:p path

This option is inserted before the path entered to the class path and inserts a semicolon between them.

Remarks:

The value for the class path can come from the CLASSPATH environment variable or from the /cp option. When multiple /cp:p switches are entered, the paths are concatenated.

Example:

The following command concatenates the directories myproj1 and myproj2, and is inserted before the resulting path to the existing class path.

JVC /cp:p myproj1 /cp:p myproj2

/d

/d directory filename

When compiling .java files, use the /d option to specify an output directory other than the current directory for the .class files. If the directory does not exist, jvc will create it.

Example:

The following command compiles the myClass.java file into a myClass.class file and writes this file into the class directory.

JVC /d c:\classdir myClass.java

/g

/g[-] filename

Generates all debugging information. No debugging options are set by default. The effect of using the /g switch is the same as using the following options together.
Option | Action
/g:l | Generates line number information.
/g:t | Generates debug tables.

Remarks:

To disable this option, use a dash (-) after the switch on the command line.

Examples:

The following command creates a .class file called myClass.class that contains debugging information.

JVC /g myClass.java

The following command instructs jvc to exclude debugging information from the myClass.class file.

JVC /g- myClass.java

/g:l

/g:l[-] filename

Generates line numbers that are used when debugging a program. By default, no debugging options are set.

Remarks:

To disable this option, use a dash (-) after the switch on the command line.

Examples:

The following command instructs jvc to generate line-number information for the resulting myClass.class file:

JVC /g:l myClass.java

The following command instructs jvc to turn off line-number generation:

JVC /g:l- myClass.java

/g:t

/g:t[-] filename

Generates debug tables that are used when debugging a program. By default, no debugging options are set.

Remarks:

To disable this option, use a dash (-) after the switch on the command line.

Examples:

The following command instructs jvc to generate debug-table information for the resulting myClass.class file:

JVC /g:t myClass.java

The following command instructs jvc to turn off debug-table generation:

JVC /g:t- myClass.java

/nowrite

/nowrite filename

Tells jvc to compile a .java file and suppress the writing of a .class file.

Example:

In the following example, the myClass.java file is compiled, and errors and warnings are reported, but no myClass.class file is produced.

JVC /nowrite myClass.java

/O

/O filename

Combines optimizing options to produce the fastest possible program. The effect of using this option is the same as using the following options together.
Option | Action
/O:I | Optimizes by inlining methods, when appropriate.
/O:J | Optimizes bytecode jumps. Default optimization setting.

Remarks:

To disable any optimization option, use a dash (-) after the switch on the command line.

Examples:

The following command fully optimizes the code for the myClass.class file that is produced.

JVC /O myClass.java

The following command turns off all code optimization.

JVC /O- myClass.java

/O:I

/O:I filename

Tells the compiler it can inline methods to produce more efficient code. Code that is inlined does not have the overhead associated with a method call. Since there is no mechanism in the Java language to request inlining of methods, use this option when you want the compiler to inline your code.

Remarks:

To disable this option, use a dash (–) after the switch on the command line.

Examples:

The following example evaluates the source code in the myClass.java file and inlines methods where possible. The resulting myClass.class file contains the optimized code.

JVC /O:I myClass.java

The following command turns off all inline-code optimization.

JVC /O:I- myClass.java

/O:J

/O:J filename

Causes jvc to optimize the bytecode jumps in the compiled .class file. This switch tells the compiler to generate code that jumps to another jump. This switch is the compiler's default optimization setting.

Remarks:

To disable this option, use a dash (-) after the switch on the command line.

Examples:

The following example evaluates the source code in the myClass.java file and optimizes the bytecode jumps to produce more efficient code. The resulting myClass.class file contains the optimized code.

JVC /O:J myClass.java

The following command turns off bytecode jump optimization.

JVC /O:J- myClass.java

/verbose

/verbose filename

Instructs jvc to display all messages while compiling a file or project. These messages give useful information about the progress of the compilation.

/w

/w0
/w1
/w2
/w3
/w4

These options control the number of warning messages produced by the compiler. They affect only source files named on the command line.

Compiler warning message numbers begin with "J5." The documentation describes the warnings, indicates each warning's level, and indicates potential problems (rather than actual coding errors) with statements that might not compile as you intend.

The meanings of the options are as follows:
Option | Description
/w0 | Turns off all warning messages.
/w1 | Displays severe warning messages.
/w2 | Displays a less-severe level of warning message than /w1. This is the default.
/w3 | Displays a less-severe level of warning message than /w2, including use of methods with no declared return type, failure to put return statements in methods with non-void return types, and data conversions that would cause loss of data or precision.
/w4 | Displays the least severe level of warning messages.

/x

/x[-] filename

This compiler supports the Java language specification. In addition, the compiler might offer a number of features beyond those required by the Java language specification. These features are available by default, and are not available when the /x option is specified.

Use /x if you plan to port your program to other environments. The /x option tells the compiler to treat extended keywords as simple identifiers and to disable the other Microsoft extensions.

Remarks:

To disable this option, use a dash (-) after the switch on the command line.

Examples:

The following command ignores any extensions used in the myClass.class file.

JVC /x myClass.java

The following command restores the default settings and recognizes the language extensions.

JVC /x- myClass.java

/?

/?

Displays a listing of compiler options to standard output.


Microsoft Visual J++ Compiler

The following notes apply to the Microsoft® Visual J++™ Compiler. Issues identified here are subject to change without notice.

Note This version of the compiler supports @com tags for Java/COM integration. It also supports @dll tags for Microsoft® J/Direct™. For more information on these technologies, see the documentation for J/Direct and @com Directives, provided in the Microsoft SDK for Java.

Using new Java Language Features in Visual J++ 1.1

This release of the Java Language Compiler supports the new language features specified in the JDK 1.1 from Sun Microsystems, Inc., including

  • Inner classes
  • Anonymous classes
  • Instance initializers
  • Anonymous array expressions
  • Class literals
  • Blank finals and final locals
  • The @deprecated tag

It is possible to use these new language features with Microsoft® Visual J++™ 1.1. You may do so by replacing the compiler file in Visual J++ with three files from the Microsoft SDK for Java. First, save a copy of the compiler (jvc.exe) from your existing Visual J++ installation. Next, copy jvc.exe, jps.dll, and msjvc.dll into your Visual J++ directory. Projects will then build using the new compiler.

JDK 1.1 Compatibility

This release of jvc is compatible with the language enhancements specified in the Sun JDK 1.1. The following section briefly describes differences between jvc (the Java Language Compiler from Microsoft) and javac (the Sun Java Compiler).

The following items are in the Inner Classes specification and are implemented by the Sun javac, but not by jvc:

  • There are no known items in this category.

The following items are in the Inner Classes specification, but are not implemented by the Sun javac or by jvc:

  • Inherited members in inner classes

The specification states: "Any inherited member m of a subclass C is in scope within the body of C.... If C itself is an inner class, there may be definitions of the same kind (variable, method, or type) for m in enclosing scopes. In all such cases, the inherited member m hides the other definitions of m. Additionally, unless the hidden definition is a package member, the simple name m is illegal; the programmer must write C.this.m."

Jvc does not implement the last sentence. The simple name m is accepted in these cases. The Sun javac does not implement this, either.

Member Access Protection in Inner Classes

The specification states: "Access protection never prevents a class from using any member of another class, as long as one encloses the other, or they are enclosed by a third class."

In jvc and in the Sun javac, an inner class can access private members of an enclosing class. However, an outer class cannot access private members of an enclosed class, nor can two "sibling" classes, enclosed by a common class, access private members of each other. These rules seem much more logical and useful than those in the specification.

Exceptions Thrown from Anonymous Class Instance Initializers

The specification states: "An instance initializer in an anonymous class can throw any exception."

Jvc does not allow an instance initializer, in an anonymous class, to throw any checked exceptions. Neither does the Sun javac.

The following items are implemented differently by jvc and by Sun's javac:

Deprecation Warnings

Deprecation warnings in jvc are automatic (no /deprecation switch). However, warnings do require that source code with deprecated members be recompiled. Deprecation warnings are emitted at warning level 2.

Inner Class Index Attributes

In the section on the InnerClasses attribute, the specification states: "If an inner class is not a member, its outer_class_index_index is zero. If a class is anonymous, its inner_name_index is zero."

Jvc reads and writes the InnerClasses attributes according to these rules; the Sun javac does not (it never writes zero in either of these fields). Sun's javac may fault when reading the InnerClasses attributes that are produced by jvc.

Inner Class Access to Private Members of Enclosing Class

The specification states: "When an inner class accesses a private field or method of an enclosing class, the accessor method with default (package) access should be inserted to allow the inner class access to the private field or method."

The Sun javac generates code that accesses the private member directly, which may cause verification or illegal access errors on some virtual machines. Jvc does not create accessor methods, but uses a mechanism that is compatible with all virtual machines.

When an inner class accesses a private field or method of an enclosing class, jvc changes the access flags of the field or method to indicate that the member has default (package) protection. An additional attribute is written and read by the compiler that indicates the actual access flags of the member. This attribute can and should be ignored by the virtual machine: it is for the compiler only.

Interface Declarations in Inner Classes

The specification states: "Inner classes may not declare ... member interfaces."

Jvc enforces this rule; the Sun javac does not.

Compatibility with Code Written for Previous Releases of Visual J++

Due to more strict error and security checking in this release of the compiler, some illegal code that compiled without errors using Visual J++ 1.x may now (correctly) fail to compile. One common cause is more careful checking of class member access across package boundaries. Section 3.6.7 of the Java Language Specification contains an example of this scenario.

The following is an example of a typical error message for this type of code.

error J0204:

Cannot access protected member 'x' in class 'Point' via a qualifier of type 'Point3d'


About the Microsoft Visual J++ Compiler

The following notes apply to the Microsoft Visual J++ Compiler, pre-released in the Microsoft SDK for Java. Information listed here is subject to change in the next major release of the product.

Note This version of the compiler supports @dll tags for Microsoft® J/Direct™. It also supports @com tags for Java/COM integration. For more information see the Microsoft SDK for Java.

Using new Java Language Features in Visual J++ 1.1

This release of the Java compiler supports the new language features specified in Sun's JDK 1.1, including: inner classes, anonymous classes, instance initializers, anonymous array expressions, class literals, blank finals and final locals, and the @deprecated tag.

It is possible to use these new language features with Visual J++ 1.1. You may do this by replacing the compiler file in Visual J++ with three files from the Microsoft SDK for Java. First, save a copy of the compiler (jvc.exe) from your existing Visual J++ installation. Next, copy jvc.exe, msjvc.dll, and jps.dll into your Visual J++ directory. Projects will then build using the new compiler.

JDK 1.1 Compatibility

This release of JVC is compatible with the language enhancements specified in Sun's JDK 1.1.

Compatibility with code written for previous releases of Visual J++

Due to more strict error and security checking in this release of the compiler, some illegal code that compiled without errors using Visual J++ 1.x may now (correctly) fail to compile. One common cause is more careful checking of class member access across package boundaries. Section 3.6.7 of the Java Language Specification contains an example of this scenario.

Here is an example of a typical error message for this type of code:

error J0204: Cannot access protected member 'x' in class 'Point' via a qualifier of type 'Point3d'


Introduction to Jvc

Working with MS VM

Tools | Tools
Jvc Reference | Tools

JVC Errors and Warning Messages

This page contains a listing of all JVC Errors and Warning Messages produced by this compiler.

Error Message Links

J0001 | J0021 | J0041 | J0061 | J0081 | J0101 | J0121 | J0141 | J0161 | J0181 | J0201 | J0221 | J0241
J0002 | J0022 | J0042 | J0062 | J0082 | J0102 | J0122 | J0142 | J0162 | J0182 | J0202 | J0222 | J0242
J0003 | J0023 | J0043 | J0063 | J0083 | J0103 | J0123 | J0143 | J0163 | J0183 | J0203 | J0223
J0004 | J0024 | J0044 | J0064 | J0084 | J0104 | J0124 | J0144 | J0164 | J0184 | J0204 | J0224
J0005 | J0025 | J0045 | J0065 | J0085 | J0105 | J0125 | J0145 | J0165 | J0185 | J0205 | J0225
J0006 | J0026 | J0046 | J0066 | J0086 | J0106 | J0126 | J0146 | J0166 | J0186 | J0206 | J0226
J0007 | J0027 | J0047 | J0067 | J0087 | J0107 | J0127 | J0147 | J0167 | J0187 | J0207 | J0227
J0008 | J0028 | J0048 | J0068 | J0088 | J0108 | J0128 | J0148 | J0168 | J0188 | J0208 | J0228
J0009 | J0029 | J0049 | J0069 | J0089 | J0109 | J0129 | J0149 | J0169 | J0189 | J0209 | J0229
J0010 | J0030 | J0050 | J0070 | J0090 | J0110 | J0130 | J0150 | J0170 | J0190 | J0210 | J0230
J0011 | J0031 | J0051 | J0071 | J0091 | J0111 | J0131 | J0151 | J0171 | J0191 | J0211 | J0231
J0012 | J0032 | J0052 | J0072 | J0092 | J0112 | J0132 | J0152 | J0172 | J0192 | J0212 | J0232
J0013 | J0033 | J0053 | J0073 | J0093 | J0113 | J0133 | J0153 | J0173 | J0193 | J0213 | J0233
J0014 | J0034 | J0054 | J0074 | J0094 | J0114 | J0134 | J0154 | J0174 | J0194 | J0214 | J0234
J0015 | J0035 | J0055 | J0075 | J0095 | J0115 | J0135 | J0155 | J0175 | J0195 | J0215 | J0235
J0016 | J0036 | J0056 | J0076 | J0096 | J0116 | J0136 | J0156 | J0176 | J0196 | J0216 | J0236
J0017 | J0037 | J0057 | J0077 | J0097 | J0117 | J0137 | J0157 | J0177 | J0197 | J0217 | J0237
J0018 | J0038 | J0058 | J0078 | J0098 | J0118 | J0138 | J0158 | J0178 | J0198 | J0218 | J0238
J0019 | J0039 | J0059 | J0079 | J0099 | J0119 | J0139 | J0159 | J0179 | J0199 | J0219 | J0239
J0020 | J0040 | J0060 | J0080 | J0100 | J0120 | J0140 | J0160 | J0180 | J0200 | J0220 | J0240

Warning Message Links

J5001 | J5002 | J5003 | J5004 | J5005 | J5006 | J5007 | J5008 | J5009 | J5010
J5011 | J5012 | J5013 | J5014 | J5015 | J5016

J0001 - INTERNAL COMPILER ERROR: 'identifier'

The compiler was unable to recover after detecting an error. Contact Microsoft Product Support Services for further assistance on how to resolve this problem.

J0002 - Out of memory

The compiler attempted to allocate some additional memory during processing, but was unable to do so. When this error occurs, check the location, size, and validity of your system swap file. Also, check that there is sufficient growth space available on the drive on which your swap file resides. This error can also occur if a source file is too large. Break your source file into smaller blocks, and then try compiling again.

J0003 - Invalid code: 'string'

The compiler may have detected generation of invalid code. Try dividing larger methods defined within your classes into smaller methods and compiling again.

J0004 - Cannot open class file 'filename' for reading

The compiler could not open the program source file for reading. This error most likely occurs when another program has an exclusive lock on the source file. Try shutting down other processes that may be accessing the source file and compiling again.

J0005 - Cannot open class file 'filename' for writing

The compiler failed to generate the output .class file. This error most likely occurs when the compiler cannot get write or create permission for the file. Make sure the file does not have its read-only attribute set, and that it is not currently in use by another process. This error can also occur when you are currently running or debugging the program that contains the specified .class file. Stop all running instances of the program and try compiling again.

J0006 - Cannot read class file 'filename'

The compiler failed to read the specified .class file. This error most likely occurs when the compiler encounters an error reading the storage device, or when the compiler cannot otherwise get read permission for the file. Check to ensure the file is not currently in use by another process. Also, use whatever means available (for example, SCANDISK) to ensure the validity of the storage device you are attempting to use.

J0007 - Cannot write class file 'filename'

The compiler failed while attempting to write the contents of a buffer to the specified .class file. This error most likely occurs when space is exhausted on the targeted storage device. Try freeing up any available space on the storage device and compiling again.

J0008 - Cannot locate class file 'filename'

The compiler could not locate a core language class for the java.lang package. This error most likely occurs when the Java CLASSPATH variable is not properly set. Try correcting the CLASSPATH variable, and compiling again.

J0009 - Not used

This error message is currently not used.

J0010 - Syntax error

The compiler could not determine the meaning of an expression or statement within the source program. This error most likely occurs when the line indicated in the error message is syntactically invalid. This error usually accompanies a more descriptive error. Try correcting any accompanying errors and compiling again.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      int i =; // error: initialization error
   }
}

J0011 - Expected ':'

The compiler expected to find a colon following a case label or in a conditional expression that makes use of the ternary operator. This error most likely occurs when the colon is accidentally omitted. Many times this error is caused on the line previous to the line the compiler has reported the error on. Check to make sure lines that require a colon are correct, and then compile again.

The following sample illustrates this error.

public class Simple {

   private int i;
   private static int x = 1;

   public void method1(int arg1) {

      switch (arg1) {
         case 1 // error: ':' omitted
            ; // do something meaningful
      }

      i = ( arg1 < x) ? arg1  x; // error: ':' omitted
   }
}

J0012 - Expected ';'

The compiler expected to find a semicolon in the position indicated by the error message. This error most likely occurs when the semicolon is accidentally omitted from the end of a statement. This error can also occur when a conditional expression is not syntactically correct. Many times this error is caused on the line previous to the line the compiler has reported the error on. Check to make sure both lines of source code have proper semicolon usage, and then compile again.

The following sample illustrates this error.

public class Simple {

   private static int x = 10 // error: ';' omitted

   public void method1(int arg1) {

      for (int i = 1; i < x i++) {
         // error: ';' omitted
         ;
      }
   }
}

J0013 - Expected '('

The compiler expected to find a left parenthesis in the position indicated by the error message. This error most likely occurs when the left parenthesis is accidentally omitted in any of the following situations:

  • type initializations
  • catch statements
  • parenthesized expressions
  • while loops
  • for loops
  • if-else statements
The following sample illustrates this error.

public class Simple {

   private int i;

   public void method1(int arg1, int arg2) {

      if arg1 < arg2) // error: '(' omitted
         i = arg1;
      else
         i = arg2;

   }
}

J0014 - Expected ')'

The compiler expected to find a right parenthesis in the position indicated by the error message. This error most likely occurs when the right parenthesis is accidentally omitted in any of the following situations:

  • type initializations
  • type casts
  • catch statements
  • parenthesized expressions
  • while loops
  • for loops
  • if-else statements
The following sample illustrates this error.

public class Simple {

   private int i;

   public void method1(int arg1, int arg2) {

      i = (arg1 < arg2 ? arg1 : arg2;
      // error: ')' omitted
   }
}

J0015 - Expected ']'

The compiler expected to find a right square bracket in the position indicated by the error message. This error most likely occurs when the right square bracket is accidentally omitted from an array declaration. Many times this error is caused on the line previous to the line the compiler has reported the error on. Check to make sure all brackets match again.

The following sample illustrates this error.

public class Simple {

   private int x[ = new int[500]; // error: ']' omitted

}

J0016 - Expected '{'

The compiler expected to find a left brace in the position indicated by the error message. This error most likely occurs when the left brace is accidentally omitted from the beginning of a class declaration or method code block. Many times this error is caused on the line previous to the line the compiler has reported the error on. Check to make sure all braces match, and then compile again.

The following sample illustrates this error.

public class Simple // error: '{' omitted

   public void method1() {
      // do something meaningful
   }
}

J0017 - Expected '}'

The compiler expected to find a right brace in the position indicated by the error message. This error most likely occurs when a class or method's closing brace is not found. Many times this error is caused on the line previous to the line the compiler has reported the error on. Check to make sure all braces match, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int arr[] = {1, 2A};
      // error: invalid initialization

   }
}

J0018 - Expected 'while'

The compiler expected to find the keyword while in the position indicated by the error message. This error most likely occurs when a do/while loop is not syntactically correct. The correct structure for a do/while loop is:

do {
   // do something useful here
} while (condition);

J0019 - Expected identifier

The compiler expected to find an identifier toward the end of a class, interface, variable, or method declaration. This error most likely occurs when the type is accidentally omitted in a declaration.

The following sample illustrates this error.

public class Simple {

   private i;  // error: type omitted

}

J0020 - Expected 'class' or 'interface'

The compiler expected to find either class or interface used within the corresponding declaration. This error most likely occurs when the keywords are accidentally omitted from a class or interface declaration. Another possible cause of this error is unbalanced scoping braces.

The following sample illustrates this error.

public class Simple {

   // do something meaningful

}}   // error: additional '}' is the problem

J0021 - Expected type specifier

The compiler expected to find a type specifier in the position indicated by the error message. Other errors may accompany this error due to the missing type specifier.

The following example illustrates this error.

public class Simple {

   public Object o =new; //error: missing 'Object' type specifier
}

J0022 - Expected end of file

The compiler expected to encounter an end of file character, but did not. This error most likely occurs when the source file has been damaged in some way. Try visually checking the source file for obvious corruption, save any changes, and then compile again.

J0023 - Expected 'catch' or 'finally'

The compiler expected to find a catch or finally block immediately following a corresponding try block.

The following sample illustrates this error.

public class Simple {

   public void method1( ) {

      try {
         // do something meaningful
      }

   } // error: 'catch' or 'finally' not found
}

J0024 - Expected method body

The compiler expected to find a method body immediately following a method declaration. This error most likely occurs when the braces surrounding the method body are not properly balanced. This error may also occur when the method was intended to be abstract or native, but the abstract or native keyword was mistakenly omitted from the method declaration.

The following sample illustrates this error.

public abstract class Simple {

   public void method1( );
   // error: 'abstract' omitted

}

J0025 - Expected statement

The compiler expected to find a statement before the end of the current scope. This error most likely occurs when the right brace designating the end of the current scope is misplaced.

The following sample illustrates this error.

abstract class Simple {

   void method1() {

      if (1)
      // error: a statement is required
      // after the if statement
   }
}

J0026 - Expected Unicode escape sequence

The compiler expected to find a valid Unicode escape sequence. This error most likely occurs when a syntactical error is found in a Unicode escape sequence.

The following sample illustrates this error.

public class Simple {

   int i = \\u0032;
   // error: '\\' not invalid

}

J0027 - Identifier too long

The compiler detected an identifier name with a length greater than 1024 characters. Shorten the identifier name, and then compile again.

J0028 - Invalid number

The compiler detected a numeric value that the Java language is not capable of supporting. This error most likely occurs when the number specified is an amount greater than any of the Java language's primitive types can accept.

The following sample illustrates this error.

public class Simple {

   long i = 12345678901234567890;
   // error: value out of range

}

J0029 - Invalid character

The compiler detected an ASCII character that could not be used in an identifier. This error most likely occurs when a class, interface, method, or variable identifier includes an invalid character.

The following sample illustrates this error.

public class Simple {

   private int c#;
   // error: '#' not supported

}

J0030 - Invalid character constant

The compiler detected an attempt to assign an invalid character or character escape sequence to a variable of type char.

The following sample illustrates this error.

public class Simple {

   char c = '\';
   // error: invalid escape character

}

J0031- Invalid escape character

The compiler detected the use of an invalid escape character. This error most likely occurs when a syntactical error is found in a Unicode escape sequence.

The following sample illustrates this error.

public class Simple {

   int i = \u032;
   // error: Unicode uses 4 hex digits
   int x = \u0032;
    //correct assignment of a unicode escape sequence

}

J0032 - Unterminated string constant

The compiler did not detect a terminating double-quote character at the end of a string constant. This error most likely occurs when the string terminator is accidentally omitted, or when the string constant is mistakenly divided onto multiple lines.

The following sample illustrates this error.

public class Simple {

   String str = "Hello
   // error: '"' and ';' omitted

}

J0033 - Unterminated comment

The compiler detected the beginning of a block comment, but did not detect a valid ending for it. This error most likely occurs when the comment terminator is accidentally omitted.

The following sample illustrates this error.

public class Simple {

   /* This comment block
    * does not have a valid
    * terminator

}

J0034 - Not used

This error message is currently not used.

J0035 - Initializer block must be declared 'static'

The compiler detected a modifier other than static associated with an initializer. Initializers can only use the static keyword to specify the initializer as a static initializer or no modifier to signify that the initializer is a field initializer. Remove the modifier from the initializer specified in the error message or add the static modifier to the initializer, adn then compile again.

The following sample illustrates this error.

public class Simple {

   static private int i;

   {   // error: 'static' omitted
      i = 1;
   }
}

J0036 - A data member cannot be 'native', 'abstract' or 'synchronized'

The compiler detected one of the modifiers previously shown used in the declaration of a variable. The modifiers synchronized and native can only be applied to method declarations. The abstract modifier can be applied to methods, classes, and interfaces.

J0037 - A method cannot be 'transient' or 'volatile'

The compiler detected one of the modifiers shown above used in the declaration of a method. The modifiers transient and volatile can only be applied to field declarations.

J0038 - 'final' members must be initialized

The compiler detected an uninitialized final variable in an interface definition. Variables declared as final in an interface definition must have their value set at declaration. Once set, the value cannot be programatically changed.

The following sample illustrates this error.

public class Simple {

   private final int COOL_RAD;
   // error: must have value set

}
Note that variables declared within interfaces are implicitly defined as final or static. As such, this error also occurs when their initial values are not set at declaration.

J0039 - Not used

This error message is currently not used.

J0040 - Cannot define body for abstract/native methods

The compiler detected a method body defined immediately following the corresponding declaration of an abstract or native method. An abstract method must have its implementation code defined in a subclass. Native methods are implemented using code of a native language, such as C++.

The following sample illustrates this error.

public interface Simple {

   public void method1() {
      // error: must define this method body
      // in a class that implements the
      // 'Simple' interface
   }
}

Note that methods declared within an interface are implicitly abstract. As such, this error will also occur when you attempt to define a method body in an interface.

J0041 - Duplicate modifier

The compiler detected a modifier used twice in a declaration. This error most likely occurs when the same modifier is mistakenly used more than once within a declaration.

The following sample illustrates this error.

public class Simple {

   public public void method1() { // error: 'public' used twice
      // do something meaningful
   }
}

J0042 - Only classes can implement interfaces

The compiler detected an interface declaration using the implements keyword. Interfaces cannot implement other interfaces. Interfaces may only be implemented by classes.

The following sample illustrates this error.

public interface Simple implements color{
   // error: 'Simple' cannot implement the
   // 'color' interface

}
interface color {
   // do something meaningful
}

J0043 - Redeclaration of member 'identifier'

The compiler detected the same identifier name being declared more than once within the same scope. This error most likely occurs when a variable is mistakenly declared more than once.

The following sample illustrates this error.

public class Simple {
   private int i;
   private int i; // error: 'i' declared twice
}

J0044 - Cannot find definition for class 'identifier'

The compiler could not locate the definition for the specified class. This error is most likely caused by a typographical error. It may also occur when the package containing the specified class cannot be found.

The following sample illustrates this error.

public class Simple {

   char buf[] = new chaar[5];
   // error: 'chaar' not a valid type

}

J0045 - 'identifier' is not a class name

The compiler detected one of the following conditions:

  • A class name provided as part of an import statement could not be found or the import statement was not syntactically valid.
  • The class attempted to extend an interface.

Make sure that the package exists and that any classes that you import exist in the package specified in the import statement, and then compile again.

The following sample illustrates this error.

package non.existent;

import non.existent; // error:

public class Simple {

   // do something meaningful

}

J0046 - 'identifier' is not an interface name

The compiler detected that the identifier referred to by the keyword implements is not an interface.

The following sample illustrates this error.

class Simple2 {

   // do something meaningful

}

public class Simple implements Simple2 {

   // error: cannot implement class 'Simple2'

}

J0047 - 'identifier' is not a package name

The compiler detected an invalid package name. This error most likely occurs when a syntactical error exists in an import statement or when the package name does not otherwise exist.

J0048 - Cannot extend final class 'identifier'

The compiler detected an attempt to subclass a class declared with the keyword final. Classes declared as final cannot be subclassed.

The following sample illustrates this error.

final class Simple2 {

   // do something meaningful

}

public class Simple extends Simple2 {

   // error: cannot extend 'Simple2'

}

J0049 - Undefined name 'identifer'

The compiler detected an unknown class name while processing an import statement. This error most likely occurs when the identifier is misspelled or does not exist. This error may also occur if the CLASSPATH environment variable is not set correctly.

The following sample illustrates this error.

import java.io.bogus; // error: unknown class name

public class Simple {

   // do something meaningful

}

J0050 - 'identifier' is not a member of 'identifier'

The compiler detected a reference to an identifier that is not a member of the specified package. This error most likely occurs when the identifier is misspelled or does not exist.

The following sample illustrates this error.

class Simple2{
   public void methodx(){}
}

public class Simple {

   public void method1() {
      Simple2 smp = new Simple2();
      smp.method2();
      // error: 'method2' not member of 'Simple2'
   }
}

J0051 - Undefined package 'identifier'

The compiler detected a package name, but was unable to locate the package definition. This error most likely occurs when a syntactical error exists in an import statement. This error may also occur when the package cannot be found or does not exist. Make sure the path is set in the CLASSPATH environment variable.

The following sample illustrates this error.

import java.lang.String.*;
// error: 'String' not a valid package name

public class Simple {

   // do something meaningful

}

J0052 - Not used

This error message is currently not used.

J0053 - Ambiguous name: 'identifier' and 'identifier'

The compiler could not resolve an ambiguity between the two identifiers shown. The error most likely occurs when the same class name occurs in two packages that are both imported into a source file using the "*" class import specifier. Make sure that you do not have two classes with the same name in the packages you are importing into your source file.

J0054 - Not used

This error message is currently not used.

J0055 - Not used

This error message is currently not used.

J0056 - Missing return type specification

The compiler detected a method declaration without a return type specified. All method declarations must specify a return type. If the method is not meant to return a value, use the void keyword.

The following sample illustrates this error.

public class Simple {

   public method1() { // error: no return type

      // do something meaningful
   }
}

J0057 - Class file 'identifier' doesn't contain class 'identifier'

The compiler did not detect the class name previously shown within the specified file. This error most likely occurs when the class name is either misspelled or does not exist. This error may also occur when a .class file has been renamed after successful compilation.

J0058 - Cannot have a variable of type 'void'

The compiler detected a variable declared as type void. The keyword void is not allowed in variable declarations. Rather, void can only be used as a method return type, indicating that the method does not actually return a value.

The following sample illustrates this error.

public interface Simple {

   public final static void i = 1;
   // error: 'void' not valid
}

J0059 - Cannot reference member 'identifier' without an object

The compiler detected an attempt to reference a variable without a known object association. This error most likely occurs when an instance field or method (a field or method declared without the keyword static) is referenced from within a static method without a valid instance. Static methods cannot use instance fields and methods without a valid instance of the class.

The following sample illustrates this error.

public class Simple {

   private int x;

   public static void method1() {

      x = 0; // error: 'x' must be static
   }
}

J0060 - Invalid forward reference to member 'identifier'

The compiler detected an attempt to initialize a variable with another variable that had not yet been defined. To avoid this situation, reverse the field declarations order so that a variable that is referenced by another is defined first.

The following sample illustrates this error.

public class Simple {

   private static int i = j;
   // error: 'j' not yet defined
   private static int j = 0;
}

J0061 - The members 'identifier' and 'identifier' differ in return type only

The compiler detected a subclass method attempting to overload a base class method, but the methods differed only in return type. In Java, overloaded methods must be distinguished by unique signatures. A unique signature consists of the method name, the number, type and positions of its parameters, and the return type.

The following sample illustrates this error.

public class Simple extends Simple2 {

   public void method1() {
      // error: only return type differs
   }
}

class Simple2 {

   public int method1() {

      return 1;
   }
}

J0062 - Attempt to reduce the access level of member 'identifier'

The compiler detected an overridden method in the class being compiled that reduces the access level of its base class method. The base class access modifier for a method must be maintained by all derived classes that want to overload the method.

J0063 - Declare the class abstract, or implement abstract member 'identifier'

The compiler detected the declaration of an abstract method within a class, but the class was not declared to be abstract.

The following sample illustrates this error.

public class Simple {

   public abstract void method1();
   // error: class not abstract

}

J0064 - Not used

This error message is currently not used.

J0065 - Cannot assign to this expression

The compiler detected an expression in the position normally held by an lvalue for assignment. This error most likely occurs when an expression is being assigned a value, but the expression is not capable of accepting the assignment.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int x = 0;
      int y = 1;

      x++ = y; //error: '++' not valid
   }
}

J0066 - 'this' can only be used in non-static methods

The compiler detected use of the keyword this within a class (or static) method. Class methods are not passed implicit this references. As such, they cannot reference instance (non-static) variables or methods.

The following sample illustrates this error.

public class Simple {

   int x;

   public static void method1() {

      this.x = 12; // error: 'this' instance specific
   }
}

J0067 - Cannot convert 'identifier' to 'identifier'

The compiler detected a variable type used out of its correct context. As such, the compiler could not implicitly convert the result to anything meaningful. Convert the value you are attempting to use to something the method or field definition requires, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int i = 10;

      if (i--) {
         // error: conditional needs expression
         // or boolean variable
      }
   }
}

J0068 - Cannot implicitly convert 'identifier' to 'identifier'

The compiler could not convert the specified variable without an explicit typecast. The error most likely occurs when a numeric field is assigned to a data type that is not numeric. Use a typecast to convert the data type to the appropriate data type, and then compile again.

The following sample illustrates this error.

public class Simple {

   int i = 10;

   public char method1() {

      return i; // error: expected type char
   }
}

J0069 - Cannot apply '.' operator to an operand of type 'identifier'

The compiler detected the '.' operator applied to an invalid type. This error most likely occurs when the length method is applied to an invalid type.

The following sample illustrates this error.

public class Simple {

   int i = 123;
   int j = i.length; // error: 'i' not an array

}

J0070 - Not used

This error message is currently not used.

J0071 - Not used

This error message is currently not used.

J0072 - 'identifier' is not a member of class 'identifier'

The compiler detected a method call, but the method remains undefined. This error most likely occurs when the method name is either misspelled or cannot be found within proper scope. This error may also occur when the method does not exist. Make sure that the member you are trying to reference exists in the specified class.

The following sample illustrates this error.

public class Simple {

   public static void main(String args[]) {

      System.out.printline("Hello");
      // error: 'printline' should be 'println'
   }
}

J0073 - Not used

This error message is currently not used.

J0074 - Operator cannot be applied to 'identifier' and 'identifier' values

The compiler detected an operator that cannot be correctly applied to the identifiers shown in the error message. This error most likely occurs when two fields are non-numeric and operators used for numbers are applied to the fields.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      String s1 = "one";
      String s2 = "two";
      String result;

      result = s1 * s2; // error: invalid operands
   }
}

J0075 - Invalid call

The compiler detected syntax for a method call, but the identifier does not represent a valid method name. This error most likely occurs when a method name is misspelled or contains characters that are not recognized as valid in Java naming conventions.

The following sample illustrates this error.

class Simple {

   int x = 1();
   //error: 1 is not a valid method name
}

J0076 - Too many arguments for method 'identifier'

The compiler detected a known method call, but the call contained more arguments than needed. Check the number of arguments for the method you are attempting to call, and remove any additional arguments from the call.

The following sample illustrates this error.

public class Simple {

   public void method1(int arg1) {

      // do something meaningful
   }

   public void method2() {

      method1(1, 2); // error: Too many arguments
   }

}

J0077 - Not enough arguments for method 'identifier'

The compiler detected a known method call, but the call contained fewer arguments than needed. This error most likely occurs when one or more arguments are accidentally omitted from the call.

The following sample illustrates this error.

public class Simple {

   public void method1(int arg1) {
      // do something meaningful
   }

   public void method2() {

      method1(); // error: Too few arguments
   }
}

J0078 - Class 'identifier' doesn't have a method that matches 'identifier'

The compiler identified a call to a known overloaded method within another class, but was unable to detect a matching method with the correct number of arguments. Make sure the overloaded method call has the correct number and type of arguments, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      // do something meaningful
   }

   public void method1(int arg1) {
      // do something meaningful
   }
}

class Simple2 {

   public void method1() {

      Simple s = new Simple();
      s.method1(1, 2, 3); // error: too many args
   }
}

J0079 - Ambiguity between 'identifier' and 'identifier'

The compiler could not distinguish the correct method to execute. This error most likely occurs when two overloaded methods have related argument lists and the method call cannot be differentiated between the two methods. Make sure your method call is not using a parameter that conflicts with another overloaded method. Another way to avoid this error is to change the argument lists of the two overloaded methods so that they have a different number of arguments or more uniquely defined parameter data types.

The following sample illustrates this error.

public class Simple {

   static void method1(Simple2 s2, Simple3 s3) {
      // do something meaningful
   }

   static void method1(Simple3 s3, Simple2 s2) {
      // do something meaningful
   }

   public static void main(String args[]) {

      Simple2 s2 = new Simple2();
      method1(s2, s2);
      // error: Ambiguity between Simple2 and Simple3
   }
}

class Simple2 extends Simple3 {
   // do something meaningful
}

class Simple3 {
   // do something meaningful
}

J0080 - Value for argument 'identifier' cannot be converted from 'identifier' in call to 'identifier'

The compiler detected a method argument that does not match the parameters specified in the method declaration. This error most likely occurs when a numeric field is passed as an argument to a method but the method requires a different numeric type. To pass different numeric types to arguments of a method, typecast the field being passed to method.

The following sample illustrates this error.

public class Simple {

   public void method1(int arg1) {
      // do something meaningful
   }

   public void method2() {

      float f = 1.0f;
      method1(f); // error: mismatched call types
   }
}

J0081 - Value for argument 'identifier' cannot be converted from 'identifier' in call to 'identifier'

The compiler detected a method call, but was unable to convert one of the arguments from the supplied type to the type shown in the method declaration. This error most likely occurs when a method is called with the arguments in the wrong order or the wrong method was called.

J0082 - Class 'identifier' doesn't have a constructor that matches 'identifier'

The compiler did not detect a constructor matching the call identified in the error. This error most likely occurs when a constructor is called with the wrong number of arguments. Check to make sure that the class has a constructor that matches the one you are attempting to call.

The following sample illustrates this error.

public class Simple {

   Simple(int arg1) {
      // do something meaningful
   }

   public static void main (String args[]) {

      Simple s = new Simple(12, 13);
      // error: too many arguments
   }
}

J0083 - 'super( )' or 'this( )' may only be called within a constructor

The compiler detected use of either the super() or this() keyword outside of a constructor. The super() keyword is used to call a superclass constructor, while the this() keyword is used to call one constructor from another. To reference methods in a base class, you must use the super keyword.

The following sample illustrates this error.

public class Simple {
   public void method1 () {
      super(); // error: 'super' cannot be called
   }
}

public class Simple{
   public method2(){
      super.method1(); //correct way to call a method of a superclass
   }
}

J0084 - Can't return a value from a 'void' method

The compiler detected an attempt to return a value from a method declared with a return type of void.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      return 1; // error: cannot return a value
   }
}

J0085 - Expected return value of type 'identifier'

The compiler detected the keyword return within the body of a method which was declared to return a specific type, but the return had no associated value. The return statement with no associated value will not return a default value and thus must be assigned a valid return value.

The following sample illustrates this error.

public class Simple {

   public int method1() {
      return; // error: must return int value
   }
}

J0086 - '[]' cannot be applied to a value of type 'identifier'

The compiler detected array brackets used with a non-array variable type. Change the field to be a valid array declaration if you wish to use the field as an array.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      int i = 0;
      int j, x;

      x = j[i]; // error: 'j' not declared as array
   }
}

J0087 - The 'goto' statement is not currently supported by Java

The keyword goto, while defined as a keyword, has not yet been implemented in the Java language.

J0088 - Not used

This error message is not currently used.

J0089 - Already had 'case: 'identifier'

The compiler identified two or more case statements with the same identifier or value occurring within the same switch statement.

The following sample illustrates this error.

public class Simple {

   public int method1(int arg1) {

      switch (arg1) {
         case 1:
            return (int) 1;
         case 2:
            return (int) 2;
         case 2: // error: duplicate of above
            return (int) 3;
         default:
            return (int) 0;
      }
   }
}

J0090 - Already had 'default'

The compiler identified two or more instances of the keyword default occurring within the same switch statement.

The following sample illustrates this error.

public class Simple {

   public int method1(int arg1) {

      switch (arg1) {
         case 1:
            return (int) 1;
         case 2:
            return (int) 2;
         default:
            return (int) 3;
         default: // error: duplicate of previous
            return (int) 0;
      }
   }
}

J0091 - 'case' outside of switch statement

The compiler identified the keyword case used outside the scope of a switch statement.

The following sample illustrates this error.

public class Simple {

   public int method1() {
      case 1: // error: no switch statement
         return 1;
   }
}

J0092 - Constant expression expected

The compiler has detected an expression that used a nonconstant value when a constant value was required. This error most likely occurs when a variable is used in a case statement. Check the expression and make sure that a constant value is being used.

The following sample illustrates this error.

public class Simple{
   int var1 = 10;
   int var2 = 20;
   public void method1(){
      switch(var1){
        case var2:
        //error: cannot use variable with case
      }
   }
}

J0093 - 'break' only allowed in loops and switch statements

The compiler detected the keyword break occurring outside the scope of a loop or switch statement.

J0094 - Label 'identifier' not found

The compiler detected a label name associated with one of the keywords continue or break, but could not find the label. This error most likely occurs when a label does not exist yet is being referenced by a break or continue statement. The error can also occur if the label is placed outside of the break or continue statement's scope. A label cannot reference labels in other classes or other source files. Check to make sure the break or continue statement can access a valid label, and then compile again.

The following example illustrates this error.

public class Simple{
   public int method1(){
      int y;
      for (int x = 0; x < 10; x++){
         y = x *2;
         if (x == 5)
            break test; //error 'test' is not defined as a label
      }
      return y;
   }
}

The following example illustrates the proper usage of a label when used with the break or continue statements:

public class Simple{
   public int method1(){
      int y;
      for (int x = 0; x < 10; x++){
         y = x *2;
         if (x == 5)
            break test; //error 'test' is not defined as a label
      }
      test:
      return y;
   }
}

J0095 - 'continue' only allowed in loop

The compiler detected attempted use of the keyword continue outside the scope of a loop.

J0096 - Class value expected

The compiler detected a synchronization block, but the synchronized modifier was applied to an invalid type. This error most likely occurs when an identifier other than a class object instance is used with the synchronized statement.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int i;

      synchronized (i);
      // error: 'i' must resolve to
      // class or array type
   }
}

J0097 - Class or array expected

The compiler detected the instanceof operator applied to a type that did not resolve to a class or array. The instanceof operator is used to determine if identifier is an instance of a specific class or array. Make sure the lvalue used with the instanceof operator references a class instance or array and the rvalue references a valid class name or array.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      Simple2 obj = new Simple2();

      if (obj instanceof int) // error: bad type
         ; // do something meaningful
   }
}

class Simple2 {
   // do something meaningful
}

J0098 - Attempt to access nonexistent member of 'identifier'

The compiler detected an array member that was specified, but could not identify it. This error most likely occurs when an attempt to reference the length method of an array is mistyped. This error can also occur when an attempt is made to call a method in an array of objects, but the call does not reference an element of the array.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int j[] = new int[10];
      int i = j.bogus;
      // error: 'bogus' not valid member
   }
}

J0099 - Not used

This error message is currently not used.

J0100 - Cannot throw 'identifier' - the type doesn't inherit from 'Throwable'

The compiler detected an object in a throw statement that was not derived from the class Throwable. This error most likely occurs when a throw statement uses a class that does not inherit from the Throwable class. Check to make sure that the exception class you are throwing is a valid exception class.

J0101 - The type 'identifier' does not inherit from 'Throwable'

The compiler detected an invalid class argument used as an argument in a catch declaration. When using a catch statement to handle exceptions, you must define it with a class derived from Throwable as a parameter. Make sure the class you defined for the catch statement is derived from Throwable, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      try {
         // do something meaningful
      } catch (String s) {
         // error: 'String' not a subclass
         // of 'Throwable'
      }
   }
}

J0102 - Handler for 'identifier' hidden by earlier handler for 'identifier'

The compiler detected an exception handler that will never be executed because an earlier handler would have already caught the exception. This error is most likely caused by putting catch statements in the wrong order.

The following sample illustrates this error.

class Simple {

   static
   {
      try
      {
      }
      catch (Exception e)
      {
      }
      catch (ArithmeticException e)
      {
      }
      // error: any exceptions this block
      // could have caught are already caught
      // by the first catch statement.
   }
}

J0103 - Cannot override final method 'identifier'

The compiler detected a class method attempting to override one of its base class methods, but the base class method was declared with the keyword final. Methods defined with the final modifier cannot be overridden by a derived class.

The following sample illustrates this error.

public class Simple extends Simple2 {

   public void method1() {
      // error: 'method1' final in superclass
   }
}

class Simple2 {

   public final void method1() {
      // do something meaningful
   }
}

J0104 - Unreachable statement or declaration

The compiler detected a statement or declaration that cannot be reached under any circumstances. This error most likely occurs when a return statement is called from a method and code is placed below the return statement. This error can also occur if a break statement is used in a loop without any flow control to allow code below it to be run.

The following sample illustrates this error.

class Simple {
   static
   {
      return;
      int x;
      //error: the declaration cannot be reached
   }
}

J0105 - Method 'identifier' must return a value

The compiler detected a method declaration, which included a return type other than void, but the keyword return was not found in the method body. This error most likely occurs when a method that returns a value is missing a valid return statement. This error can also occur if a return statement is called within a flow control block and cannot always accessed due to the logic of the method.

The following sample illustrates this error.

public class Simple {

   public int method1(int arg1) {

   } // error: expected an integer returned
}

J0106 - Class 'identifier' has a circular dependency

The compiler detected two or more classes directly or indirectly attempting to subclass each other. One class should act as the base class of the other.

The following sample illustrates this error.

public class Simple extends Simple2 {

   // error: extending 'Simple2'
}

class Simple2 extends Simple {

   // error: also extending 'Simple'
}

J0107 - Missing array dimension

The compiler detected the initialization of an array, but failed to detect a valid array dimension. This error most likely occurs when an array is defined but one of the dimensions of the array is not defined. To use an array, all dimensions must be defined.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int [][] i = new int[][12];
      // error: missing first array dimension
   }
}

J0108 - Cannot 'new' an instance of type 'identifier'

The compiler detected an attempt to instantiate a data type that does not require use of the keyword new. This error most likely occurs when an attempt is made to use the new keyword with an intrinsic data type and the declaration is not an array. Make sure your member declaration does not use the new keyword unless it is a class object or array declaration.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      int i = new int(5);
      // error: cannot use 'new' on 'int' types
   }
}

J0109 - Cannot 'new' an instance of abstract class 'identifier'

The compiler detected an attempt to instantiate a class object declared as abstract. A class declared as abstract cannot be instantiated and exists only as a base class for other classes to derive from.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      Simple2 s2Object = new Simple2();
      // error: class 'Simple2' declared as abstract
   }
}

abstract class Simple2 {
   // do something meaningful
}

J0110 - Cannot 'new' an interface 'identifier'

The compiler detected an attempt to instantiate an interface object declared as abstract. Note that interfaces are abstract by default, regardless whether the keyword abstract is used in their declaration.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      Simple2 s2Object = new Simple2();
      // error: interface Simple2 is abstract
   }
}

interface Simple2 {
   // do something meaningful
}

J0111 - Invalid use of array initializer

The compiler detected an attempt to initialize an array, but the initialization statement was not syntactically correct. Arrays can be initialized at declaration with an initial set of values. The compiler detected that the syntax of the initialization was incorrect. This error most likely occurs when trying to initialize a multidimension array with the incorrect number or positioning of braces and commas. Check the syntax of your array initialization, and then compile again.

J0112 - Cannot assign final variable 'identifier'

The compiler detected an attempt to change the value of a variable declared as final. A field declared as final cannot be assigned a value once it has been initialized with a value either at declaration or in an initializer block.

The following sample illustrates this error.

public class Simple {
   private final int i = 3;

   public void method1(int arg1) {
      i = arg1;
      // error: variable 'i' declared final
   }
}

J0113 - Call to constructor must be first in constructor

The compiler detected a constructor called from within the body of a second constructor, but the constructor call was not placed at the beginning of the second constructor body. In a constructor, calls to another constructor must be the first line of code in the constructor's body. Move the constructor call to the top, and then compile again.

The following sample illustrates this error.

public class Simple {

   int i, j;
   Simple () {

      i = 0;
   }

   Simple(int arg1) {

      j = arg1;
      this(); // error: call to Simple() must be first
   }
}

J0114 - Cannot reference 'this' in constructor call

The compiler detected a reference to this in a constructor. The this statement can only be used in a constructor to access methods and fields of the constructor's class. Usage of this(this) or super(this) in a constructor will cause this error to occur because the instance of the class has not yet been created, and thus cannot be passed to another constructor.

The following sample illustrates this error.

class SuperSimple {

   SuperSimple(Object o) { }
}

public class Simple extends SuperSimple {

   Simple()
   {
      super(this);
      //error: cannot refer to this in constructor
   }
}

J0115 - Cannot call constructor recursively

The compiler detected a recursive constructor call. This error most likely occurs when a constructor has a call to the same constructor. This error can also occur if one constructor calls a second constructor and the second constructor has a call back to the first constructor.

The following sample illustrates this error.

public class Simple {

   Simple (int arg1) {

      this(1);
      // error: constructor calling itself
   }
}

J0116 - Variable 'identifier' may be used before initialization

The compiler detected an attempt to use a variable before it was properly initialized. To use a variable in an assignment or expression, you need to assign a value to it. Initialize the variable in a constructor or field initializer, and then compile again.

The following sample illustrates this error.

public class Simple {

   static
   {
      int i;
      int j = i;
      // error: 'i' not yet initialized

   }
}

J0117 - Cannot declare a class to be 'private'

The compiler detected use of the modifier private in an outer class declaration. This modifier may only be used with fields, methods, and inner class declarations.

The following sample illustrates this error.

private class Simple {

   // error: a class cannot be 'private'

}

J0118 - Not used

This error message is currently not used.

J0119 - Not used

This error message is currently not used.

J0120 - Divide or mod by zero

The compiler detected a division by zero error in code.

The following sample illustrates this error.

public class Simple {

   final int x = 0;
   int y = 1 % x;
   //error: x cannot be 0

}

J0121 - Unable to recover from previous error(s)

The compiler encountered a serious error and could not continue processing the file reliably. Try fixing whatever errors are already flagged, and then compile again.

J0122 - Exception 'identifier' not caught or declared by 'identifier'

The compiler detected an exception that was thrown but never caught within the exception class. This error most likely occurs when a method calls another method with a declaration to throw an exception. For a method to call another method that throws an exception, the method must either be declared to throw the exception or handle the error using a try catch combination.

The following sample illustrates this error.

class SimpleException extends Exception {
   // do something meaningful
}

class Simple {

   void method1() throws SimpleException { }
   void method2() { method1(); }
   // error: exception not declared for method2
}

J0123 - Multiple inheritance of classes is not supported

The compiler detected a class attempting to apply the keyword extends to more than one base class. This is defined as multiple inheritance in other languages and is not supported in Java.

The following sample illustrates this error.

public class Simple extends BaseClass1, BaseClass2 {
   // error: Multiple inheritance not supported in Java
}

class BaseClass1 {

   // do something meaningful
}

class BaseClass2 {

   // do something meaningful
}

J0124 - Operator cannot be applied to 'identifier' values

The compiler detected an operator being applied to a type it cannot be used with. Make sure the operation you are attempting is valid for the type of variable or object, and then compile again.

The following sample illustrates this error.

public class Simple {

   void method1(boolean b) {

      b++;
      // error: post increment operator cannot
      // be applied to boolean variables
   }
}

J0125 - 'finally' without 'try'

The compiler detected a finally block but did not find a corresponding try statement. A finally block is used to execute code after a try statement and regardless of the results of the try statement.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      finally {
         // error: missing corresponding 'try'
      }
   }
}

J0126 - 'catch' without 'try'

The compiler detected a catch block but did not find a corresponding try statement. To use a catch block you must have a try statement preceding it. Make sure you have a valid try statement, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      catch {
         // error: missing corresponding 'try'
      }
   }
}

J0127 - 'else' without 'if'

The compiler detected the keyword else, but did not find a corresponding if statement. This error most likely occurs when there are scoping issues with regards to the placement of an else statement. This error can also occur if an else statement's corresponding if statement is missing.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      else // error: no corresponding 'if'
         ;
   }
}

J0128 - Cannot declare an interface to be 'final'

The compiler detected an interface declared with the keyword final. Interfaces cannot be defined as final and thus cannot use the final modifier. Remove the final keyword from the interface's declaration, and then compile again.

The following sample illustrates this error.

final interface Simple {

   // error: 'final' only applies to
   // classes, methods or variables

}

J0129 - Cannot declare a class to be 'identifier' and 'identifier'

The compiler detected a class declared with modifiers that cannot be combined. Make sure that the modifiers you have applied to the class do not conflict with each other, and then make appropriate changes.

The following sample illustrates this error.

public abstract final class Simple {

   // error: 'abstract' and 'final' cannot
   // be used together in a class declaration

}

J0130 - Cannot declare an interface method to be 'native', 'static', 'synchronized' or 'final'

The compiler detected one of the keywords previously shown used in the declaration of an interface method. Because an interface method does not have implementation code, it cannot be declared as native, static, synchronized, or final.

The following sample illustrates this error.

interface Simple {

   public final void method1();
   // error: 'method1' cannot be declared
   // as final in an interface
}

J0131 - Cannot declare a method to be 'identifier' and 'identifier'

The compiler detected the use of two or more incompatible modifiers in the declaration of a method. This error most likely occurs when a method has been defined with two access modifiers such as public and private. Make sure the modifiers for the method do not conflict with each other, and then make appropriate changes.

The following sample illustrates this error.

public class Simple {

   public private void method1() {

      // error: modifiers 'public' and 'private'
      // cannot be combined in a declaration
   }
}

J0132 - Cannot declare a field to be 'identifier' and 'identifier'

The compiler detected the use of two or more incompatible modifiers in the declaration of a variable. This error most likely occurs when a field has been defined with two access modifiers, such as public and private. Make sure the modifiers for the field do not conflict with each other, and then make appropriate changes.

The following sample illustrates this error.

public class Simple {

   public private int i;
   // error: modifiers 'public' and 'private'
   // cannot be combined in a declaration
}

J0133 - Constructors cannot be declared 'native', 'abstract', 'static', 'synchronized', or 'final'

The compiler detected the use of one of the modifiers previously shown in the declaration of a constructor. Make sure that the constructor is not defined with any of the modifiers mentioned in the error message, and then compile again.

The following sample illustrates this error.

public class Simple {

   final Simple() {}
   // error: constructors cannot be 'final'

}

J0134 - Interfaces cannot have constructors

The compiler detected an interface containing a constructor declaration. Because an interface cannot be instantiated, constructors are not allowed to be defined for an interface. If you are defining a method with the same name as the method, make sure that it has appropriate modifiers to differentiate it from a constructor declaration.

The following sample illustrates this error.

interface Simple {

   Simple();
   // error: interfaces cannot
   // declare constructors

}

J0135 - Interface data members cannot be declared 'transient', 'volatile', 'private', or 'protected'

The compiler detected one of the modifiers previously shown used in the declaration of a interface member variable.

The following sample illustrates this error.

interface Simple {

   volatile int i = 1;
   // error: 'volatile'cannot be used.

}

J0136 - Public class 'identifier' should not be defined in 'identifier'

The compiler detected more than one class declared with the modifier public in a source file. Remove the public access modifier from the other classes, and make sure that the class that will be exposed through the class file is declared as public. You can also move classes that need to remain declared as public to their own source file.

The following sample illustrates this error.

public class Simple {

   // do something meaningful

}

public class Errorclass {

   // error: only one class may be defined as
   // 'public' within the same source file

}

J0137 - Not used

This error message is currently not used.

J0138 - Interface cannot have static initializer

The compiler detected a static initializer within an interface. Because an interface does not get instantiated, initializers cannot be defined in an interface. To set the values of interface fields, initialize them at the time of declaration.

The following sample illustrates this error.

interface Simple {

   static {
      // error: static initializers cannot
      // be used in interfaces
   }

}

J0139 - Invalid label

The compiler detected an invalid label. Labels must start with an alphanumeric character. Change the label, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

   123:
   // error: label cannot
   // begin with alphanumeric

   return;

   }
}

J0140 - Cannot override static method 'identifier'

The compiler detected an attempt to override a static method from within a subclass. A method that has been declared as static cannot be overridden.

The following sample illustrates this error.

public class Simple {

   static void method1() {}
}

class SimpleSubclass extends Simple {

   void method1() {}
   // error: cannot override
   // static method
}

J0141 - Argument cannot have type 'void'

The compiler detected a method argument defined as type void. The void type can only be used for method return values to declare a method has no return value. Change the data type of the argument, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1(void i) {
      // error: type void can only
      // be used as a return value
   }
}

J0142 - Cannot make static call to abstract method 'identifier'

The compiler detected an attempt to directly call an abstract method. Abstract methods are defined to provide a definition of a method to be implemented by subclasses and thus abstract methods do not have implementation code. Because of this lack of implementation in an abstract method, calling an abstract method using the super keyword is invalid.

The following sample illustrates this error.

abstract class Simple {

   abstract int method1();
}

class SimpleSubclass extends Simple {

   int method1() {

      return super.method1();
      // error: 'method1' must be
      // implemented instead
   }
}

J0143 - Cannot throw exception 'identifier' from static initializer

The compiler detected an attempt to throw an exception from within a static initializer. This error most likely occurs when a throw statement is called or an initialization of a static class instance occurs within a static initializer. To capture exceptions from static class instance initializations in a static initializer, use a try and catch block combination.

The following sample illustrates this error.

public class Simple {

   static {
      ThrowClass TClass = new ThrowClass();
      // error: cannot throw exceptions
      // within static initializers
   }
}

class ThrowClass {

   ThrowClass() throws Exception{}

}

J0144 - Cannot find definition for interface 'identifier'

The compiler could not locate a definition for the named interface. This error most likely occurs when an implemented interface is either missing or misspelled. Verify the location and name of the interface you are implementing, and then compile again.

The following sample illustrates this error.

public class Simple implements Bogus {
   // error: the interface 'Bogus' does not exist

}

J0145 - Output directory too long: 'identifier'

The output directory exceeded 228 characters in length. Try shortening the length of the output directory path, and then compile again.

J0146 - Cannot create output directory 'identifier'

The output directory could not be created. This error most likely occurs when you do not have write permission on the specified drive.

J0147 - Cannot access private member 'identifier' in class 'identifier' from 'identifier'

The compiler detected an invalid attempt to access a private member contained within another class. Private class members are only accessible from within the member's class.

The following sample illustrates this error.

class AccessClass {
   private int i = 0;
}

public class Simple {

   public void method1() {

      AccessClass ac = new AccessClass();

      ac.i = 1;
      // error: cannot access 'i'
   }
}

J0148 - Cannot reference instance method 'identifier' before superclass constructor has been called

The compiler detected an attempt to reference an instance method before the superclass constructor was called. This error most likely occurs when a base class method is called from within a subclass's constructor using the super() method. This error can also occur if the subclass calls its own methods from the constructor using the this() method. Because instances of the subclass and base class have not been instantiated at the time the constructor is called, this error occurs. To avoid this situation, use the super statement to call a base class method, and use the this statement to call a subclass method.

The following sample illustrates this error.

abstract class Simple {

   Simple(int i) {}

   int method1() {

      return 0;
   }
}

class SimpleSubclass extends Simple {

   SimpleSubclass() {

      super(method1());
      // error: constructor must be called first
   }
}

J0149 - Not used

This error message is currently not used.

J0150 - Cannot have repeated interface 'identifier'

The compiler detected an interface name being repeated within a class declaration. This error is most likely caused when a class implements a large number of interfaces and an interface has a duplicate entry in the implements list. Check to make sure you do not have a duplicate interface entry, and then compile again.

J0151 - Variable 'identifier' is already defined in this method

The compiler detected two variables with the same name that are defined twice within the same scope of a method. Make sure that a variable has not been defined twice in the same scope, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {

      int i = 1;
      int i = 0;
      // error: 'i' defined twice within
      // the same scope

   }
}

J0152 - Ambiguous reference to 'identifier' in interfaces 'identifier' and 'identifier'

The compiler detected an ambiguous reference to an identifier. The identifier may have been declared in two or more interfaces, and the compiler could not determine which reference to use. Make sure that you do not have two interfaces with the same field defined.

The following sample illustrates this error.

interface Interface1 {
    final int i = 0;
}

interface Interface2 {
    final int i = 1;
}

public class Simple implements Interface1, Interface2 {

   int method1() {
      return i; //Error, the class implements two
                //interfaces that define 'i' separately.
   }
}

J0153 - Not used

This error message is currently not used.

J0154 - Not used

This error message is currently not used.

J0155 - Not used

This error message is currently not used.

J0156 - Not used

This error message is currently not used.

J0157 - Not used

This error message is currently not used.

J0158 - Class 'identifier' already defined

The compiler detected two or more classes defined with the same name. Make sure that you do not have the class defined more than once in the same source file. This error can also occur if a class is duplicated by an imported class. Rename one of the classes or remove the duplicate instance, and then compile again.

The following sample illustrates this error.

public class Simple {
   // do something meaningful
}

class Simple {
   // error: class 'Simple' already defined
}

J0159 - '@' must be followed by the response filename

The compiler detected the @ character on the JVC command line, but did not detect a valid response filename immediately following it. Supply the response filename, and then compile again.

J0160 - response file 'identifier' could not be opened

The compiler could not open the specified response file. This error most likely occurs when the response file name is misspelled or the file does not exist.

J0161 - Cannot open source file: 'identifier'

The source file specified in the error message could not be opened. This error most likely occurs when either the filename specified is misspelled or the file does not exist. Check the location of the specified source file, and then compile again.

J0162 - Failed to initialize compiler - maybe you didn't set the class path?

The compiler failed to properly initialize. Check to ensure the CLASSPATH environment variable is set properly, and then compile again.

J0163 - Array 'identifier' missing array index

The compiler detected access to an array type, but the index value was missing. To access an element of an array, you must provide a valid integer index for the array.

The following sample illustrates this error.

public class Simple {

   int j[] = {1, 2, 3};

   void method1() {
      j[] = 0;
      // error: 'j' missing index value
   }
}

J0164 - Ambiguous import of class 'identifier' from more than one package

The compiler detected two or more import statements attempting to import identical class names from different packages. This error most likely occurs when two packages contain duplicate classes and both packages are imported into the same source file. Check the packages imported into the source file for duplicate classes. Remove the duplicate class from one of the packages or remove one of the import statements from the source file.

J0165 - Cannot throw exception 'identifier' from method 'identifier' -- it is not a subclass of any exceptions thrown from overloaded method 'identifier'

The compiler detected an override method attempting to throw more exceptions than the method it overrides. In Java, an override method may not be declared to throw more exceptions than the overridden method. Either change the exception thrown to one that the base class throws, or change the base class declaration to throw the exception type that the subclass needs to throw.

The following sample illustrates this error.

class ExceptionA extends Exception (
   // do something meaningful
}

class ExceptionB extends Exception {
   // do something meaningful
}

class AnotherClass {

   public void method1() throws ExceptionA {
      // do something meaningful
   }
}

public class Simple extends AnotherClass {

   public void method1() throws ExceptionA, ExceptionB {
      // error: cannot throw greater than
      // one exception here
   }
}

J0166 - Cannot access member 'identifier' in class 'identifier' from 'identifier' -- it is in a different package

The compiler detected an invalid attempt to reference a member variable defined within a different package. This error most likely occurs when an attempt is made to access a protected member defined within another package.

J0167 - Cannot override non-static method 'identifier' with static method 'identifier'

The compiler detected an attempt to override a superclass method with a subclass method declared with the modifier static. When a method is overridden in a subclass, the method cannot raise or lower the access level of the method or apply the static modifier. Remove the static modifier from the overridden method declaration, and then compile again.

The following sample illustrates this error.

public class Simple {

   public void method1() {
      // do something meaningful
   }
}

class Simple2 extends Simple {

   static public void method1() {
      // error: overriding superclass 'method1'
      // with a static method is not valid
   }
}

J0168 - The declaration of an abstract method must appear within an abstract class

The compiler detected a method declared with the modifier abstract within a class which was not defined as abstract. This error most likely occurs when a class was intended to be abstract but is missing the abstract modifier in the class declaration. Either change the class so it is declared as abstract or remove the modifier from the methods defined in the class.

The following sample illustrates this error.

public class Simple {

   abstract void method1();
      // error: class must also be abstract
}

J0169 - Cannot access 'identifier' -- only public classes and interfaces in other packages can be accessed

The compiler detected an attempt to access a non-public class or interface contained within another package. Only classes or interfaces defined with the modifier public can be accessed in other packages. Check the access level of the class or interface you are accessing in the other package and ensure that it is public.

J0170 - Cannot load predefined class 'identifier' -- is CLASSPATH set correctly?

The compiler attempted to load a predefined class, but was unable to find the appropriate file. This error most likely occurs when the CLASSPATH variable has not been set correctly. Check to ensure the CLASSPATH is set properly, and then compile again.

J0171 - Not used

This error message is currently not used.

J0172 - Not used

This error message is currently not used.

J0173 - Found class 'identifier' in package 'identifier' rather than package 'identifier'

The compiler found the specified class, but the class was not defined as a member of the correct package. This error most likely occurs when an import statement includes an incorrect package identifier for the class.

J0174 - Not used

This error message is currently not used.

J0175 - Cannot invoke method on 'null' literal

The compiler detected an attempt to call a method from the null keyword. Null is not a class object and provides no methods.

J0176 - Duplicate label 'identifier' nested inside another label with same name

The compiler detected a nested label that was the same as another label. Rename the label to something different then change all break and continue statements that reference the label, and then compile again.

The following sample illustrates this error.

public class Simple{
   void method1(){
      outsideLoop:
      for (int i=0;i<10;i++)
      {
         outsideLoop:  //error: duplicate label
         for (int x=0;x<10;x++)
         {
            break outsideLoop;
         }
         break outsideLoop;
      }
   }
}

J0177 - Not used

This error message is currently not used.

J0178 - Not used

This error message is currently not used.

J0179 - Not used

This error message is currently not used.

J0180 - Not used

This error message is currently not used.

J0181 - Not used

This error message is currently not used.

J0182 - Not used

This error message is currently not used.

J0183 - Not used

This error message is currently not used.

J0184 - Not used

This error message is currently not used.

J0185 - Not used

This error message is currently not used.

J0186 - Not used

This error message is currently not used.

J0187 - Not used

This error message is currently not used.

J0188 - Not used

This error message is currently not used.

J0189 - 'return' not allowed in a static initializer or instance initializer

A return statement was found in a static initializer. Initializers, like constructors, cannot return a value. Remove the return statement, and then compile again.

The following sample illustrates this error.

public class Simple{

   static int var1;

   static{

   var1 = 0;
   return; // Error, static initializer cannot use the
           // return statement.

   }
}

J0190 - Not used

This error message is currently not used.

J0191 - Expected '.class'

The compiler detected usage of an intrinsic type name in an assignment statement but did not find .class after the name. This error most often occurs when the .class keyword was omitted. Make the appropriate changes to the statement, and then compile again.

The following sample illustrates this error.

public class Simple{
   public static void main (String args[]){
      Class x = int;//error: missing '.class'
   }
}

J0192 - '.class' on intrinsic type requires Java 1.1 compatible class libraries

The compiler has detected usage of .class with an intrinsic data type, but either the Microsoft Win 32 VM for Java or the Java class libraries are based on Java 1.0. Make sure that your class libraries and Java VM are the Java 1.1 versions, and then compile again.

J0193 - Cannot have an array of type 'void'

An attempt to define an array of type void was found by the compiler. The void data type is for use with methods to declare the method has no return value and thus cannot be used as an array.

J0194 - class or interface cannot be declared 'volatile', 'native', 'transient', or 'synchronized'

The compiler detected that an inner class has been declared with one of the above mentioned modifiers. Inner classes can only use the private, public, protected, and static modifiers.

The following example illustrates this error.

public class Simple{
   //Do something here
   volatile class InnerClass{
      /*error: like outer class, inner classes cannot be defined as
               volatile */
   }
}

J0195 - Cannot declare 'identifier' as 'static' in inner class 'identifier'

The compiler detected an attempt to declare a variable or method as static from within an inner class. Unlike regular class declarations, inner classes do not support static members unless the inner class has been declared static. This error can also occur if an interface was defined within an inner class.

The following example illustrates this error.

public class Simple{

   //Do something meaningful here

   class InnerClass{

   static int var1; /* error: cannot declare static
                              members in inner class */
   }
}

J0196 - Nested class 'identifier' cannot have the same name as any of its enclosing classes

The specified inner class has the same name as one of the classes that it is nested under. Make sure you have not duplicated the name of a class that your inner class is nested in.

The following example illustrates this error.

public class Simple{

   // Do something meaningful here
   class InnerClass{
      //Do something meaningful here
        class Simple{
            //error: inner class has same name as a parent class
        }
   }
}

J0197 - Cannot declare interface in inner class 'identifier'.

The compiler detected an attempt to declare an interface inside an inner class. Inner class definitions do not support interfaces declared within them.

The following example illustrates this error.

public class Simple{
   //Do something meaningful here
   class InnerClass{
   //Do something meaningful here
      interface MyInterface{
         /*error: interfaces cannot be declared
                  inside inner classes */
      }
   }
}

J0198 - An enclosing instance of type 'identifier' is required

The compiler detected that an inner class definition has tried to reference something outside of its scope. Examples of when this can occur are:

  • A static inner class definition referenced one of the parent class's variables. Because the inner class is declared static, it cannot reference any members of the parent class without an instance of the parent class defined.
  • An inner class tried to reference a class that was not its outer class using the this keyword with the classes name preceding it. Since the referenced class it not the inner class's parent class, an instance cannot be implied.

The following example illustrates this error.

//This example illustrates the first error situation
public class Simple{
   int x = 10;
   static class InnerClass{
      public void method1(){
         int y = x; /*error: instance variable needed
                             to reference parent
                             variables. */
      }
   }
}

//This example illustrates the second error situation
class A{
   int x;
}
class B{
   //Do something meaningful here
   class InnerClass{
      void method1(){
         int y = A.this.x;
         /*error: no instance of A defined. Cannot use
           the <classname.this.variable> syntax here.*/
      }
   }
}

J0199 - Call of 'this()' cannot be qualified

The compiler detected that an inner class's constructor attempted to call a constructor from its outer class using the class name and this(). Inner classes cannot call their outer class's constructors.

The following example illustrates this error.

public class Simple{
   int x;
   Simple(int x){
      this.x = x;
   }
   class InnerClass{
      InnerClass(){
         Simple.this(10);
         //error: cannot call outer class constructor
      }
   }
}

J0200 - 'this' must be qualified with a class name

The compiler detected that an attempt was made in an inner class to reference an outer class member using the this keyword with a name other than an outer class's name. Only the name of the outer class can be used from an inner class to reference members of the outer class.

The following example illustrates this error.

public class Simple{
   int x;
   class InnerClass{
      void method1(){
         int j = x.this;
         /*error: only a class name can be used with
         this to reference outer class */
      }
   }
}

J0201 - 'super' cannot be qualified except as a superclass constructor call

The compiler detected the usage of the super keyword with an instance of the superclass preceding it to access a field or method of the superclass. Using an instance of a superclass along with the keyword super is limited to referencing a superclass constructor when the superclass has inner classes defined.

J0202 - 'super()' cannot be qualified; superclass 'identifier' is not an inner class

The compiler has detected a call to a superclass constructor using an instance of the superclass but the superclass is not an inner class. The usage of an instance of a superclass with the super keyword is only valid when the superclass is an inner class.

The following example illustrates this error.

class Simple{
   //Do something meaningful here
}

class NotSimple extends Simple
{
   NotSimple(Simple smp){
      smp.super();
      /*error: cannot call 'super' with instance when
        superclass does not contain inner classes*/
   }
}

J0203 - Cannot access protected member 'identifier' in class 'identifier' from class 'identifier'

The compiler has detected an attempt to access a protected member from a class in a different package. Classes that reside in separate packages cannot refer to protected members unless you are subclassing a class in the other package.

J0204 - Cannot access protected member 'identifier' in class 'identifier' through a qualifier of type 'identifier'

The compiler detected that a class in one package that is extending a class in another package, attempted to access a protected member of the base class using an instance of the base class. This error most likely occurs when a class attempts to access members of its base class through an instance other than this or super.

J0205 - Cannot use non-final local variable 'identifier' from a different method

The compiler detected that a local variable, which was not declared as final, was referenced in a method. This error can occur if an inner class is defined in a method declaration and the inner class attempts to reference a parameter or local variable passed to the method.

The following example illustrates this error.

public class Simple{
   void method1(int var1){
      class InnerClass{
         boolean getVar1(){
           return(var1 == 1);
           /*error cannot reference local variable of
                   method from within inner class. */
         }
      }
   }
}

J0206 - Cannot assign a second value to blank final variable 'identifier'

The compiler detected an attempt to assign a value to a final variable more than once. This error most likely occurs when a blank final variable is initialized more than once in constructor or initializer. Check for duplicate initializations of the final variable mentioned in the error message, and then compile again.

J0207 - Cannot assign blank final variable 'identifier' in a loop

The compiler detected that a final variable was assigned a value from within the scope of a program control loop. A final variable can only be assigned a value once and thus cannot be initialized within a loop. Move the initialization of the final variable specified in the error message outside of the loop and ensure that it is initialized only once.

The following example illustrates this error.

public class Simple{
   final int x;

   public Simple(){
      for (int z=0;z<10;z++){
         x = z; /*error: cannot assign final variable
                  in loop */
      }
   }
}

J0208 - Constructor or instance initializer must assign a value to blank final variable 'identifier'

The compiler detected that a final variable was declared but never assigned a value in either an initializer or constructor. For a variable to be properly declared final, it must be assigned a value.

J0209 - Expected '='

The compiler detected that an "=" was missing from a comment tag (for example @com, @security, @dll) attribute. This error most often occurs when an equal sign is missing from an attribute in a comment tag declaration. This error could also occur if another symbol or character obscures the "=" sign from being evaluated by the compiler. Check to make sure all comment tag attributes have proper "=" signs applied, and then compile again.

The following example illustrates this error.

/**@com.interface(iid 31415926-5358-9793-2384-612345678901)*/
//error: missing equal sign in 'iid' parameter
interface Itest{
   //Do something meaningful here
}

J0210 - Expected '.'

The compiler detected that the specified comment tag's declaration (for example @com) is missing a period (.) after the comment tag. This error can also occur if another symbol or character obscures the period symbol from being evaluated by the compiler. Check to make sure your comment tag declaration contains a period after the comment tag, and then compile again.

The following example illustrates this error.

/**@com class*/
//error: missing '.' from @com statement

public class Simple{
   //Do something meaningful here
}

J0211 - Not used

This error message is currently not used.

J0212 - Not used

This error message is currently not used.

J0213 - Not used

This error message is currently not used.

J0214 - Invalid GUID specified

The compiler detected that an @com attribute that uses a GUID was incorrect. This can be caused by a syntax error in entering the GUID. Check the syntax for the GUID, and then compile again.

J0215 - Syntax error in @com declaration

A syntax error was found in the specified @com declaration. This is most often caused by incorrectly typing the declaration. Check the syntax of the @com declaration, and then compile again.

J0216 - @com attribute 'identifier' on 'identifier' is illegal in this context

The compiler has detected that a value assigned to an attribute within an @com declaration is illegal. This error most often occurs when an attribute is specified but usage of the attribute requires that other specific attributes be specified. This error can also occur if an attribute is specified in the wrong location within an @com declaration. The following list illustrates some examples of when this can occur.

  • The @com.parameter attribute iid can only be specified if the attribute type has a value of either "OBJECT" or "DISPATCH".
  • The @com.parameter attribute size can only be specified if the type attribute is specified as either "ARRAY", "STRUCT", "SYSFIXEDSTRING", or "FIXEDARRAY".
  • The @com.method attribute name2 can only be specified if the method is declared within an @com.interface declaration that has its type attribute equal to either dual or dispatch.
  • The @com.parameter attribute name cannot be specified as the last attribute in an @com.parameter declaration.

J0217 - @com attribute 'identifier' was not specified for 'identifier' but is required in this context

The compiler has detected an attribute for the @com declaration shown in the error is missing, and is required for this type of declaration. Each type of @com declaration has attributes that are required. Check the documentation on @com for more details on what attributes are required for the @com declaration that is listed in the error message.

The following example illustrates this error.

/**@com.class() */
//error: must specify iid for @com.class
public class Simple{
   //Do something here
}

J0218 - @com attribute 'identifier' on 'identifier' has an invalid value

The compiler has detected that the value specified in the error message is either not the correct type for the attribute specified in the error or is outside the valid ranges for the error. Check the value assigned to the specified attribute, and then compile again.

J0219 - An @com attribute cannot be placed on member 'identifier' unless the containing class also has an @com attribute

The compiler has detected that an @com declaration was placed on a member of a class or interface but the class or interface was not declared with an @com declaration. Check to make sure the class or interface that contains the method specified in the error has a valid @com declaration defined.

The following example illustrates this error.

interface Simple{
   /**@com.method(dispid=777) */
   public void method1();
   /*error: interface does not have an @com comment tag
            assigned*/
}

J0220 - An @com attribute cannot be placed on static member 'identifier'

The compiler detected that an @com declaration was placed on a static member of a class. Static members cannot be exposed through COM. Remove the static keyword from the method or field, and then compile again.

J0221 - The @com attribute on member 'identifier' cannot be used in this kind of class or interface

The compiler has detected that an @com declaration was placed on a member of a class or method but because of the type of @com declaration used with the class or interface, it is not allowed. This error can occur in the following situations:

  • Using an @com.structmap declaration on a member of a class or interface that has the @com.class or @com.interface declaration applied.
  • Using an @com.method declaration on a member of a class that has the @com.struct declaration applied.

The following example illustrates this error.

/**@com.struct()*/
class Simple{
   /**@com.method(dispid=777)*/
   public native void method1();
   /*error: cannot use @com.method inside of
            @com.struct*/
}

J0222 - @com attribute cannot be placed on method 'identifier'-- it must be declared 'native' or be in an interface

The compiler has detected that a method was specified with an @com.method or @com.parameters declaration but the method was not declared with the native modifier or declared in an interface definition. For methods to be exposed through a COM interface, they must be either declared native from within a class declaration or be declared in an interface declaration.

J0223 - The @com.parameters declaration on member 'identifier' has the wrong number of parameters

The compiler has detected that the @com.parameters declaration, specified in the error message, has a different number of parameters than the method it is exposing through COM. Make sure that both the method's declaration and the @com.parameters declaration have the correct number of parameters, and then compile again.

The following example illustrates this error.

/**@com.interface(iid=31415926-5358-9793-2384-612345678910)*/
interface Itest{
   /** @com.method(dispid=306)
       @com.parameters([type=BOOLEAN] var1, var2, var3)
   */
   public void method1(boolean var1, int var2);
   /*error: extra parameter added to com.parameters
            declaration */
}

J0224 - 'return' must be the last item in an @com.parameters declaration

When declaring @com.parameters for a method, the return parameter must be the last parameter in the list. The compiler has detected the return parameter in a different position within the parameter list. Check the location of the return parameter in the @com.paramters declaration specified in the error message, make appropriate changes, and then compile again.

J0225 - An @com.'identifier' declaration is illegal for this kind of item

The compiler detected that an @com declaration was defined for the wrong type of item. This error most likely occurs as a result of a change to your code but not to the syntax or placement of an @com declaration. Make sure the proper @com declaration is used on the specified item in your code.

The following example illustrates this error.

/**@com.interface(iid=31415926-5358-9793-2384-612345678901,dual)*/
interface Itest{
   /**@com.struct()*/
   public int method1();
   //error: wrong type of @com attribute applied
}

J0226 - The @com declared type of 'identifier' is illegal for a dispatch or a dual interface

The compiler detected that an @com interface declaration, declared as either a dual or dispatch interface, has a member that contains an @com.parameters declaration with an incorrect type. Certain @com.parameters types are not allowed when the interface they are defined in is declared as either dual or dispatch interface. The following list shows which values are invalid for type.

  • FIXEDARRAY
  • SYSFIXEDSTRING
  • I8
  • U8
  • STRUCT
  • CUSTOM, CUSTOMBYREF/CUSTOMBYVAL
  • PTR (except PTR to VARIANT)
  • Arrays of any of the previously listed values.

J0227 - It is impossible for an expression of type 'identifier' to be an instance of 'identifier'

The compiler has detected that a comparison of two classes using the instanceof operator could never be instances of each other. To use the instanceof operator correctly, you must be comparing classes that have some common class lineage. Either change the expression containing the instanceof operator so that it uses a related class and instance for its comparison, or remove the expression, and then compile again.

The following example illustrates this error.

class Simple1{
   //do something meaningful here
}

class Simple2{
   //do something meaningful here
}

class CompClasses{
   Simple1 x = new Simple1();
   public static void main(String args[]){

   if(smp.x instanceof Simple2){
      /*error: nonrelated classes cannot be instances of each other*/
   }
}

J0228 - Syntax error in @dll declaration

The compiler has detected a syntax error in an @dll statement. This error most likely occurs when an @dll statement has been mistyped. Check the statement for syntactical errors, and then compile again.

J0229 - Expected string constant

The compiler detected a parameter of a comment tag's declaration (for example @com, @dll, or @security) that was expecting a string constant, was either missing it or it was incorrectly entered. This error most often occurs when matching quotes are missing around a value passed to an attribute. Check your comment tag declaration's attributes, and then compile again.

The following example illustrates this error.

/**@com.interface(iid=31415926-5358-9793-2384-612345678901,dual)*/
interface ITest{
   /**@com.method(name=method1);*/
   //error: Missing quotes around 'method1'
   public void method1();
}

J0230 - Class or interface name 'identifier' conflicts with import 'identifier'

The specified class or interface conflicts with a class that has been imported. This could be caused by declaring a class or interface that is already declared in the Java API and you are importing that API class or interface into your source file.

J0231 - Expression statement must be assignment, method call, increment, decrement, or 'new'

The compiler has detected an invalid expression statement. An expression statement is a statement that can reside on its own line of source code. The following are some examples of valid expression statements.

Method calls
m_cars.changeColor();
Assignment statements
int x = y + z;
Increment statement
j++;
m_tempVar1 += 3;
Use of the new keyword
new Simple();

The following are examples of invalid expression statements.

1+2;
Error: No assignment statement
j+k-method1();
A method call but not a valid assignment statement
var1 == var2;
Comparison statements should be contained in flow control statements

J0232 - Expected '{' or ';'

The compiler has detected an error with a method declaration in a class or interface. This error most likely occurs if an interface's method declaration is missing a semicolon at the end of the declaration or a class's declaration is missing its opening brace '{'. Check the specified class or interface method declaration and check for a missing semicolon or opening brace, and then compile again.

J0233 - Catch clause is unreachable; exception 'identifier' is never thrown in the corresponding try block

The compiler detected that the specified catch clause will never be executed because the corresponding try statement never throws the catch statement's exception type. Catch statements are required to catch exceptions or derivations of exceptions that the try statement can throw. This error can be avoided by changing the catch statement so it does not catch a specific exception type but catches the base Exception class. Change the exception class so that your catch statement will trap it, and then compile again.

J0234 - 'identifier' is not a field in class 'identifier'

The compiler detected a field reference but the field does not exist in the specified class. This error most likely occurs when the field reference is mistyped or the field reference was meant to reference a field in a different class. Make sure that the field exists in the specified class and that your reference to the field is syntactically correct, and then compile again.

J0235 - 'identifier' is not a method in class 'identifier'

The compiler detected a method call but the method does not exist in the specified class. This error most likely occurs when the method call is called incorrectly or the method call was meant to reference a method in a different class. Make sure that the method exists in the specified class and that your method call is syntactically correct.

J0236 - 'identifier' is not a nested class or interface in class 'identifier'

The compiler has detected a reference to a nested class or interface but the nested class or interface does not exist in the specified class. This error most likely occurs because of a syntactical error in referencing a nested class or interface. Check the reference to the inner class for syntax errors and make sure that the class or interface exists inside the specified class, and then compile again.

The following example illustrates this error.

class NotSimple{
}

public class Simple{
   void method1(){
      NotSimple nt = new NotSimple();
      Object o = nt.new InnerClass();
      //error: 'InnerClass' is not an inner class of 'NotSimple'
   }
}

J0237 - 'identifier' is not a field or nested class in class 'identifier'

The compiler has detected a reference to a nested class or field but the nested class or field does not exist in the specified class. This error most likely occurs because of a syntactical error in referencing a nested class or field. This error can also occur if a reference to a field in an inner class is made but the field does not exist within the inner class definition. Check to make sure the inner class or field exists, and then compile again.

J0238 - Cannot throw exception 'identifier' from field initializer

The compiler has detected that an exception was thrown within a field initializer. This error most likely occurs when an exception can be thrown from a constructor of a class, and an instance of that class is declared and instantiated as a member of another class. To resolve this problem, have the class object that throws the exception instantiated inside a constructor so it can use a try and catch combination to trap any exceptions from the other class's constructor call.

The following example illustrates this error.

public class Simple{
   public int i;
   public Simple(boolean var1) throws Exception{
      if (var1 = true)
         i = 0;
      else
         throw new Exception();
   }
}
//This is the incorrect way to instantiate this class
class Simple2{
   Simple smp = new Simple(true);
   /* error: cannot call constructor that throws exception in field
            initializer*/
}

J0239 - Static initializer must assign a value to blank final variable 'identifier'

The compiler detected that a static final variable was not initialized to a value using a static or field initializer. To declare a variable as static and final, you must use a static or field initializer to set an initial value. This error can also occur if a field is declared as static and final and assigned a value in a constructor.

The following example illustrates this error.

public class Simple{
   static final int MAX_CONTROL;
} //error: static final variables must have value assigned

J0240 - Syntax error in @security declaration

The compiler detected a syntax error in the specified @security comment tag. This error most likely occurs when the comment tag is missing a closing parenthesis or the tag's attributes are incorrect. Check the syntax of the specified @security comment tag declaration, and then compile again.

The following example illustrates this error.

/**@security()*/   //error: invalid @security syntax
public class Simple{
   //Class members defined here
}

J0241 - '@security' can only be specified on a class or interface

The compiler detected that the @security comment tag was applied to something other than a class or interface declaration. @security comment tags are used to define the security settings for a class or interface definition and cannot be applied to methods or fields of a class or interface.

J0242 - Cannot make static call to nonstatic method 'identifier'

The compiler has detected that a method was called by using the static method call syntax of '<classname>.<method>', but the method is not a static method. Change the method call to use an instance of the class that contains the method instead of the class name itself, and then compile again.

J5001 - Local variable 'identifier' is initialized but never used

The compiler detected an initialized variable that was never referenced in any class code. This message occurs at warning level 3 or greater.

The following sample illustrates this warning.

public class Simple {

   public int method1() {

      int i = 1;
      return 1;
      // warning: 'i' is never used
   }
}

J5002 - Compiler option 'identifier' is not supported

The compiler that detected an unsupported command line option was specified. Check your compiler switch settings, and then try compiling again.

J5003 - Ignoring unknown compiler option 'identifier'

The compiler detected an unknown option specified on the Jvc command line. This warning most likely occurs when a typographical error exists. For example, specifying /W4 on the command line will cause this warning because the warning level option must use a lowercase 'w'.

J5004 - Missing argument for compiler option 'identifier'

The compiler detected a valid command line option, but the required argument was not specified. Check your compiler switch settings and try compiling again.

J5005 - Package 'identifier' was already implicitly imported

The compiler detected an import statement for a package that was already implicitly imported, such as java.lang. This message occurs at warning level 1 or greater.

J5006 - 'private protected' not supported, using 'protected'

The compiler detected use of the modifier combination private protected. This combination is now obsolete and has been replaced by protected. This message occurs at warning level 1 or greater.

J5007 - Not used

This error message is currently not used.

J5008 - Not used

This error message is currently not used.

J5009 - Not used

This error message is currently not used.

J5010 - Not used

This error message is currently not used.

J5011 - Not used

This error message is currently not used.

J5012 - Not used

This error message is currently not used.

J5013 - Not used

This error message is currently not used.

J5014 - 'identifier' has been deprecated by the author of 'identifier'

The method or class referenced has been marked as deprecated. Deprecated methods or classes are marked by the creator of the source code as outdated and subject to removal. To keep code stable, avoid calling functions that have been flagged as deprecated.

J5015 - The parameter 'identifier' in an @com.parameters declaration does not match the corresponding argument 'identifier'

A COM interface parameter declaration does not match the method that implements the interface. This error could indicate inconsistent data types or mismatched of parameter locations.

The following sample illustrates this warning.

/** @com.interface(iid=31415926-5358-9793-2384-612345678901, dual) */
interface ExampleInterface
{
/**
@com.method(dispid=306)
@com.parameters([type=BOOLEAN] when, on)
*/
public String Method1(boolean on, int when); //Error, on and when
                                             // have changed order.
}

J5016 - This 'instanceof' operator will always be true

The compiler determined that the specified instanceof expression will always evaluate to true. This could occur when instanceof is used to determine if a subclass instance is a member of a base class or an implemented interface. Although it is not an error to use the operator in this way, it is not useful because the expression will always evaluate to true.

The following sample illustrates this warning.

interface I {}
class X {}
class Y extends X implements I {}

public class Simple{
   void f()
   {
      Y y = new Y();
      X x = new X();
      Object o;

      // These statements result in J5016 warnings.
      if (y instanceof X){
         // y is of type Y, which extends X, so this is always true
      }
      if (y instanceof I){
         // type Y implements I, so this is always true.
      }
      if (x instanceof Object){
         // everything is of type Object
      }
   }
}


Tools Quick Reference

This section defines the command-line syntax and operation of the Java tools included with the Microsoft SDK for Java.

Microsoft AppletViewer (appletviewer)

appletviewer url | filename

Runs a Java applet.

Parameter | Description
url | Specifies the address of an HTML file containing an APPLET tag that defines the Java applet to run.
filename | Names the HTML file containing an APPLET tag that defines the Java applet to run.

AWT Conversion Wizard (awt2afc)

The awt2afc utility is a web-based application that parses Java source code and determines what changes are necessary to convert the source to use the Application Foundation Classes (AFC). The utility only adds source code comment-style suggestions to an existing source file. It does not handle the conversion process.

The awt2afc utility has two functions. It determines and lists the classes that need to be changed in an existing source file in order for the source to run with AFC. It can also add comments directly to a source file at each declaration or instantiation of a class that could be replaced in source.

The list of classes appears below the applet and is generated every time you select Go. The list includes links to pages that suggest changes for particular classes and a link to a page that lists all the classes that do not change when using AFC. Select Show All Conversions to list all the classes and their suggested AFC conversions.

The Add Comments to Source check button controls whether awt2afc inserts suggestions directly into a parsed source file. The comments are inserted at each instantiation and declaration of an AWT class, but not at each method. See the help files included in the generated list for specific method conversions for a particular class. Each comment follows the following format:

//TODO: Suggestion (AWT2AFC)

This format makes it easy to do a global search for suggested code changes in a source file.

The Create Backup option saves the original parsed file under a .bak suffix (MySource.java becomes MySource.java.bak). Only one backup file is made, and it is overwritten if a file is parsed mutiple times.

Cabinet File Archiving Utility (cabarc)

cabarc [options] [command] filename

Handles the archiving of multiple files in a compressed format.

For more information, see Creating and Using Cabinet Files for Java Applets and Libraries.

Parameter Description
options The n command can take a combination of the following options:
/p | Preserves the directory name in the cabinet file when used with the n command and uses that directory information when used with the x command. By default, only the filename component is stored or extracted.
/P path | Strips the path entered from any paths preserved in the cabinet file when using the p option.
/r | Archives files recursively in all subdirectories.
/s size | Reserves space size in the cabinet file for a code signature. The size parameter should be 6144 bytes.
/i cabinet ID | Includes a specified 16-bit cabinet identifier for application use.
/m compression type | Sets the compression type. compression type can be either MSZIP or NONE. By default, MSZIP is used as the compression type.
@file file | Takes the list of files to be added to the cabinet file from a specified text file.
command Can be one of the following commands:
n filename | Creates a new cabinet file with a name specified by filename. See the previous options for a description of the options available with this command.
l filename | Lists the contents of the cabinet file specified by filename. Cabarc also displays any cabinet identifier in the cabinet file (see the previous option /s) and the following file information: size, date, time, and attributes.
x | Extracts files from the cabinet file specified by filename. See the previous /p option for extracting files into the original directory.
filename Specifies a list of files to be archived. Wildcards (such as *.java) are accepted. All files are placed in a single folder, unless a plus sign (+) is placed in the list to delimit folders. For example, the following command would create two folders.
cabarc /n n mycab.cab test.* + *.java

Remarks:

Use this utility to create new cabinet files or to list or extract files from existing cabinet files.

Software Publisher Certificate Test Utility (cert2spc)

cert2spc cert1.cer cert2.cer...certN.cer outputSPCfile.spc

Creates a Software Publisher's Certificate (SPC) from one or multiple X.509 certificates. This utility, like makecert, is for test purposes only. A valid SPC is obtained from a Certification Authority (CA).

Parameter | Description
certN.cer | Specifies the name of an X.509 certificate to include in the SPC file.
outputSPCfile.spc | Specifies the name of the PKCS #7 object that contains the X.509 certificates.

Certificate Manager (certmgr)

certmgr [options] [/s[/r RegistryLocation]] Storename

certmgr /add [options] [/s[/r RegistryLocation]] SourceStore [/s[/r RegistryLocation]] DestinationStore

certmgr /delete [options] [/s[/r RegistryLocation]] SourceStore [/s[/r RegistryLocation]] DestinationStore

The certmgr utility manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs). The certmgr has three basic functions, as follows:

  • Displays certificates, CTLs, and CRLs. In this capacity, it replaces the dumpcert utility.
  • Adds certificates, CTLs, and CRLs, from one certificate store to another.
  • Deletes certificates, CTLs, and CRLs, from a certificate store.

Certmgr works with two kinds of certificate stores, StoreFile and system store. It is not necessary to specify the type of store file; certmgr can identify the StoreFile type and perform the appropriate operations.

Parameter Description
/add Adds certificates from one certificate store to another. When this option is invoked, the following options may also be used.
/c | Adds certificates.
/CTL | Adds certificate trust lists (CTLs).
/CRL | Adds certificate revocation lists (CRLs).
/all | Adds all the entries.
/7 | Saves the destination store as a PKCS#7.
/n commonName String | Specifies the common name of the certificate to add. This option can only be used with certificates; it cannot be used with CTLs or CRLs.
/sha1 sha1Hash | The SHA1 hash of the certificate, CTL, or CRL to add.
/delete Deletes certificates. When this option is invoked, the following options may also be used.
/c | Deletes certificates.
/CTL | Deletes certificate trust lists (CTLs).
/CRL | Deletes certificate revocation lists (CRLs).
/all | Deletes all the entries.
/7 | Saves the destination store as a PKCS#7.
/n commonName String | Specifies the common name of the certificate to delete. This option can only be used with certificates; it cannot be used with CTLs or CRLs.
/sha1 sha1Hash | The SHA1 hash of the certificate, CTL, or CRL to delete.
options The certmgr utility also accepts the following options.
/s | Indicates the store is a system store. If this option is not set, the store is a StoreFile.
/r Registry location | Identifies the registry location of the system certificate store. This option is considered only if the /s option is set. Registry location must be either currentUser (indicating that the certificate store is under the HKEY_CURRENT_USER key [the default]) or localMachine (indicating that the store is under HKEY_LOCAL_MACHINE).
/? Displays Help for the utility.
/v | Verbose mode. Displays detailed information about certificates (CTLs and CRLs). Using the certmgr tool with the /v option performs the same function as the dumpcert tool. This option is not used with the /add or the /delete options.
/c | Displays certificates when used without the /add or the /delete options.
/CTL | Displays certificate trust lists when used without the /add or /delete option.
/CRL | Displays certificate revocation lists when used without the /add or /delete option.
/y storeProviderType | Specifies the store provider type.
/f dwFlags | Specifies the store open flag. This is the dwFlags parameter passed to CertOpenStore. The default value is CERT_SYSTEM_STORE_CURRENT_USER. This option is considered only if the /y option is used.
/e encodingType | Specifies the certificate encoding type.

Remarks:

The following examples show some of the certmgr utility's different functions.

View a system store called my store.

C:\..\>certmgr /s my

Add all the certificates in a file called myfile.ext to a new file called newFile.ext.

C:\..\>certmgr /add /all /c myFile.ext newFile.ext

Move a certificate with a common name myCert in my system store to a file called newCert.cer.

C:\..\>certmgr /add /c /n myCert /s my newCert.cer

Delete all the CTLs in my system store and save the resulting store to a file called newStore.str.

C:\..\>certmgr /del /all /ctl /s my newStore.str

Java Signature Verification (chkjava)

chkjava [options] filename

Allows users to view security information placed in a cabinet file by signcode with the JavaSign DLL. The utility checks the validity of a signature and displays the certificate information and security permissions contained in the file on the console output.

If the signing information is valid, and the signature contains Microsoft® ActiveX® permissions, the utility displays a message that indicates the file is signed with ActiveX permissions.

Parameter | Description
options The chkjava utility supports the following options:
/q | Suppresses all message boxes (quiet mode). If you do not specify the /q switch, the utility displays a dialog box that shows all the permissions and signature information.
/o outputfile | Specifies that permissions read from the signed cabinet file will be written to the output file in an .INI format. The format of the output file is the same as the input file for JavaSign.dll.
filename | Specifies the name of the file to verify Java permissions for.

Remarks:

The following output is an example showing the format used
when the signed file is successfully read and the information
is dumped to the screen.

   Filename:         <filename>
   Program Name:     <OpusName>
   Further Info:     <Info Location>

   Published by:     <Publisher Name>
   Publisher type:   (Commercial | Individual)
   Verified by:      <Agency Name>

   Trust Level:      (High | Medium | Low | Custom)
   [<permission info>]

If the /o flag is specified, the permission information will be written to a text file suitable for input as the information file in signcode using the JavaSign.dll.

The following example shows various sample command lines using the chkjava utility, and their results.

C:\..\>chkjava my.cab
   Displays a dialog box with signature information.

C:\..\>chkjava /o test.ini my.cab
   Displays a dialog box and outputs the .INI file as test.ini.

C:\..\>chkjava /o test.ini /q my.cab
   Only outputs to .INI.

C:\..\>chkjava /q my.cab
   Displays only basic information.

Certificate File Validation Utility (chktrust)

chktrust [options] filename

Checks the validity of a file by extracting the PKCS #7 data object and its X.509 certificates, and compares a hash with the signed hash in the PKCS object. If the hash is equivalent to the signed hash code, the utility verifies that the signer's X.509 certificate is traceable back to the root certificate and that the correct root key was used.

Parameter | Description
options The chktrust utility accepts the following options.
/c | A cabinet file (for Internet Explorer 3.02 UPD only).
/i | A PE image file. Includes .exe, .dll, and .ocx files (for Microsoft® Internet Explorer 3.02 only).
/n | No user interface in a "bad trust" case (for Internet Explorer 3.02 only).
/s | Software publishing trust provider (default, for Internet Explorer 4.0 only).
/q | Software publishing trust provider, but no user interface in a "bad trust" case (for Internet Explorer 4.0 only).
/w | Windows compatibility trust provider.
/cf | Catalog file and path.
/cmt | Catalog member tag.
/? Displays options.
filename | The signed file to check trust on.

Remarks:

Versions of chktrust that are older than the one released with Internet Explorer 3.02 can't validate files signed with later Microsoft® Authenticode™ releases.

Class File Contents Viewer (classvue)

classvue [options] [drive:][path] classname [>outputfile]

Displays the contents of a Java class in a readable format.

Parameter | Description
options Can be a combination of the following:
/min | Displays only D1 level information.
/ltd | Displays only D1, D2, and D3 level information (see the following for definition).
/v | Provides a verbose display of the .class file.
/cpno | Suppresses the display of constant pooling.
/tables | Displays many of the items in table form.
/ivmal | Generates informal Virtual Machine Assembly Language.
/CVue | Displays output sent to a file named by the package and class with the extension .cvue.
/q | Suppresses the Microsoft copyright banner (quiet mode).
/? Displays the list of available options.
/D? | Displays the list of information levels.
/readme | Displays descriptions of ActiveX® terms and abbreviations displayed by classvue, and known issues relating to the utility.
classname | Specifies the name of a Java .class file. This must specify a drive or a path (or both) of the file if it is not in the current drive or directory.

Remarks:

The classvue utility writes information to the standard output, listing a class overview and the offsets, sizes, types, and values of the constant pool, fields, methods, and attributes belonging to the class.

The ClassVue utility generates seven description levels. By default, all levels are displayed. You can use the /min, /ltd, or /cpno options to alter the levels displayed. The description levels are as follows:
D1 | Overview information
D2 | Methods, fields, and classes
D3 | Root data structures
D4 | Constant pool
D5 | Fields pool
D6 | Methods pool
D7 | Attributes pool

Example:

The following command line generates information about a class named "Hello."

classvue \SDK\Samples\Jexegen\Hello\Test\Hello.class

Package Manager Archive Utility (clspack)

clspack [options] [filename]

The clspack windows-based utility enables you to write the contents of packages that are installed with the package manager to a .zip file archive. This avoids constant downloads of the classr.exe self-extracting archive; you can now create your own archive from the contents of the Java Language Package Manager (JPM).

The utility reads from a text file that contains the list of packages to write to the .zip file archive. This enables you to archive only packages that you need. The following example shows how you can create a .zip file using the contents of a text file. The clspack utility is case insensitive, so packages like com.ms.activeX and com.ms.util.InputMethod are parsed as com.ms.activex, and com.ms.util.inputmethod, respectively. The text file lists the following packages:

java.io
com.ms.util
com.ms.util.cab
com.ms.util.InputMethod

The clspack utility automatically skips non-system classes (including when the -dump or -auto options are used from a command line). However, the utility will export any class if it is included in the text file that lists the packages.

Parameter Description
options In addition to its windows-based operation, the clspack utility currently accepts the following command line options:
-auto Creates a single Classes.zip and adds it to your classpath, if not present. It contains all system classes stored in the JPM. The Microsoft compiler for Java (jvc) checks this location by default, so there is no need to set your class path environment variable. If you use another Java compiler that does not check this location, set your class path variable as follows:
C:\>set CLASSPATH=%WINDIR%\java\classes\classes.zip

Use the javasrc utility to extract the contents of classes.zip.

-dump outputfile | Writes all the system packages currently installed in the package manager to the specified output file.
-nonsystem | Builds a Microsoft VJ++ 1.1 compatible .zip archive for non-system classes (java\trustlib\nonsystm.zip). This archive is built separately from classes.zip and is added to the trusted classpath.

A .zip file that contains the contents of system packages stored in the package manager is created first by using the -dump option to create a text file that lists the various packages. Run the clspack utility with this same text file as the source package list:

clspack -dump tmpfile.txt
clspack MyJavaClasses.zip tmpfile.txt

Custom Permission Editor (cprmedit)

cprmedit

Edits Java permissions for security zones recognized by Microsoft® Internet Explorer 4.0 and later.

The cprmedit tool enables you to edit Java permissions for specific security zones using a graphical user interface. The permissions set by cprmedit are recognized by Internet Explorer 4.0 and later. The user interface presented by the cprmedit tool is similar to the dialog boxes in Internet Explorer 4.01 that allow administrators to set security options.

To run the Custom Permission Editor, type cprmedit on the command line. The Custom Permission Editor dialog box will appear. To edit the permissions for a particular zone, choose one of the zones listed in the drop-down list box. For each zone, there are three sets of permissions that you can edit.

Permission Set | Description
Unsigned Permissions | Permissions that are granted to unsigned content.
Trusted Signed Permissions | Permissions (requested by signed content) that do not require user approval.
Untrusted Signed Permissions | Permissions (requested by signed content) that require user approval or permissions that are absolutely denied.

You can choose to add all permissions to a permission set or you can edit specific permissions in the set. If you need more information about how to edit a particular permission, you can get context-sensitive help by pressing F1 after you have selected a check box or text box.

For more detailed information about how to use the Custom Permission Editor, see the Using the Custom Permission Editor article.

Distribution Unit Archiving Utility (dubuild)

dubuild filename.cab [drive:][path] [options]

Writes an Open Software Distribution (OSD) file and places it in a cabinet file archive with any specified contents. The dubuild utility is similar to cabarc, but uses the OSD manifest instead of .inf files. Dubuild and Distribution Units are only used by Internet Explorer 4.0.

For more information, see Using DUBuild.

Parameter | Description
filename.cab | Specifies the Distribution Unit filename.
path | Specifies the source path to the files that are included in the archive.
options Can be a combination of the following:
/H or /? | Displays the list of available options.
/D "friendlyname" | Sets the Distribution Unit's friendly name.
/P oldDUName.cab | Specifies a previous Distribution Unit filename used in creating Split DUs.
/M | Creates a multi-cab Distribution Unit.
/I pattern | Includes files that match the specified pattern.
/X pattern | Excludes files that match the specified pattern.
/N "namespace" | Sets the DU's namespace.
/B BeanInfo | Used to register ActiveX controls as JavaBeans.
/S pattern | Marks packages as system packages.
/V version | Use default version numbers for VD, VP, and VN.
/VD version | Sets the minimum version number for the Distribution Unit.
/VP version | Sets the minimum version number for the packages included in the DU.
/VN version | Sets the version number for new packages included in the DU (used in creating Split DUs).
/Z | Builds DUs with MSZIP compression for Internet Explorer 3 compatibility. By default, LZX compression is used.

Remarks:

The dubuild utility creates Distribution Units, Split Distribution Units and registers ActiveX controls as Beans. Any command-line parameters may be specified from a file by providing that file's name as @file.

The {BeanInfo} syntax is as follows:

/B package,class,regmode,progid,guid,iconfile,flags,tlbguid,
   tlbfile,bitmap32

The arguments must be in this order and may not have any spaces, and there cannot be any spaces between comma separators if any parameters are excluded. For example, if you do not want to include an iconfile, you would use the following syntax:

C:\..\>dubuild /B pkg,cls,regmd,pid,guid,,flags,tlbguid,tlbfile,bit32

Simple Bean identification can be done by supplying only the package name and the class filename. ActiveX registration requires regmode and at least the guid argument, as well.

Simple Registration
C:\..\>dubuild /B com.foo.net,Connect.class

Full Registration
C:\..\>dubuild /B com.foo.net,Connect.class,ActiveX,
      FooNetConnector,{FCOCF5C5-06DA-11d1-8F36-00C04FD8FF5E},
      com\foo\net\Connect.ico,1,
      {FCOCF5C6-06DA-11d1-8F36-00C04FD8FF5E},
      com\net\foo\Connect.tlb,
      com\net\foo\Connect.bmp

GUID Generator (guidgen)

Generates a globally unique identifier (GUID).

Remarks:

The guidgen utility displays a dialog box that you specify the format of the GUID definition with. You can then save the definition to the Clipboard and paste it into your source file. For more information about using this utility, press F1 in the guidgen dialog box to open a Help window.

Java/ActiveX Integration Utility (jactivex)

jactivex [options] filename

Hosts automation-enabled ActiveX Controls in Java and generates Java source from type libraries.

For more information, see Using Jactivex's JavaTLB Compatibility Support and Using Jactivex to Create a User-Defined Type for Java/COM Marshaling.

The default operation is to create a JavaBean wrapper for an ActiveX Control. Jactivex creates IDispatch wrappers for an ActiveX object using code and helper objects that are similar to JavaBeans to add and remove listeners for the ActiveX event interfaces.

The jactivex utility also inherits all the capabilities of the jcom utility (released in previous versions of the Microsoft SDK for Java) to generate Java source files from type libraries. These operations are performed with an additional switch, /javatlb, but are otherwise the same as with the jcom utility.

Parameter Description
options
/javatlb Accesses Component Object Model (COM) integration features not available in default mode (generates Java source from type libraries). To access lower-level COM integration features with the jactivex utility, use the /javatlb switch and any combination of the following switches:

/b | Follows JavaBeans design pattern for properties.
/cj | Creates template for implementing coclass in Java.
/d directory | Sets the output directory for concerted controls. By default, the directory is set as (default=%WINDIR%\java\trustlib).
/e | Excludes the output for typelibs not on command line.
/G3.1 | Targets 3.1 Microsoft VM for Java (default=/G4).
/G4 | Targets 4.0 Microsoft VM for Java (default=/G4)
/j | Generates undecorated Java source.
/l list file | Creates a list of all output files (default=none).
/n jnffile | Specifies a JNF file (default=none).
/nologo | Suppresses the Microsoft copyright message.
/p package name | Sets the root package. By default, the package name is not set.
/p:b- | Indicates that the type library name is not included in the package.
/r | Registers type libraries.
/w | Disables all warnings.
/WX | Elevates warnings to error status.
/x2 | Represents 2-byte integers as a char.
/xc | Ignores coclasses in typelib.
/xd- | Do not generate Default interfaces.
/xh | Do not map S_FALSE to ComSuccessException.
/X:m- | Disables auto-marshaling. By default, auto-marshaling is enabled.
/xi | Exposes default interface methods directly on coclass.
/? Displays command-line help and usage.

filename When run in default mode, this is the name of the ActiveX file to create a wrapper for.

The following command creates a JavaBean wrapper for an ActiveX control:

jactivex mscal.ocx

Otherwise, if you use the /javatlb switch and any other options, this is the name of the type library that the Java source will be generated from.

For more information on jactivex command-line options that relate to Java/COM integration, see Jactivex Extended Command-Line Options.

Remarks:

Warning Do not use Microsoft® Visual J++™ compilers earlier than version 1.02.3920 to compile the files generated by this utility.

Java Register (version 2.0) (javareg)

javareg [options]

Registers Java classes as COM components in the Microsoft® Windows® Registry.

For more information about using this utility, see Using JavaReg.

Parameter Description
options
/? Provides command-line Help and usage information.
/register | Registers the command-line class parameter with the specified class identifier in classid. You can also use /register with /class, but without the class identifier to force javareg to create a CLSID and register it. Javareg will also recognize the /regserver switch for this command. The /register switch can also be used with several other switches to register a JavaBeans object as an ActiveX Control.
/codebase:[filename|URL] | Specifies the base location, either a URL or a filename, to obtain the Java class.
/control | Adds the necessary Registry information for containers to treat the Java class as an ActiveX control.
/typelib: [filename] | Generates the type library for this Java class at the specified filename's location. In order to register a typelib without generating a new one, use this option combined with the nomktyplib option.
/nomktyplib | Registers an existing typelib, specified in the filename argument of the /typelib switch, without creating a new one.
/unregister | Unregisters the class specified in the class parameter. If /unregister is specified, /class:classname must be specified as well.
/class:classname | Specifies the name (classname) to be registered with the classid (or with the CLSID generated by javareg if no classid is provided).
/clsid:CLSID | Specifies the class identifier (CLSID) to be registered with the class. Omit this parameter to force javareg to create a CLSID.
/surrogate | Supports remote access to COM classes. Writes the appropriate Registry entries necessary to allow the Java class to be activated out-of-process.
/progid:PROGID | Specifies a ProgID for the class being registered.
/remote:RemoteServerName | Activates the class on a remote server, using Distributed Component Object Model (DCOM).
/q | Suppresses all message boxes (quiet mode).

Package Manager Extraction Utility (javasrc)

javasrc [-] [class_zip]

Extracts all java source files from class_zip, or classes.zip (created by clspack) if no .zip archive is specified.

Note If you run classd.exe from the \bin directory and then run javasrc, the error message, "Unable to open file classes.zip" may appear. Run javasrc from within the Java\Classes directory, or run it with a command line that includes the path to classes.zip.

C:\..\>javasrc C:\Windows\java\classes\classes.zip

The classd.zip debug source file is not installed automatically and can be installed from the Active Setup SDK installation program.

Parameter Description
options The javasrc utility has the following command-line options:
/? Displays help and usage information.
- Deletes all java source files that are extracted from class_zip.

Java Win32 Executable Generator (jexegen)

jexegen [options] [@command file] filename

Converts Java classes into a fully executable Microsoft Win32® application.

For more information, see the Introduction to Jexegen.

Parameter | Description
options Can be a combination of the following:
/main:classname | Sets the name of the main .class file. This option is required.
/nomain | Indicates that no main .class file is specified (useful only in conjunction with the /raw or /bindto options).
/base:dir | Changes the base directory used when determining package names of specified .class files to dir.
/out: filename | Sets the output filename.
/r[–] | Recurses into subdirectories when searching for the specified .class files. Use a hyphen (-) after the switch to disable this option if /r has already been used in the command string.
/v | Provides detailed output.
/w | The generated executable will not have an associated console window.
/bindto: stub | Specifies the stub (.exe or .dll file) to bind the class resources to.
/raw | Saves resource data to a file and does not generate an executable.

For a detailed description of each of these options, see Reference to Jexegen Command-Line Options.

@command file | As an alternative to specifying all the class files and options on the jexegen command line, you can use a command file. For more information, see the Introduction to Jexegen.
filename | Name of the Java .class file or files that the executable will be generated from.

Remarks:

If you do not specify the /out option, the utility creates the executable file Jex.exe (by default).

Examples:

The following command line creates the executable file, Hello.exe, from a single .class file, Hello.class.

jexegen /out:hello.exe /main:Hello Hello.class

The following command line creates the executable file, classvue.exe, from all classes in the classvue directory in the Microsoft SDK for Java.

jexegen /out:classvue.exe /main:ClassVue *.class

Windows NT Service Executable Generator (jntsvc)

jntsvc [options] [@command file] files

The jntsvc utility generates self-contained, self-installing/uninstalling, redistributable executables (.exe files) for Microsoft® Windows NT® system services.

For more information about using the jntsvc utility and about the user options for the generated service executable, see the com.ms.service package overview.

Parameter | Description
options Can be a combination of the following:
/base:dir | Changes the base directory and is used to determine package names of specified class files. When used with the /raw or /bindto option, /base specifies the base directory that file operations are relative to. By default, package names and file operations are determined relative to the current directory. If this option is used more than once on the command line, all /base options are relative to the original (current) directory.
/out: filename | Specifies the name of the output file.
/r | Indicates that jntsvc should search recursively into subdirectories when searching for the specified class files. By default, subdirectories will not be searched.
/r– Used to turn off subdirectory recursion. This is only useful if the /r option has already been used.

As an example, consider the following partial command line:

/r This*.class /r- That*.class

This example command line instructs jntsvc to find all class files that match This*.class in the current directory and all subdirectories, and all files that match That*.class only in the current directory.

/v | Verbose mode; provides detailed output.
/svcmain: classname (Required) Sets the name of the main service class file. This class must be derived from com.ms.service.Service. The name specified on the command line must be the same as the class's internal name; it is case-sensitive and you must separate package names with periods.

For example, if the service's class name is MyService and is in package MyPackage, the appropriate switch for jntsvc would be

/svcmain:MyPackage.MyService.

This option may be used multiple times to specify the service class of each service that may be run within the same process. One or more service-specific options may follow each service:
/servicemain: service name | Sets the name the service is registered as.
/displayname display name | Sets the descriptive name of the service. This is displayed in the first column of the Services control panel.
/eventsource event source name | Sets the event source name. The default is Java Service. This is displayed in the Source column of the event viewer.
/classpath path | Sets any additional class paths required. Because the service classes are embedded in the generated executable, this does not need to point to the service classes (unlike Microsoft SDK for Java version 1.5 services).

/bindto: stub | Specifies the stub (.exe or .dll file) to bind the class resources to.
/raw | Saves resource data to a file and does not generate an executable.
@command file | As an alternative to specifying all the class files and options on the jntsvc command line, you can use a command file. For more information, see the Introduction to Jexegen.
files | The name of the Java .class file or files that the executable will be generated from.

Remarks:

The use of the command file and specification of the class files in combination with the /base and /r options are identical to jexegen.

Microsoft Compiler for Java (jvc)

jvc [options] filename

Creates Java programs and applets by compiling Java source code.

For more information, see the Introduction to jvc and Jvc Release Notes.

For a listing of all errors and warnings produced by this compiler, see Jvc Errors and Warning Messages.

Parameter | Description
options Can be a combination of the following:
/cp classpath | Sets the class path environment variable for the current compilation.
/cp:o | Prints the class path to standard output.
/cp:p path | Inserts the path entered and a semicolon to the beginning of the class path environment variable.
/d | Specifies an output directory other than the current directory for the .class files.
/g [-] | Generates all debugging information. Use a hyphen (-) after the switch to disable this option.
/g:l [-] | Generates line number debugging information. Use a hyphen (-) after the switch to disable this option.
/g:t [-] | Generates debug tables. Use a hyphen (-) after the switch to disable this option.
/nowrite | Compiles a .java file and suppresses the writing of a .class file.
/O [-] | Combines optimizing options to produce the fastest possible program. Use a hyphen (-) after the switch to disable this option.
/O:I [-] | Optimizes compilation by inlining methods (when appropriate). Use a hyphen (-) after the switch to disable this option.
/O:J [-] | Optimizes bytecode jumps (default setting). Use a hyphen (-) after the switch to disable this option.
/verbose | Prints messages about compilation progress.
/w[0-4] | Sets warning level (the default is 2).
/x [-] | Disables extensions (the default is to enable extensions).

For a detailed description of each of these options, see Reference to Jvc Command-Line Options.

filename | Name of one or more source files.

Remarks:

You can specify any number of options and filenames, if the number of characters on the command line does not exceed 1024 or the limit prescribed by the operating system.

Java Viewer (jview)

jview [options] classname [arguments]

Executes Java applets and applications from the command line.

For more information, see the Introduction to Jview.

Parameter | Description
options Can be a combination of the following:
/a | Invokes the use of the Microsoft AppletViewer. Applets viewed with the Microsoft appletviewer function the same as when viewed with a browser, including sound, loading, security features, and so on. When the appletviewer switch is used, all other remaining command-line tokens become parameters used by the appletviewer.
/cp classpath | Sets the classpath environment variable. For more information, see CLASSPATH Environment Variable.
/cp:a path | Appends the path entered at the end of the classpath environment variable and inserts a semicolon between them.
/cp:p path Inserts the path entered and a semicolon at the beginning of the classpath environment variable.

For more information, see Reference to Jview Command-Line Options.

/p | Pauses before terminating if an error occurs.
/n namespace | Provides a namespace in which to run an application. This allows Java packages with identical names to exist without conflict, if they are in separate namespaces. The Microsoft JPM stores packages in a global namespace and searches there for packages if no namespace is specified to its API elements (for example, the contents of classes.zip is stored in the global namespace). Note, however, that applications running in the name space specified with the /n switch cannot access other namespaces.
/v | Verifies all invoked methods (normally, only methods from untrusted loaders are verified).
/D:property=value | Sets a system property to a specified value. System properties are defined in the Java.lang.system.getProperty method.
classname | Name of the .class file to execute. Do not use the .class extension with this filename.
arguments | Command-line arguments to be passed to the .class file supplied in classname.

X.509 Certificate Creation Utility (makecert)

makecert [options] OutputCertificateFile

Generates a test X.509 certificate. It creates a public and private key pair for digital signatures and associates it with a name that you choose. The utility also associates the key pair with a specified publisher's name and creates a X.509 certificate that binds your name to the public part of the key pair.

Parameter | Description
basic options The makecert utility supports the following basic options:
/sk | Subject's key container name (will be created if not present).
/ik | Issuer's key container name.
/# Serial Number from 1 to 2^31-1. Default to be unique.
/$ The signing authority of the certificate: either individual, commercial, minimal or all.
/n | Certificate subject X500 name (eg: CN=Fred Dews).
/? Returns a list of basic options.
/! Returns a list of extended options.
extended options The makecert utility supports the following extended options:
/sc | Subject's certificate file.
/sv | Subject's PVK file (will be created if not present).
/sp | Subject's CryptoAPI provider's name.
/sy | Subject's CryptoAPI provider's type.
/ic | Issuer's certificate file.
/iv | Issuer's PVK file.
/is | Issuer's certificate store name (default to my+root+ca).
/ir | Location of issuer's certificate store, either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER. The default is HKEY_CURRENT_USER.
/ip | Issuer's CryptoAPI provider's name.
/iy | Issuer's CryptoAPI provider's type.
/a | The signature algorithm, either md5, or sha (the default is md5).
/d | Display name for the subject.
/l | Link to the policy information (such as URL).
/ky | Key types, either signature or exchange (the default is signature).
/cy | Certificate types, either end, authority, or both.
/b | Start of the validity period (default to now).
/m | The number of months for the certificate validity period.
/e | End of validity period (defaults to 2039).
/h | Max height of the tree below this certificate.
/g | Create a glue certificate.
/r | Create a self-signed certificate.
/nscp | Include Netscape client-authorization extension.
/eku | Comma separated enhanced key usage OIDs.
OutputCertificationFile | The test X.509 certificate (.cer) file.

Remarks:

The makecert utility uses slightly different syntax dependent on whether Internet Explorer 3.02 or Internet Explorer 4.0 is used. See Java Code Signing in Microsoft® Internet Explorer 4.0 for more information.

Header File Converter for Java (msjavah)

msjavah [options] ClassName

Generates C language header files for Java classes.

Parameter | Description
options Can be a combination of the following:
/v | Specifies verbose output.
/classpath pathname | Sets an alternate class path to search in addition to the classpath environment variable.
/d output directory | Specifies an output directory to place the header files. Ignored if the filename used with the /o option includes absolute pathnames.
/o outfile | Specifies the output filename of the header file. By default, a separate header name is generated for each class name based on the class name. With this option specified, all classes are generated in the header file specified by outfile.
/nologo | Suppresses the Microsoft copyright message.
/noclint | Does not run class initializers in any specified classes. By default, msjavah attempts to run initializers. If the initializers fail, a warning message is displayed and the class is reloaded without running the initializers.
/nowritebarrier | Produces headers without const declarations of object member fields. Newer implementations of the Java garbage collector require all members of objects that are object references be modified with the GCSetObjectReferenceForObject API. As a result, these fields are generated as const fields. Pragmas for the Microsoft compilers are generated to disable the appropriate warnings encountered when the compiler fails to generate default constructors. The /portable switch suppresses these pragmas, to ensure portability.
/portable | Generates headers without enhancements specific to the Microsoft compiler (pragmas and so on).
/helpers | Generates inline wrapper methods for making static and non-static Java calls through the execute_java_dynamic_method and execute_java_static_method Raw Native Interface APIs. Use of these helpers allows incompatible changes to a Java method's signature to result in compilation errors, rather than runtime errors.
/ctors | Generates operator new wrapper methods for constructing Java objects through the execute_java_constructor API. This option is similar to /helpers; incompatible changes to constructors result in compilation errors, rather than runtime errors.
ClassName | Name of the Java class to create a C header file for (required).

Remarks:

Unlike other utilities, you must give a Java class reference instead of a filename for the given class, as in the following example.

msjavah java.lang.Thread

One command can create multiple headers, and a header file will be created for each (unless the /o option is included). For example, the following command line produces two header files, java_util_Hashtable.h and java_lang_System.h.

msjavah java.util.Hashtable java.lang.System

In contrast, the following command line generates a file called headers.h, which includes both classes.

msjavah /o headers.h java.util.Hashtable java.lang.System

You can use the /portable switch to create headers that suppress pragmas specific to the Microsoft compiler, and other compiler information, to ease portability. The following command line produces a portable file called headers.h, which includes several classes.

msjavah /o /portable headers.h java.util.Hashtable
    java.lang.System java.lang.Thread

You use the /helpers and /ctors options with the msjavah utility to generate inline RNI wrapper method calls. For example, the following class has a constructor and a static and a dynamic method.

class fuzzle {
    void dynamicMethod (int i) {}
    static void staticMethod (String s) {}
    fuzzle (int i1, int i2) {}
}

The msjavah utility generates the following native code.

C:\..\>msjavah /helpers /ctors fuzzle

void nativeMethod () {
    GCFrame gcf;
    struct gc {
        Hfuzzle *fuzzle;
    };
    GCFramePush(&gcf, &gc, sizeof(gc));
#ifdef __cplusplus
    // Note that arguments are presented *before* the
    // class name, as arguments to the 'new' operator
    // and not directly to the constructor.
    // Generated by /ctors
    gc.fuzzle = new (3, 10) Hfuzzle;
    // Generated by /helpers
    gc.fuzzle->dynamicMethod(5);
#else
    /* Generated by /ctors */
    gc.fuzzle = new_fuzzle(3, 10);
    /* Generated by /helpers */
    fuzzle_dynamicMethod(gc.fuzzle, 5);
#endif
    /* Generated by /helpers */
    fuzzle_staticMethod(makeJavaString("Hello", 5));
    GCFramePop(&gcf);
}

Permission INI File Editor (piniedit)

piniedit [inifilename]

Creates and edits .ini files for use with the signcode tool.

The Permission INI File Editor tool provides a quick way to create .ini files that are used with the signcode tool. The signcode tool uses .ini files to provide descriptions of the permission settings that Java applets need. Using an .ini file with the signcode tool enables you to digitally sign your applet with the permissions encoded within the digital signature. The other way to create .ini files requires manually creating the file and setting the value of each variable in the file. The Permission INI File Editor creates and edits .ini files quickly and easily by enabling you to specify the permissions using a graphical user interface.

To start the Permission INI File Editor, type piniedit on the command line, optionally followed by the name of the .ini file that you want to edit.

To edit the .ini file, choose a Tab that corresponds to a permission that you want to specify. You can then edit the permission by selecting appropriate check boxes and entering parameters in the text boxes. The following table lists the Tabs and the permissions that can be edited in each Tab.

Tab Name | Permission Description
File | The ability to read, write, or delete files.
Registry | The ability to read, write, delete, create, or open keys in the registry.
Network | The ability to connect or bind to various hosts or ports on the network.
Client Services | The ability to access client storage, perform user-directed file I/O, access user interface functionality, print, use multimedia libraries, and access security classes.
System | The ability to run programs, access system properties, manipulate threads, and redirect system streams.
Reflection | The ability to access public or declared members of a class, based on the class loader.
Custom | The ability to use a non-system permission designed by the user.

If you need more detailed information about these permissions and how to edit them, see the Editing Permission Sets section of the documentation for the cprmedit tool. (The cprmedit tool uses the same user interface as piniedit, but instead of editing .ini files, cprmedit sets Java permissions for security zones.)

You can select the High or the Medium button to set all permissions to a High or Medium security level, respectively. These buttons are useful if you want to save time by adding to or removing permissions from a preset group of permissions. Be aware that selecting High or Medium erases any permission editing that you have done previously and then resets the permissions to High or Medium. To clear the settings for all permissions, select the Clear button. To create an .ini file with a Low security level, select the Full Permissions button. This setting allows all permissions.

You can also load the permissions from a specific zone by choosing Load from Zone from the Zone menu. This action will allow you to edit the .ini file using a set of permissions that are identical to the permissions for the specified zone.

To add ActiveX permissions to the .ini file, select the ActiveX permissions button.

When editing the File, Registry, Network, property access, or execution access permissions, you can use the asterisk (*) and the question mark (?) as wildcard characters in the text boxes. You can use semicolons (;) to delimit multiple entries in the property access and execution access text boxes. Multiple ports in the Network permission should be separated by commas.

If you are using an asterisk, a question mark, or a semicolon as a literal in an expression, you need to precede the literal character with a backslash and put the whole expression in double quotes. Each literal backslash must also be preceded by a backslash. For example, if you want to specify all files in the c:\windows directory whose second character is the asterisk, you should enter "c:\\windows\\?\**".

When you have finished editing the permissions, you should save the file. To save the permissions as an .ini file, choose Save from the File menu. To save the edited permissions to a zone, choose Save to Zone from the Zone menu, which will modify the permissions that are recognized by Internet Explorer 4.0 and later for the specified zone.

For more information on .ini files, see the Sample Permissions INI File and the Java Permissions INI Values Reference. To learn how .ini files are used with the signcode tool, see the Signing a Cabinet File with Java Permissions Using Signcode article.

Java Class Viewer (qvue)

qvue [options] classname

Prints out class method signatures and identifies .class files that were generated from a type library.

Parameter Description
options Can be used with:
/s | Only prints the type of class (whether a Java class or a class generated from a type library). Does not print the class methods.
classname | Specifies the name of the .class file to inspect. Qvue supports wildcards.

Remarks:

The qvue utility is similar to the jactivex utility's /javatlb /u option, which prints out class file summaries. The qvue utility is convenient for selecting the correct class file to use when the class files are generated from a type library using jactivex.

Win32 Resource File Merging Utility (resmerge)

resmerge [-a] target filename appended file 1 appended file 2 ...

The resmerge utility combines multiple Win32 resource (.res) files into a single file.

Parameter | Description
options The resmerge utility supports the following option:
-a Appends the specified resource files to the first named resource file (the target file).
target filename | The primary file that other files will be appended to.
appended files | Additional files that are appended to the target file.

Cabinet File Signing Utility (signcode)

signcode [options] -j JavaSign.dll [-jp level] [more options] filename

Signs a cabinet file with Java permissions to give developers more detailed control over the security restrictions placed on their applet when it is used over the Internet or an intranet.

For more information, see Signing a Cabinet File with Java Permissions Using Signcode.

Parameter Description
options SignCode accepts the following command-line options:
/j JavaSign.dll | The option that tells the signcode utility to use Java permission information.
/jp level Level is an optional string that tells what level of permissions to encode in the cabinet file. This must occur immediately after the /j parameter. You can use any of the following flags:

Low Medium High LowX MediumX HighX

If the string is not one of these six, it is accepted as the name of an .INI file that specifies the permissions to encode. You can create this .INI file by hand, following the example provided by the sample permissions .INI file, or you can use the piniedit tool to generate the .INI file for you. See Using Signcode with Java Permission Information and the .INI Permissions Reference for more details on custom permissions.

If the /jp option is not specified, a default level of LowX will be used. The exact permissions associated with these flags were previously described in Cabinet File Permission Levels and Cabinet Files and ActiveX.

Other Options
/spc | SPC file containing software publishing certificates.
/v | Pvk filename containing the private key.
/k | Key container name.
/n | Text name representing content of the file to be signed.
/i | Place to get more information on content (usually a URL).
/p | Name of the cryptographic provider on the system.
/y | Cryptographic provider type to use.
/$ Signing authority of the certificate, either individual or commercial. The default is using the certificate's highest permission.
/a | Hashing algorithm for signing, either md5 or sha (the default is md5).
/t | TimeStamp server's http address.
/c | Software publishing certificate file.
/s | Certificate store containing certificates (the default to my+root+ca+spc).
/sp | Add all the certificates in the chain or add only to spc store (the default is chain).
/r | Location of the certificate store in the registry, either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER. The default is HKEY_CURRENT_USER.
/add | Add the certificate in the store in signing.
/addr | Location of the added cert store in the Registry, either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER (the default is HKEY_CURRENT_USER).
/x | Does not sign the file. Only timestamps the file.

Remarks:

To add the Java permission information into the signature, add the /j JavaSign.dll option to signcode. You may also specify the /jp option for finer control over the exact permissions in the signature.

Java Window Viewer (wjview)

wjview [options] classname [arguments]

Executes Java applets and applications from the command line and spawns a separate window process.

Parameter | Description
options Can be a combination of the following:
/a | Invokes the use of the Microsoft AppletViewer. Applets viewed with the Microsoft appletviewer function the same as when viewed with a browser, including sound, loading, security features, and so on. When the appletviewer switch is used, all other remaining command-line tokens become parameters that are used by the appletviewer.
/cp classpath | Sets the classpath environment variable. For more information, see CLASSPATH Environment Variable.
/cp:a path | Appends the path entered at the end of the class path environment variable and inserts a semicolon between them.
/cp:p path | Inserts the path entered and a semicolon at the beginning of the classpath environment variable.
/n namespace | Provides a namespace in which to run an application. This allows Java packages with identical names to exist without conflict, if they are in separate namespaces. The Microsoft JPM stores packages in a global namespace and searches there for packages if no namespace is specified to its API elements (for example, the contents of classes.zip is stored in the global namespace). Note, however, that applications running in the name space specified with the /n switch cannot access other namespaces.
/v | Verifies all invoked methods (normally, only methods from untrusted loaders are verified).
classname | Name of the .class file to execute. Do not use the .class extension with this filename.
arguments | Command-line arguments to be passed to the .class file supplied in classname.

Remarks:

Use this utility to launch window-based Java applications and applets. This utility is the same as the jview utility, with the exception that wjview runs the application as a separate graphical user interface (GUI) process and does not use or require a console window. Consequently, you do not use wjview for Java applications that require output to or input from the console window.


Introduction to Jexegen

Working with MS VM
In this topic

* Basic Operation

* Reference to Jexegen Command-Line Options

* Working with Package Names

* Command Files

* Custom Stubs

Tools | Previous | Tools | Next
Jexegen Reference | Previous | Tools | Next

Introduction to Jexegen

The jexegen tool is used to create Microsoft® Win32® executables from Java applications. The class files for the application are bound into the executable, and do not need to exist anywhere else on the drive. Note that the Microsoft Win32 VM for Java is required to run programs generated by the jexegen tool.

Basic Operation

You must specify on the jexegen command line what class files you want to include and the name of the main class file. For example, you have a Java application that consists of three class files—A.class, B.class, and C.class—and that class A contains the application's entry point (the main method). To generate an executable, you would run the following command from the directory that contains the class files.

jexegen /main:A /out:MyApp.exe A.class B.class C.class

In this case, the jexegen tool creates the file MyApp.exe, which contains your Java application.

The jexegen tool uses virtual paths in command line arguments. It is important that the jexegen tool is in your CLASSPATH environment variable, as well as the classes you are working with. If jexegen is not in the CLASSPATH, the utility must be run from the directory where the associated classes are located (in particular, any classes that contain main()), or an application error occurs. For example, the following command will not work.

C:\>\SDK-java\bin\jexegen /v c:\_java\BsetEditor\*.class
   c:\_java\BsetEditor\sun\audio\*.class ...

The jexegen utility is running directly from bin, and absolute paths are used. This results in an "Ignoring file.." message. You can avoid this by adding jexegen to your CLASSPATH and by using virtual paths in command line arguments. Also note that the classes you include on the command line need only be a package name (for more information, see Working with Package Names), as the following example shows.

C:\_java\BsetEditor\>jexegen /V com.ms.ui.*.class ...

Reference to Jexegen Command-Line Options

jexegen [options] [@command file] files

The options are as follows:
/main:classname | (Required) Sets the name of the main class file. This class must contain the public static method main. The name specified on the command line must be the same as the class's internal name; it is case-sensitive and you must separate package names with periods. For example, if you usually run your application with the command line: view MySample.Sample then the appropriate switch for jexegen would be: /main:MySample.Sample
/nomain | Indicates that you do not want to specify a main class file. This option is useful only in conjunction with the /raw or /bindto option.
/base:dir | Changes the base directory; used to determine package names of specified class files. When used with the /raw or /bindto option, this option specifies the base directory that file operations are relative to. By default, package names and file operations are determined relative to the current directory. If used more than once on the command line, all /base options are relative to the original (current) directory.
/out:filename | Specifies the name of the output file.
/r | Indicates that jexegen should recurse into subdirectories when searching for the specified class files. By default, subdirectories will not be searched.
/r- | Used to turn off subdirectory recursion. Only useful if the /R option has already been used. As an example, consider the following partial command line: /r This*.class /r- That*.class This example command line instructs jexegen to find all class files matching This*.class in the current directory and all subdirectories, and all files matching That*.class only in the current directory.
/v | Provides detailed output.
/w | The generated executable will not have an associated console window. This option will be useful only for graphical applications.
/bindto:stub | Specifies the executable (.exe file) or dynamic-link library (DLL) to bind the class resources to.
/raw | Saves resource data to a file and does not generate an executable. The data file generated is of the appropriate format to be used with the IJavaExecute2::SetClassSource method.

Working with Package Names

Be sure to preserve package names when using the jexegen tool. The package names of the classes to be bound into the executable are determined by the directories in which those class files are located. Therefore, you must run the jexegen tool from a directory above the directory containing the class files.

For example, a Java application consists of two class files, Main.class and Helper.class, which exist in a package called Sample. The files are in the c:\classes\Sample directory.

  c:\classes\Sample\Main.class
  c:\classes\Sample\Helper.class

If the command jexegen /main:Main *.class is run from the c:\classes\sample directory, the generated executable will not work correctly: The names of the class files contained within the executable will not reflect their real names. The correct way to build the .exe file is to run jexegen /main:Sample.Main Sample/*.class from the c:\classes directory. To verify that the correct names are included, you can use the /v option to observe the names of class files that are stored in the executable.

By default, the current directory is used as the base directory. Package names are determined relative to the base directory. You can use the /base option to specify an alternative base directory.

Command Files

As an alternative to specifying all the class files and options on the jexegen command line, you can use a command file. A command file contains a list of options and file specifications, one per line. For example, this command line:

C:\..\>jexegen /main:myapp /out:myapp.exe
             Myapp.class Fido.class Fido2.class Fido3.class

can be replaced with the following command line:

 jexegen @myapp.dat

where the contents of the file myapp.dat is:

  /main:myapp
  /out:myapp.exe
  Myapp.class
  Fido.class
  Fido2.class
  Fido3.class

Custom Stubs

The jexegen tool works by binding the class files to a small stub program. This stub simply instantiates the Microsoft VM, and uses the IJavaExecute2::SetClassSource method to tell the VM that it should look for class files inside the executable.

If the built-in stub is insufficient for your needs, you can provide your own stub file. For example, a custom stub could contain version information or a custom icon. You can use the /bindto option of the jexegen tool to add the class resource data to your own stub program. Alternatively, you can use the /raw option and reference the resulting data file from your program's resource script.

The SDK for Java includes the source code for a sample jexegen stub.


Using Jactivex's JavaTLB Compatibility Support

Working with MS VM
In this topic

* Using the Jactivex Command-Line Tool

* Upgrading to Jactivex from JavaTLB

* @com Directives

* Implementing Automation Objects in Java

* Jactivex Extended Command-Line Options

Tools | Previous | Tools | Next
Using Jactivex's JavaTLB Compatibility Support | Previous | Tools | Next

Using Jactivex's JavaTLB Compatibility Support

The jactivex utility is used for hosting automation-enabled ActiveX controls in Java, and generating .java files for the classes and interfaces that are described by a type library. These .java files, once compiled into .class files, allow Java programs to use COM (Component Object Model) services. Although the default operation of the tool is ActiveX Control manipulation in Java, this documentation only covers tool usage for features originally supported by the javatlb and jcom tools (which this tool replaces).

Using the Jactivex Command-Line Tool

To use a COM class from Java, you must first import it; this means creating a Java class that represents the COM class in the context of Java. The jactivex tool uses the COM type library information to create Java classes that represent COM interfaces.

A type library is a mechanism defined by COM to define type information. Each type library contains complete type information about one or more COM entities, including classes, interfaces, and dispinterfaces. For more information about type libraries, see the Microsoft Platform SDK. To find out how to use the interfaces that are available from a particular programmable control or automation server, see the documentation provided by that vendor.

Note The jactivex tool is virtually identical to the jcom tool, and similar to the javatlb tool. The jactivex tool generates Java source code (.java) rather than the .class files that javatlb generates. The generated Java source requires new functionality not present in older versions of the compiler in Microsoft® Visual J++™. To learn about upgrading from older versions of this tool, see Upgrading to Jactivex from JavaTLB.

To use the jactivex tool for low-level Java/COM integration (that is, enabling the JavaTLB behavior), use the /javatlb switch and provide the name of a type library as follows:

jactivex /javatlb <filename>

Filename is the filename of the type library (*.tlb, *.olb, *.ocx, *.dll or *.exe).

Note If you specify an .ocx file without the /javatlb switch, the jactivex tool will generate a JavaBean wrapper for the ActiveX control (its default operation).

For example, consider this command line, which first creates a \Widgets subdirectory underneath the trusted library directory (specified by the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\TrustedLibsDirectory):

jactivex /javatlb widgets.tlb

If the trusted library directory is \Windows\Java\Trustlib, the preceding command creates the directory \Windows\Java\Trustlib\Widgets, and fills it with .java files. A separate .java file is created for each class, structure, enumeration, and interface described by the widgets.tlb type library. The names of packages and directories created by jactivex contain only lowercase letters.

If the type library contains an importlib statement, jactivex creates a separate Java package in a separate directory for the imported type library.

Upgrading to Jactivex from JavaTLB

Jactivex has been designed for backward compatibility with the javatlb tool. In most cases, upgrading to jactivex should require only three modifications to your makefiles or build scripts:

  1. Replace references to javatlb with references to jactivex.
  2. Add the appropriate command-line switch (/javatlb) in any scripts to access jactivex features.
  3. Upgrade to a compiler for Java that recognizes the new @com directives generated by jactivex. If you are using the Visual J++ compiler (jvc.exe), you must use version 1.02.3920 or later to compile the output from jactivex. Earlier versions of jvc will not issue a compile-time error, but the class files they generate will not work. For more information about the @com directives, see @com Directives.

The following table shows the correspondence between jactivex and javatlb command-line options:
Javatlb | Jactivex | Notes
/d dir | /javatlb /d dir | Option works identically
/p package | /javatlb /p package | Option works identically
/p:b- | /javatlb /p:b- | Option works identically
/X:m- | /javatlb /X:m- | Option works identically
/U | N/A | Not supported in jactivex*
/U:T | N/A | Not supported in jactivex*
*Jactivex does not support the generation of summary.txt files as did javatlb because jactivex generates human-readable .java source.

@com Directives

Jactivex generates Java source files that use a new Microsoft extension called the @com directives. These directives must appear inside specially formatted comments that are similar to the javadoc documentation comments syntax. A typical @com directive generated by jactivex might look like the following example:

/** @com.method(vtoffset=4, dispid=100, type=METHOD, name="Hello")
    @com.parameters() */
    public void Hello();

The @com directives are important and are used to generate the extra information needed by the Java/COM integration subsystem in the Microsoft Win32 VM for Java. Therefore, the compiler used to compile jactivex's output must process these directives. If you are using the jvc.exe, you must use version 1.02.3920 or later to compile jactivex's output. Earlier versions of jvc will not issue an compile-time error, but the class files they generate will not work.

Implementing Automation Objects in Java

There are two ways to implement automation objects in Java:

  1. Use automatic IDispatch
  2. Use the /javatlb /cj command-line option to generate a .impl file.

The following sections describe each of these methods.

Using Automatic IDispatch

The Microsoft VM now implements IDispatch automatically for almost all Java objects (previously, it did so only for applets). This means that tools such as jactivex are no longer necessary simply to script a Java object from an automation controller such as Microsoft® Visual Basic® or Microsoft ® Visual Basic® Scripting Edition (VBScript). To implement a simple automation object in Java:

  1. Implement the Java object and compile it.
  2. Register it using javareg (version 2.0).
  3. Ensure that the Java class is visible in the CLASSPATH environment variable.

Using the /javatlb /cj Option with Jactivex

The second approach uses jactivex to generate COM interfaces from type libraries. This approach requires more work but allows you to ensure that the exposed interface matches the typelib description exactly.

The /javatlb /cj approach requires an interface definition language (IDL) or object definition language (ODL) file describing your interface and a coclass, which uses the [default] attribute to define the default interface. The following example shows a simple IDL file for the IWidget interface:

[
       object,
       uuid(...),
       helpstring("IWidget"),
       pointer_default(unique)
           ]
           interface IWidget : IUnknown
           {
        HRESULT add([in] long x, [in] long y, [out,retval] long*pz);
           };

    [
        uuid(...),
        helpstring("CWidget")
    ]
    coclass CWidget
    {
        [default] interface IWidget;
    };

When you invoke jactivex on the typelib using the /javatlb /cj switches, Jactivex generates an extra file named CWidgetImpl.java, which looks as follows:

public class CWidgetImpl implements IWidgetDefault,com.ms.com.NoAutoScripting
    {
        public int add(int x, int y)
                {
           throw new com.ms.com.ComFailException(0x80004001);  //E_NOTIMPL
                }
    }

To create a Java implementation of CWidget, you can either extend the class or use CWidgetImpl itself as a template for MyWidget (this is preferable as it eliminates a superclass). The following shows the superclass implementation:

public class MyWidget extends CWidgetImpl
    {
        public int add(int x, int y)
        {
            return x+y;
        }
    }

Jactivex Extended Command-Line Options

The jactivex tool replaces both javatlb and jcom. By default, the tool is used to host automation-enabled ActiveX controls in Java. To access typelib features, you must use the /javatlb command-line switch to activate the other switches described in the following section.

Translation

/javatlb
Specifies typelib translation. Use this switch combined with others to access typelib features of the jactivex tool.
/b
Uses the JavaBeans design pattern for properties. For example, by default, a read-write property named "a" becomes mapped to property accessor methods named "geta" and "puta". If the "/b" flag is specified, the names "getA" and "setA" will be used instead. In addition, the property is exposed to COM by the name "A" only. It is not possible to access the names "getA," or "setA" from COM (these names were exposed only for compatibility with javatlb).
/G3.1
Prevents use of features that are not supported by the VM in Microsoft® Internet Explorer version 3.1. Disabled by default.
/G4
Prevents the use of features that are not supported by the VM in Internet Explorer version 4.0. Disabled by default; this switch is reserved for future use.
/r
Causes jactivex to register all type libraries that are mentioned on the command line.
/w
Disables all warnings.
/WX
Treats warnings as errors. This prevents any output files from being generated if a warning is reported.
/x2
Maps VT_I2 and VT_UI2 to Java char rather than Java short. By default, these types are mapped to Java short for compatibility with javatlb.
/xc
This causes all coclasses in the type libraries to be ignored.
/xd-
Suppresses creation of default versions of the .java files. Jactivex normally creates two .java files for each dispinterface: one that is used when the interface is the default for a coclass, and one that is used when the interface is not the default. The default versions of the java files are needed only to implement the interface using Java. Suppressing the creation of default versions can speed up compilation considerably on large type libraries.

Do not use this switch with the /cj option.

/xh
Modifies translation of HRESULT types so that only HRESULT return types that have the high (FAIL) bit set cause Java exceptions. Non-failing HRESULTs (such as S_FALSE) are treated as if they were S_OK.

Warning This feature is not supported by versions of the Microsoft VM prior to Internet Explorer 4.0. Classes built with this option set will not load on versions prior to version 4.0. If your class must run on versions prior to version 4.0, do not use this switch. Callers of this method will need to catch ComSuccessException to avoid the exception.

/xi
Causes the method declarations and COM declarations to be duplicated in the coclass files. This simplifies using COM objects from Java because default interface methods can be called directly on the object without first casting to an interface pointer. That is, without the /xi option you would have to write code like this:

IBeeper b = (IBeeper)new Beeper();
b.beep();

Using the /xi option, this can be simplified as follows:

Beeper b = new Beeper();
b.beep();

In addition, this form speeds up method invocation. The trade-offs are that the coclass files are larger and any manual changes to the information generated by jactivex must be made in both the coclass and the interface.

/X:m-
Disables thread switching. By default, the Microsoft VM assumes that all COM objects passed as parameters are non—thread-safe and performs background thread-switching to ensure that such objects are called on the correct thread. Using this switch disables this extra thread-switching. Typically, you will use this switch when you have designed a new thread-safe COM library.

Output

/cj
Generates a template file for each coclass that can be edited to implement that coclass in Java. The file is named <coclass>Impl.java. This file includes all the required methods with simple implementations that just throw an E_NOTIMPL exception. To create a Java class that implements the coclass, replace the class name and fill in the method implementations.
/d directory
Specifies the base directory where the package directory will be placed. For example, the following command will create the widgets package directory in the C:\MyPackages directory and place all generated .java files in C:\MyPackages\Widgets.
jactivex /javatlb /d c:\mypackages widgets.tlb

By default, the base directory is the value specified in the registry HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\TrustedLibsDirectory. The installation of the Microsoft VM sets this to %WINDIR%\java\trustlib.

/e
Generate files only for type libraries explicitly listed on the command line. This switch allows you to set command-line switches on a per-typelib basis. This may cause generation of .java files that reference unresolved names or packages.

If the /e option is not specified, jactivex will recursively compile type libraries needed to resolve all references.

/j
Generates Java source files without the extended COM information. As a result, these source files can be browsed more easily and will compile. They will not, however, integrate with COM if they are loaded into the Microsoft VM.
/p package
Specifies the target directory for .java files generated by jactivex as shown in the following example.
jactivex /javatlb /p gremlinsoft widgets.tlb

This example command line places the .java files in \windows\java\trustlib\gremlinsoft\widgets directory. With this option, you can define, for example, a company-specific directory tree that contains the .java files for all the COM objects produced by your company. The package parameter can have multiple levels. For example, the following command would place the .class files in the directory \windows\java\trustlib\gremlinsoft\toolworks\widgets.

jactivex /javatlb /p gremlinsoft.toolworks widgets.tlb

To use these classes in your Java program, specify an import statement of the following form in your source code:

import gremlinsoft.toolworks.widgets.*;
/p:b[-]
Use this option to include (or exclude) the basename as the package for the converted class. For example, if you are converting widgets.tlb to Java classes, this option will create a package called widgets. Since the default is to use the basename as the package, this option is generally used with the dash (-) following it to disable the automatic creation of the package directory; this places the created .java files in the default package directory (java\trustlib or the directory specified in the /d option). For example, the following command places all class files in the c:\mypackages directory:
jactivex /javatlb /p:b- /d c:\mypackages widgets.tlb

Miscellaneous Switches

/?
Prints a brief summary of command-line options.
/l lstfile
Generates a response file for jvc that lists every .java file created by jactivex. The response file is a text listing of Java files so it can also be used to find out where and what files jactivex created.

For example, the following command line creates a file called mylist.lst, which can then be used as an input file to jvc:

jactivex /javatlb /l myfiles.lst widget.tlb
JVC @myfiles.lst

If a relative path is given for the response file, it is placed in the current directory. Its location is not affected by the /d option.

/n jnffile
Specifies an optional .jnf file, which supplies extra information on how to convert the type library. The .jnf file is a text file that has the following format:
[Custom]
    <typename>=<javatype>,<javamarshalertype>
        ...

The purpose of the .jnf file is to inform jactivex that certain types are to be marshaled using a COM Custom Marshaling hook class.

/nologo
Disables the startup banner.


Introduction to Java/COM Custom Marshaling for User-Defined Data Types

Working with MS VM
In this topic

* What Is Custom Marshaling and Who Uses It?

* An Example of Custom Marshaling

* How JAVA/COM Custom Marshaling Works

* Hook Class Overview

* Hook Class Implementation

* Using Template Files to Write a Hook Class

* EXAMPLE 1: FixedPtMarshaler (The Basic Hook Class)

* EXAMPLE 2: VarStrMarshaler (Embedded Resources)

* EXAMPLE 3: PointMarshaler (Mutable Java Objects)

* EXAMPLE 4: RectMarshaler (Support for Custom Allocation)

* EXAMPLE 5: AnsiMarshaler (Variable-sized data types)

* Running and Building the Sample Client

Tools | Previous | Tools | Next
Using Jactivex to Create a User-Defined Type for Java/COM Marshaling | Previous | Tools | Next

Introduction to Java/COM Custom Marshaling for User-Defined Data Types

This article explains how to implement custom marshaling of user-defined types between Java and COM. Basically, this involves writing a hook class to do the marshaling, and using the jactivex tool with the /javatlb command-line switch to create a Java type library information file (.jnf) that describes the custom interface.

A hook class is a special class that you write for each user-defined type you want to marshal from COM to Java. It contains the code that actually does the marshaling and translates the COM type to a Java type and the Java type to a COM type. Much of this article addresses what a hook class is and how to author one.

Jactivex is a tool that can create Java libraries from existing COM interfaces. COM interfaces are based on type libraries, so a Java type library is a file that maps user-defined types in existing COM type libraries to hook classes.

What Is Custom Marshaling and Who Uses It?

Marshaling of data types is essential whenever a program spans languages, since data types are never exactly the same in any two languages. Since the Microsoft VM provides the ability to wrap COM libraries as Java classes, marshaling must occur between Java classes and COM type libraries. The Microsoft VM supports a certain level of intrinsic marshaling by default.

As an example, suppose you have a COM library that uses various data types as parameters and return values for its methods. For these methods to be callable from Java, the data types need to be converted between the COM types and Java types. For some types, like integers, floats, booleans, and strings, the Microsoft VM for Java provides intrinsic marshaling support that automatically does the type conversion.

In addition to the conversion work, the COM types must be represented as Java types to be callable from Java. This requires a Java .class file that contains type declarations in Java format. This class file is usually created by running a type-conversion tool such as jactivex (Jcom or Javatlb in older versions of the SDK) on the type library of the COM server. These conversion tools generate the correct type mappings for all types that are supported by the intrinsic marshaling of the Microsoft VM.

The Microsoft VM does not, however, have intrinsic support for complex COM library data types, such as C structures. To marshal such data types requires that you create a user-defined Java type and write a hook class that does the marshaling.

Since jactivex cannot automatically create type mappings that work for user-defined types, you will need to provide jactivex with information on how to generate the Java type declarations. This is done by creating a Java type library information file (.jnf) file, which describes your custom data types, and passing it to jactivex it creates the COM library class header file.

The .jnf file has the following format:

[Custom]
<TypeLib Type>= <Java Type>, <Hook Class>

Where:
TypeLib Type | A user-defined type declared in the COM type library.
Java Type | The Java type to map to the COM type.
Hook Class | The class that does the translation.

An Example of Custom Marshaling

The following is an example of how to marshal a simple structure type between a COM type library and Java. Suppose you have a simple COM library, represented by the following pseudo-ODL (Object Description Language) example file.

typedef struct POINT
  { long  x;
    long  y;
  } POINT;

interface IPlotter : IUnknown
  {
    HRESULT DrawLine([in] POINT *start, [in] POINT *end);
  }

coclass CPlotter
  {
    [default] interface IPlotter;
  }

To implement or access this library with Java, you would use the following procedure.

  1. Write a plotter.idl or plotter.odl file for the COM library and pass it to the mktyplib tool (which can be found in Microsoft Visual C++) to generate a type library file called plotter.tlb.
  2. Write a .jnf file that describes all the user-defined types. Here is what the .jnf file would look like for the POINT type:

    PLOTTER.JNF

    [Custom]
POINT = java.awt.Point, PointMarshaler

    This declaration instructs jactivex to substitute the Java type java.awt.Point when it encounters a reference to the type named POINT in the type library. It also tells the Microsoft VM to use the PointMarshaler class as the hook class for the POINT type.

    Important: The .idl and .odl files differ on how they expose the type name. For example, consider the following type definition:

       typedef struct _Foo
       {
         ...
       } FOO;

    If you are writing an .idl file, you need to put the struct tag name ("_Foo") in the .jnf; if you are writing an .odl file, you must put the type definition name ("FOO").

  3. Pass the names of the type library file (.tlb) and the Java type library information file (.jnf) file to jactivex using the following command:
    Jactivex /javatlb /n plotter.jnf plotter.tlb

    (Remember that for jactivex, like its predecessor Javatlb, the default output directory is in your TrustLib directory, so you may want to use the /d switch to specify a base directory.)

    Jactivex will create two .java files that include special @com javadoc syntax required for the jvc compiler to generate the extra bits needed by the Microsoft VM to treat these files as Java/COM classes. For example, the name of the PointMarshaler class is part of these bits.

    For this example, jactivex generates two files: CPlotter.java (representing the coclass), and IPlotter.java (representing the interface). Excluding the @com javadoc syntax, emitted by jactivex and used by the jvc compiler, the generated source for IPlotter.java looks like this:

    // In the actual file, you will see extra syntax that
// represents the extra bits needed for the VM Java/COM
// marshaling layer.

interface IPlotter
  {
     public DrawLine(java.awt.Point start, java.awt.Point end);
  }
  4. Compile CPlotter.java and IPlotter.java using jvc. You must use jvc version 1.02.3920 or later, which interprets the extra @com syntax that jactivex generates. This version of jvc is included in the /BIN directory of the Microsoft SDK for Java 2.5 release.
  5. A Java application can now load and use an installed Plotter library by invoking:
    IPlotter plotter = (IPlotter)(new CPlotter());
plotter.DrawLine(new Point(x1,y1), new Point(x2,y2));

    A Java class can also implement the Plotter library by using IPlotter as shown in the following example:

class MyPlotterImp implements IPlotter
{
   void DrawLine(Point start, Point end)
   {
      ...
   }
}

The sample files for this article can be found in the SDK for Java 2.5 release. The sources for a working copy of this example is under the SKD-Java.20\Samples\CustDoc\plotter subdirectory. The sources for PointMarshaler are under the \CustDoc\point subdirectory. To execute the sample, change the current directory to the \CustDoc\prundir subdirectory, and run the go.bat file.

How JAVA/COM Custom Marshaling Works

How does the Microsoft VM for Java actually marshal the call from Java to Plotter? In the interface file IPlotter.class, there are special bits associated with the start and end parameters that indicate that these parameters are a user-defined class and that the hook class is PointMarshaler.class. These bits are all generated by jactivex.exe.

When a Java application invokes the DrawLine method, the Microsoft VM loads the PointMarshaler class (if it hasn't already). It then looks for a public static field named cbByValSize, the presence of which indicates that the COM type is a fixed-size. In this example, PointMarshaler happens to expose this field. It is equal to 8, which is the size (in bytes) of a POINT structure.

The Microsoft VM, therefore, allocates 8 bytes of space on the stack, and invokes another public static method on PointMarshaler called copyToExternal. The Microsoft VM passes the copyToExternal method a pointer to this 8-byte space and a reference to the end parameter, which in this case is java.awt.Point. Be aware that the pointer to the 8-byte space is passed as an integer value.

With this information, copyToExternal translates the java.awt.Point to a POINT structure in that 8-byte space. The same routine is repeated for the end argument. The COM DrawLine method ultimately receives a pointer to the two stack buffers as its start and end parameters. Since both parameters were marked [in], there is no further action for this simple type.

Note: The previous explanation was necessarily simplified for brevity. Much of the hook class analysis implied here is done prior to any method calls and does not actually occur at method call time.

Hook Class Overview

Aside from the extra step of writing a hook class and listing your data types in the .jnf file, the previous procedure is no different from that of integrating any other COM library with Java.

As previously discussed, a hook class is a collection of static methods and fields packaged as a Java class. The hook class must be installed and visible to the classpath on any system where the user-defined types are used. Otherwise, hook classes remain fairly hidden. The Microsoft VM loads the hook class as part of loading a jactivex-created interface file that references them, and invokes methods on the hook class to marshal the user-defined types.

All hook methods and fields are static (that is, per-class, rather than per-instance). The Java/COM integration layer of the Microsoft VM will never create an instance of a hook class. There are approximately 10 fields and methods defined by the Hook Class Specification. All hook members, however, are either optional or have reasonable defaults. Most hook classes will need only to implement a subset of the members.

The following list shows the responsibilities of a hook class:

  1. Specifying the Java type (referred to generically as JTYPE). JTYPE can be a primitive type (int, double, and so on) or a reference type (objects and arrays).
  2. Specifying the size, in bytes, of the COM type (referred to generically as ETYPE). ETYPE can be variable-sized, in which case, the hook class will indicate this fact by not offering a size.
  3. Providing code (methods) to translate JTYPEs to ETYPEs and back.
  4. (Optional) Providing destructor code for ETYPEs (to release embedded resources).
  5. (Optional) Providing code to allocate and free ETYPEs.

In turn, the Microsoft VM is responsible for calling the appropriate hook methods at the right time whenever ETYPEs are passed to or from COM methods. Once the hook class is written, the VM automatically supports passing ETYPEs (if ETYPE is fixed-size), ETYPE*, and ETYPE**, as well as returning ETYPE*. The VM also implements the correct semantics for [in], [out], [in,out], and [out,retval] type library attributes, which jactivex passes along using the extra bits in the .class file. An [out] attribute or double indirection is mapped to a one-element array of JTYPE rather than to JTYPE itself.

Hook Class Implementation

Although hook classes are packaged as Java classes, they cannot be written in Java. Hook classes must receive and pass machine addresses (pointers). Java methods can receive pointers by masquerading them as an int type. The Java language offers no way, however, to dereference, allocate, destroy, or otherwise manipulate pointers. For this reason, use of the Raw Native Interface (RNI) is a necessity for authoring hook classes. RNI allows Java methods to be implemented as C functions inside a DLL. RNI also offers a small set of APIs that can be called from C to create, manipulate, and destroy Java objects.

Using Template Files to Write a Hook Class

The SDK for Java contains samples that show how to write hook classes to achieve custom marshaling. These samples are installed in several directories under the SDK-Java.20\Samples\CustDoc directory. All directory paths referenced here are in relationship to the CustDoc directory.

The easiest way to start is by copying the files under the template subdirectory to a new directory. The key files in template are:

  • TemplateMarshaler.java — a skeleton hook class
  • TemplateMarshaler.c — contains a blank C function for each method
  • lateMarshaler.def — exports the C functions in template.c

To make the files compilable, you must follow the instructions in each of the comments marked "TODO" in TemplateMarshaler.java and TemplateMarshaler.c. This involves replacing ETYPE and JTYPE with your particular type, and uncommenting some optional methods.

The template contains C functions for eight hook methods. The comments inside each function describe what that hook function is supposed to do. We will go into more detail about this as we proceed through the examples. First, a few salient points about the hook functions as a whole:

  • Each C function starts with an unused parameter "OBJECT*x". This is an artifact of RNI and will always be NULL for a static method. This parameter can be ignored.
  • Several C functions have parameters "JTYPE javaval". "JTYPE" should be replaced throughout by the C type that represents your Java type. To find out what C type to use, consult the table in TemplateMarshaler.c or use msjavah.
  • Several C functions have parameters "PPETYPE ppetype" (a pointer to a pointer to an ETYPE). These parameters are represented as "int" in the Java method, but they are true pointers.
    Important All pointers passed to hook methods are double-indirect ETYPE (PPETYPE). For many methods (such as releaseExternal), this will seem like an unnecessary level of indirection. The reason ETYPE is always double-indirected has to do with an obscure feature of hook classes that allows you to redefine the size and nature of A POINTER to ETYPE. This is a very arcane use of hook classes and will not be mentioned again in this primer. Just remember that you will, in some cases, have to deal with an extra level of indirection because of this.
  • Except for the functions that return Java types, hook methods return VOID or return a native pointer through an output buffer. To indicate failures, hook methods should use SignalError or SignalErrorPrintf, which cause RNI to throw a Java exception upon the exit of the C function. Remember that SignalError and SignalErrorPrintf return to their callers, so you must arrange to exit from your C function immediately after calling these APIs.

EXAMPLE 1: FixedPtMarshaler (The Basic Hook Class)

The FixedPtMarshaler sample is about the simplest useful hook class. It exposes only two methods and one field. The JTYPE is "double", and the ETYPE is the Win32 FIXED structure for representing fixed point fractions, as shown here:

        struct FIXED {
            WORD   fract;
            short  //covvalue;
        } FIXED;

The source code for FixedPtMarshaler can be found under the \fixedpt directory. The executables (FixedPtMarshaler.class and FixedPtMarshaler.dll) are under the \rundir directory.

The members implemented by FixedPtMarshaler are as follows:

      public FixedPtMarshaler {

          public static int cbByValSize; // set of sizeof(FIXED) = 8

          public static double toJava(int ppFIXED, int flags)
          {
             // convert **ppFIXED to a double
             // return the double
          }

          public static void copyToExternal(double javaval,
                                            int    ppFIXED,
                                            int    Flags)
          {
             // convert double to a FIXED
             // copy the FIXED to **ppFIXED
          }

      }

Even with only these methods, this hook class can now be used in the following ways:

COM Type | Marshaled to Java As
HRESULT func([in] FIXED) | func(double)
HRESULT func([out,retval] FIXED*) | double func()
HRESULT func([in] FIXED*) | func(double)
HRESULT func([out] FIXED*) | func(double[])
HRESULT func([in,out] FIXED*) | func(double[])

Note that when using this hook class in a .jnf file, you should preceed the Java type double with the const modifier as in the following example:

    [Custom]
    FIXED=const double, FixedPtMarshaler

If you do not include the const modifier, jactivex will interpret that [out] parameters are intended to pass along single values passed in by the caller (as a side-effect), rather than passing a new value out using a single-element array. That is, jactivex would map the FIXED type as follows:

COM | Marshaled to Java As
HRESULT func([out] FIXED*) | func(double)

This is not what you want. Because double is immutable, this method prototype cannot possibly return a value to the caller.

EXAMPLE 2: VarStrMarshaler (Embedded Resources)

The basic hook class, demonstrated by FixedPtMarshaler, assumes that ETYPE contained no embedded pointers or handles to allocated resources that need to be freed when ETYPE is no longer needed. In C++ terms, if ETYPE is a class in a basic hook class, it is assumed ETYPE does not have a destructor. Some structures, however, do need to clean up embedded resources. A well known example is the VARIANT structure used in ActiveX Automation. A VARIANT is a fixed-size structure, yet it can have allocated objects such as BSTR, SAFEARRAYS and COM objects referenced by it. The "destructor" for a VARIANT is the VariantClear API, which checks the type of the variant and performs the appropriate cleanup (for example, freeing the BSTR, freeing the SAFEARRAY, calling Release on the COM object, and so on).

Arranging for proper cleanup of embedded resources requires only one new method: releaseByValExternal.

The VarStr marshaler example maps VARIANT types, confining itself to only one case: marshaling BSTR VARIANT types to Java String objects. That is, the JTYPE is String, and the ETYPE is as follows:

        struct {
            short vt;           // Always VT_BSTR for this example
            short unused;
            short unused1;
            short unused2;
            BSTR  bstrVal;      // Points to characters in BSTR
            long  unused3;      // never used in this example.

        } VARIANT;

The source code for VarStrMarshaler can be found under the \varstr directory. The executables VarStrMarshaler.class and VarStrMarshaler.dll are under the \rundir directory.

The members implemented by VarStrMarshaler are as follows:

public VarStrMarshaler {

    public static int cbByValSize; // set of sizeof(VARIANT) = 16

    public static String toJava(int ppVARIANT, int flags)
    {
       // convert **ppVARIANT to a String
       // return the String
    }

    public static void copyToExternal(String javaval,
                                      int    ppVARIANT,
                                      int    Flags)
    {
       // convert String to a VARIANT
       // copy the VARIANT to **ppVARIANT
    }

    /* NEW! */
    public static void releaseByValExternal(int ppVARIANT, int Flags)
    {
       SysStringFree( (*ppVARIANT)->bstrVal );
    }

}

This hook class can be used in the following ways.

COM Type | Marshaled to Java As
HRESULT func([in] VARIANT) | func(String)
HRESULT func([out,retval] VARIANT*) | String func()
HRESULT func([in] VARIANT*) | func(String)
HRESULT func([out] VARIANT*) | func(String[])
HRESULT func([in,out] VARIANT*) | func(String[])

As before, String is immutable so the const modifier should be used for it in the .jnf file.

EXAMPLE 3: PointMarshaler (Mutable Java Objects)

In the examples up to this point, all JTYPEs were immutable. This is why [out] parameters could only be handled by single element arrays: that is, to deal with immutable types, a caller has to write code similar to the following:

   {
      double ad1[] = {0};
      double ad2[] = {0};

      func(ad1, ad2);

      System.out.println("func gave back: " + ad1[0] + ", " + ad1[1]);

   }

For immutable objects, it should be clear that the function:

  HRESULT func([out] FIXED *, [out] FIXED *);

could not be usefully mapped to:

  func(double d1, double d2);

because func() would have no way of returning information to the caller.

However, consider the java class java.awt.Point (which represents a point in 2-dimensional space.) The Point class is mutable as its x and y fields are public and can set by anyone. Therefore, it is advantageous to use the non-array form for passing [out] parameters. To do this only requires two new methods: copyToJava and toUninitJava.

The PointMarshaler class maps java.awt.Point to the Win32 POINT structure. The source code for PointMarshaler can be found under the \point directory. The executables PointMarshaler.class and PointMarshaler.dll are under the rundir directory.

The members implemented by PointMarshaler are:

public PointMarshaler {

    public static int cbByValSize; // set of sizeof(POINT) = 8

    public static Point toJava(int ppPOINT, int flags)
    {
       // convert **ppPOINT to a Point
       // return the Point
    }

    public static void copyToExternal(Point javaval,
                                      int    ppPOINT,
                                      int    Flags)
    {
       // convert Point to a POINT
       // copy the POINT to **ppPOINT
    }

    /* NEW! */
    public static void copyToJava(Point javaval, int ppPOINT, int Flags)
    {
       // modify "javaval" in place so it is "equivalent" to **ppPOINT;
    }

    /* NEW! */
    public static Point toUninitJava(int ppPOINT, int flags)
    {
       // create a new Point with arbitrary x and y values.
       // the contents of **ppPOINT are completely undefined and should
       // be ignored for fixed-size hook classes.
    }
}

This hook class can be used in the following ways.

COM Type | Marshaled to Java As
HRESULT func([in] POINT) | func(Point)
HRESULT func([out,retval] POINT*) | Point func()
HRESULT func([in] POINT*) | func(Point)
HRESULT func([out] POINT*) | func(Point)
HRESULT func([in,out] POINT*) | func(Point)

This differs from the basic hook class in that [out] POINT* becomes a single element, Point, rather than a single-element array, Point[]. To force jactivex to generate the non-array mapping, you must omit the const modifier from the Point entry in the .jnf file.

EXAMPLE 4: RectMarshaler (Support for Custom Allocation)

The hook class examples up to this point have provided no method for allocating or freeing the memory for ETYPE itself. They have relied entirely on the VM to allocate the actual memory for ETYPE. As a result, the use of custom data types up until now has been restricted to cases where ETYPE can be allocated on the stack and its lifetime is bounded by the lifetime of the call. While this is sufficient for some data types, there are cases where stack allocation is insufficient. The first case is when there is a need to marshal methods where an ETYPE is allocated by the callee but freed by the caller (or the other way around, as can happen with [in,out] parameters.) The second case is if the data type is variable-sized (such as a string), in which case, the VM cannot do the stack-allocation because the size is unknown. The first case is considered next, followed by the second case.

It is the responsibility of the hook class to specify which API is used to allocate and release the memory for ETYPE. The new hook methods required to support this are toExternal and releaseExternal.

The RectMarshaler example demonstrates this by marshaling the Win32 RECT structure into java.awt.Rect objects. The source code for RectMarshaler can be found under the \rect directory. The executables RectMarshaler.class and RectMarshaler.dll are under the \rundir directory.

The members implemented by RectMarshaler are:

public RectMarshaler {

   public static int cbByValSize; // set of sizeof(RECT) = 8

   public static Rect toJava(int ppRECT, int flags)
   {
      // convert **ppRECT to a Rect
      // return the Rect
   }

   public static void copyToExternal(Rect javaval,
                                     int    ppRECT,
                                     int    Flags)
   {
      // convert Rect to a RECT
      // copy the RECT to **ppRECT
   }

   /*NEW*/
   public static void toExternal(Rect javaval, int ppRECT, int Flags)
   {
      // allocate a new RECT, initialize it using javaval,
      // store pointer in *ppRECT
   }

   /*NEW*/
   public static void releaseExternal(int ppRECT, int Flags)
   {
      // release *ppRECT. If RECT required a releaseByValExternal
      // (which it doesn't), this routine must do that work as well.
   }

}

Note this example could also have implemented copyToJava and toUninitJava here since Rect is mutable (like Point). However, for the sake of clarity, this was not done.

Important Note: Even in the presence of these new Marshaling methods, the VM will optimize by allocating the data structure on the stack and thus override certain allocations. For example, for "[in] ETYPE*" calls, the COM method will receive a pointer to a VM-allocated ETYPE on the stack rather than one allocated by the toExternal method. If you want all ETYPEs to be allocated using toExternal(), you must omit the cbByValSize field. This will prevent the VM from optimizing to stack allocations as it cannot predict how many bytes to allocate.

This hook class can be used in the following ways:

COM Type | Marshaled to Java As
HRESULT func([in] RECT) | func(Rect)
HRESULT func([out,retval] RECT*) | Rect func()
HRESULT func([in] RECT*) | func(Rect)
HRESULT func([out] RECT*) | func(Rect[])
HRESULT func([in,out] RECT*) | func(Rect[])
HRESULT func([out,retval] RECT**) | Rect func()
HRESULT func([in] RECT**) | func(Rect[])
HRESULT func([out] RECT**) | func(Rect[])
HRESULT func([in,out] RECT**) | func(Rect[])

EXAMPLE 5: AnsiMarshaler (Variable-sized data types)

So far in this article, all of the ETYPE examples have been fixed-size structures. For some data structures, this is a prohibitive limitation. The classic example is a simple null-terminated string.

To define a variable-sized structure, the hook class must omit the cbByValSize field. The absence of this field marks the hook class as variable-size. Unlike a fixed-sized hook class, a variable-size hook class must support toExternal and releaseExternal in order to be useful (the VM cannot allocate a variable-sized structure on the stack). In addition certain mappings available to fixed-size hooks (in particular, those that pass the data type by value) are not available to variable-size hooks.

More specifically, consider the simple case where ETYPE is char (not LPSTR!), and JTYPE is java.lang.String. (Both types can be considered immutable for this example.) This structure can be defined by a hook class with only three methods: toJava, toExternal and releaseExternal; the minimum useful variable-size hook class.

The AnsiMarshaler class maps Strings to the LPSTR (ANSI null-terminated strings). The source code for AnsiMarshaler can be found under the \ansistr directory. The executables (AnsiMarshaler.class and AnsiMarshaler.dll) are under the rundir directory.

The members implemented by AnsiMarshaler are:

public AnsiMarshaler {

   public static String toJava(int ppCHAR, int flags)
   {
      // convert **ppCHAR to a String
      // return the String
   }

   public static void toExternal(String javaval, int ppCHAR, int Flags)
   {
      // allocate a new LPSTR, initialize it using javaval,
      // store pointer in *ppCHAR
   }

   public static void releaseExternal(int ppCHAR, int Flags)
   {
      // release *ppCHAR. If LPSTR required a releaseByValExternal
      // (which it doesn't), this routine must do that work as well.
   }

}

The allowed usages are as follows:

COM Type | Marshaled to Java As
HRESULT func([in] CHAR*) | func(String)
HRESULT func([out] CHAR*) | func(String[])
HRESULT func([in,out] CHAR*) | func(String[])
HRESULT func([out,retval] CHAR**) | String func()
HRESULT func([in] CHAR**) | func(String[])
HRESULT func([out] CHAR**) | func(String[])
HRESULT func([in,out] CHAR**) | func(String[])

Running and Building the Sample Client

The \client directory contains the sources for a sample Java client and a C++ inproc COM server which exchange all the various types implemented by the example.

To run the example, simply change the current directory to "rundir", and type "GO".

To build the sample, you will need to provide a makefile compatible with your build environment. Here are the steps:

  1. Compile sysdata.odl to produce sysdata.tlb:
    mktypelib sysdata.odl.
  2. Compile CustSample.odl to produce CustSample.tlb and CustSample.h
    mktyplib /h CustSample.h CustSample.odl
  3. Compile CustSample.tlb to produce CCustSample.java and ICustSample.java
    jactivex /javatlb CustSample.tlb /nCustSample.jnf
  4. Compile CCustSample.java to produce CCustSample.class
    jvc CCustSample  (You must use Jvc version 1.02.3920 or later)
  5. Compile ICustSample.java to produce ICustSample.class
    jvc ICustSample  (You must use Jvc version 1.02.3920 or later)
  6. Compile CustSample.java to produce CustSample.class and callbacks.class
    jvc CustSample  (You must use Jvc version 1.02.3920 or later)
  7. Compile CustSample.cpp & CustSample.def to produce CustSample.dll.
    cl + link.


Introduction to Jview

Jview.exe (jview) is a tool used to execute Java applets and applications from the command line. Jview provides an environment that your application can run in. It supports both debug and retail versions of your application.

Jview supports both applications and applets. If your Java project has a main method, jview will execute it. Jview executes applets, when used with the /a switch, by sending the applet to the Microsoft AppletViewer. For more information on the /a option, as well as a reference to other jview options, see Reference to Jview Command-Line Options.

Description of Jview Syntax

The Jview.exe (jview) command line uses the following syntax.

jview [options] <classname> [arguments]

The following table describes possible command-line input to the jview tool.
Entry | Meaning
options | One or more jview options. For more information, see Reference to Jview Command-Line Options.
classname | The name of the .class file to execute. Do not include the .class extension to this filename. For example, use HelloWorldApplet rather than HelloWorldApplet.class.
arguments | Command-line arguments to be passed to the .class file supplied in classname parameter.

Note Any options you want to supply to jview must be specified before the name of the .class file or they will be interpreted as command-line arguments to the .class file.

Using Jview.exe

You can specify Jview.exe (jview) options on the command line. If you are executing your Java applet or application from the command line, enter the options you want to supply to jview before the name of your .class file on the command line.

Reference to Jview Command-Line Options

This section is an alphabetic reference to all the jview command-line options. If a command-line option can take one or more arguments, its syntax is shown before its description.

To learn more about a particular jview option, choose the option from the following table.
/a /cp /cp:a /cp:p /v /p /d:

/a

/a

Use the /a option to invoke the Microsoft AppletViewer in the jview and wjview utilities. Applets run with the applet viewer behave the same as when run by a browser host application, including loading, sound, and security. The applet viewer accepts applet parameters and class names, in addition to URLs and HTML files.

When the /a option is used, any remaining command line tokens become parameters for the applet viewer.

Example:

You can load an applet either by using an HTML file to specify parameters, or by loading parameters directly from the command line. The following example shows how to load an applet from an HTML source file with the applet tag.

<applet code=MyApplet.class width=100 height=200>
               <param name=SomeName value=SomeValue></applet>

The same applet can run in the applet viewer with the following command line information.

jview /a width=100 height=200 SomeName=SomeValue MyApplet

The following example shows how to run more than one applet at a time, with the docbase as the current directory.

jview /a width=200 height=400 MyApplet height=300 MySecondApplet

This displays the first applet in a 200 x 400 frame, and the second applet in a 200 x 300 frame. If no height and width are specified on the command line, the applet's default size is one-third of the size of the screen.

Any parameter, including HTML files, will be loaded from the classpath. An example of this is as follows:

jview /a /cp \src\bvt MyApplet.html

/cp

/cp classpath

Use the /cp option to set the CLASSPATH environment variable for the current compilation. Using this option specifies the path where the jvc or jview command-line tools can find system and user-defined classes. The Java interpreter uses a platform-dependent default location and the CLASSPATH environment variable to find system classes. For more information, see CLASSPATH Environment Variable. The directories in the classpath are separated by semicolons on a Microsoft® Windows® system; on UNIX, by colons.

Example:

For example, on Microsoft® Windows®NT, the classpath might be as follows:

jview /cp x:.;x:\java\classes

In this example, jview searches in and beneath the directories on the path for system and user-defined classes.

/cp:a

/cp:a path

Appends the path entered to the end of the CLASSPATH environment variable, and inserts a semicolon between them.

For a full description of the CLASSPATH environment variable, see CLASSPATH Environment Variable.

Note The value for the classpath can come from the CLASSPATH environment variable or from the /cp option. When multiple /cp:a switches are entered, the paths are concatenated.

Example:

The following command concatenates the directories, myproj1 and myproj2, and appends the resulting path to the end of the existing classpath.

jview /cp:a myproj1 /cp:a myproj2

/cp:p

/cp:p path

This option is inserted before the path entered to the classpath and inserts a semicolon between them. When multiple /cp:p switches are entered, the paths are concatenated.

Note The value for the classpath can come from the CLASSPATH environment variable or from the /cp option. For more information, see CLASSPATH Environment Variable.

Example:

The following command concatenates the myproj1 and myproj2 directories, and is inserted before the resulting path to the existing classpath.

jview /cp:p myproj1/cp:p myproj2

/v

/v

Use the /v option to cause jview to verify all invoked methods. Without this option, only methods from untrusted loaders are verified. Verification is a process applied to the bytecode loaded from the class files to ensure that it does not pose a security threat. For remotely loaded class files, the Microsoft Win32 VM for Java (Microsoft VM) allows only a subset of the total functionality possible with the bytecode language. Verification enforces this so that if your class files attempt to do anything illegal, the class file is rejected.

For performance reasons, local system classes are not normally verified. The /v option forces the verifier to process these. You can use this to ensure that a set of class files will pass the verifier.

/p

/p

Use the /p option to force jview to pause before exiting if an error occurs. You can use this to determine the user interface state just prior to the error when debugging an application.

/d:

/d:property=string value

Use the /d: option to set a system property. System properties can be read using the java.lang.System.getProperty or java.lang.System.getProperties methods. See these methods for descriptions of system properties. As an example, you can use the following command line to set the user.dir property to some arbitrary value.

jview /d:user.dir=c:\java\test  myapp

You can also set user-defined properties. For example, you can set a property called "myprop" with the following command-line.

jview /d:myprop=12   myapp


Using Javareg (Version 2.0)

Javareg is a command line tool for registering Java classes as COM (Component Object Model) components in the Microsoft® Windows® registry. This enables you to write Java classes, compile them, and then call them from any programming language (including Java) by means of COM. You can also configure your classes to be executed remotely (on a different computer) using distributed COM (DCOM).

Note The original javareg (that shipped with Microsoft® Visual J++™, versions 1.0 and 1.1) supported /surrogate differently than the 2.0 version. In its original version, javareg itself implemented a surrogate process. Now that DCOM supports a surrogate as part of the system, and because the surrogate built into javareg was prototypical, support for the surrogate process has been dropped. The surrogate support in DCOM was made available in Microsoft® Windows NT® 4.0 Service Pack 2 (SP2) and DCOM for Microsoft® Windows® 95. For more information on this feature of DCOM, see the documentation in the Microsoft Win32 Software Development Kit (SDK) update for Windows NT SP2.

Javareg (version 2.0) supports the following command line syntax:

javareg [/?] [/register|/unregister]
        [/class:<JavaClass> [/clsid:<clsid>] [/progid:<ProgID>] [options]]

/? Displays command-line help and usage.
/register Registers the specified Java class. The /register switch can also be used with several other switches to register a JavaBeans object as a Microsoft® ActiveX® control.
/codebase:[filename|URL] | specifies the base location, either a URL or a filename, to obtain the Java class.
/control | Adds the necessary registry information to enable containers to treat the Java class as an ActiveX control. You must also use the /typelib: switch if you use this switch.
/typelib: [filename] | Generates the type library for this Java class at the specified filename's location.
/unregister | Unregisters the specified Java class.
/class | Specifes the Java class to register or unregister.
/clsid | Specifes the CLSID to use for the Java class (optional).
/progid | Specifes the ProgID to use for the Java class (optional).
/surrogate | Registers to run in system provided surrogate process.
/remote: <RemoteServerName> | Server to activate the class on (using DCOM).
/q | Quiet mode. Suppresses all message boxes.

More details on these options are provided below.

/q Javareg suppresses any message boxes it might display indicating success or failure. Regardless of whether this switch is specified, javareg will return 0 on success or 1 on failure.

/register Javareg registers the Java class specified in the registry. If /register is specified, at least /class:<JavaClass> must also be specified. Notice that javareg will also recognize /regserver for this command.

You can use a series of switches to register a JavaBean object as an ActiveX control (mentioned previously). Notice that if you use /control to register a JavaBean, you must also generate a type library using /typelib:.

javareg /register /class:[classname] /codebase:[filename|URL]
        /control /typelib:[filename]
/unregister | Javareg removes the registration information for a given Java class from the registry. If /unregister is specified, /class:<JavaClass> must also be specified. Notice that javareg will also recognize /unregserver for this command.
/class:<JavaClass> This argument specifies the name of the Java class to register or unregister. If this switch is specified either /register or /unregister must also be specified. For example, the following command line will cause javareg to register the Java class Pager. Because /clsid:<clsid> is not specified, javareg will automatically generate a UUID to be used as the CLSID for the class (it uses the COM API CoCreateGUID()).
javareg /register /class:Pager

If you execute javareg again with the same Java class name, javareg will reuse the CLSID already assigned to the Java class. As such, you can execute javareg with additional switches later to reconfigure your class (for example, by specifying the /surrogate switch).

/clsid:<clsid> Javareg uses the specified COM class ID (CLSID) rather than automatically generating one. For example, the following command will cause javareg to register the Java class Pager using the CLSID {2488D68A-D3BF-11D0-A145-080036006703}.

javareg /register /class:Pager
    /clsid:{2488D68A-D3BF-11D0-A145-080036006703}

/progid:<progid> By default, javareg does not assign a COM ProgID to your class. This switch lets you designate what ProgID to use. For example, the following command will cause javareg to register the Java class Pager and assign it the ProgID of "Pager.Java.1".
javareg /register /class:Pager /progid:Pager.Java.1

/surrogate Javareg writes the appropriate registry entries necessary to enable the Java class to be activated out-of-process. This is necessary if you want your Java class to be activated and called from a different computer. In other words, you use the /surrogate switch when registering your Java class to run as a DCOM server.

For example, the following command will cause javareg to register the Java class Pager so that it can be run from a different computer and accessed through DCOM.

javareg /register /class:Pager
        /clsid:{2488D68A-D3BF-11D0-A145-080036006703}
        /surrogate

Notice that it is not strictly necessary to specify the CLSID when using /surrogate. If you do not, javareg will generate one.

/remote:<RemSerNm> | If you want to activate and call a Java class on a different computer using distributed COM, use this switch on the client computer. When using this switch, the Java class cannot be activated on the client computer, only on the server. The <RemoteServerName> can be any computer identifier supported by distributed COM. Typically, it can be a NetBIOS name, a DNS name, or a decimal-dotted IP address.

The following example explains the necessary steps for using this functionality.

  1. Write a Java class with some public members (for example, Pager.java).

class Pager
{
   public boolean Page(String PhoneNumber, String PIN, String Msg)
   {
      System.out.println("Page request received. Sending.");
      System.out.println(" Phone: " + PhoneNumber);
      System.out.println(" PIN: " + PIN);
      System.out.println(" Message: " + Msg);
      return true;
   }
}
  2. Compile the Java source (into Pager.class, for example), and move the .class file to your trusted class lib directory on the server (for example, C:\WINNT\Java\TrustLib\).

  3. On the server, run javareg. The following shows the Pager example:

javareg /register /class:Pager /progid:Pager.Java.1
        /clsid:{2488D68A-D3BF-11D0-A145-080036006703}
        /surrogate
  4. On the client, run javareg. The following shows the Pager example (replace "yourservername" with the name of the server in the previous step):

javareg /register /class:Pager /progid:Pager.Java.1
        /clsid: :{2488D68A-D3BF-11D0-A145-080036006703}
        /remote:yourservername

    Now you can use Microsoft® Visual Basic® to create an instance of "Pager.Java.1". For example:

Dim x As Object
Set x = CreateObject("Pager.Java.1")
fSuccess = x.Page ("555-1212", "1234", "Call Home!")

The Pager class will be activated and will run remotely on <RemoteServerName>.


Introduction to Cabarc

Cabarc is a utility that creates, extracts, and lists the contents of cabinet (.cab) files. Cabarc uses a command-line interface similar to that of popular archiving tools. Cabarc supports wildcards and recursive directory searches.

The cabinet format is an efficient way to package multiple files. The cabinet format has two key features: multiple files can be stored in a single cabinet (.cab) file, and data compression is performed across file boundaries, which significantly improves the compression ratio. Cabinet file construction can be designed around the number of files to be compressed and the expected patterns for gaining access to them (sequential, random, all at once, or a few at a time).

A key concept of the cabinet file is the folder. A folder is a collection of one or more compressed files that are compressed together as a single entity. Compressing files this way improves the compression ratio. Random access time suffers, however, because decoding (decompressing) any file in a folder requires that all preceding files in that folder must also be decoded. The focus is on maximum compression as opposed to quick decompression, since the cabinet format is designed to deliver file content, rather than to stream media.

Using Cabinets With Java Files

There are two reasons to use the cabinet technology with Java classes. The first is building Java applets with lots of classes and graphics or audio files that you would like compressed and that would not be shared by other sites. This group is referred to here as the "applet" group, referring to the <APPLET> HTML tag that is used to access the contents of the cabinet file.

The second reason is to distribute your Java class libraries to users so that your classes can be accessed like system classes by Java applets or applications. HTML pages that download cabinets containing library files use the <OBJECT> tag to download and access the libraries. Note that the library scheme only supports the download and access of class files, not images or audio. These files should be provided by the applet and not the cabinet file.

Archiving Applets and Multimedia Files

This procedure will help you create a cabinet file for delivering compressed class and multimedia files to a user's system.

  1. Make sure that the SDK-Java\Bin directory, which contains Cabarc.exe, is in your path.
  2. Run Cabarc.exe to build a cabinet containing all of your files. See the section of this article for command-line syntax for the cabarc tool.
  3. Optionally, digitally sign the cabinet file.

    Code-signing is important for users, so that they know to trust your code before placing it on their computers. For the latest information on how to get your code signed, see the signcode article and http://www.microsoft.com/workshop External Link

When creating cabinets that will be read by the browser from the CABBASE parameter, make sure to use the default compression mode (MSZIP) and not the new LZX (Lempel-Ziv) compression mode, which is not supported by Internet Explorer 3.xx, but is supported by Internet Explorer version 4.0).

Archiving Library Files

When delivering libraries in a cabinet file, the files to be compressed and delivered are archived in one cabinet file called the inner cabinet. This file is itself archived in another cabinet file (called the outer cabinet) with an .inf file. The .inf file, based on the Master.inf template found in the SDK-Java\Bin directory, is used by the setup engine in Internet Explorer. It contains the names of the libraries, where the libraries should be placed, the class identifier used in the <OBJECT> tag, and so on. The use of the .inf file only pertains to libraries, which are referenced by using the <OBJECT> HTML and does not pertain to applets.

Information for the Master.inf Template

For Java libraries, you will need to gather the following information to fill out the .inf file copied from the Master.inf template (found in the SDK-Java\Bin directory).

  • Decide whether to place the libraries in the Lib or TrustLib directory. In the .inf file, you will edit the lines that determine whether the libraries are placed in the <windir>\Java\Lib or <windir>\Java\TrustLib directory. Comment out the line that does not apply. The following code sample shows the default that is in Master.inf.

   ; If you use one of these, you will use exactly one.

   HKLM,"SOFTWARE\Classes\CLSID\%ClassId%\InProcServer32","Lib",,"%49000%"
   ;HKLM,"SOFTWARE\Classes\CLSID\%ClassId%\InProcServer32","TrustedLib",,"%49000%"
  • Include the name of the cabinet file that contains your classes. Replace CabFileName.cab with your class cabinet name in the following line.

    run=extrac32.exe /e /a /y /l %49000% CabFileName.cab
  • Include the name of the .inf file that you are using. Replace Master.inf with the name of your .inf file as indicated in the following code example.

    [hook2]

    ; Change the name of master.inf to the name you are assigning this
    ; file. Leave the second line alone.

    InfFile=master.inf
    InfSection=RegistryData
  • Include a unique ClassId, generated by running Guidgen.exe from the SDK-Java\Bin directory. The following code excerpt from the Master.inf template file sets the identifier.

    [Strings]
    ; Running guidgen in the SDK generates the ClassId you need to fill
    ; in here. This classId also goes in the OBJECT tag.
    ; Don't forget the set braces!

    ClassId="{99999999-9999-9999-9999-999999999999}"
  • Include the name of your libraries. The following code excerpt from the Master.inf template file sets the library name.

    ; Put the name by which your packages should be referred to
    ; (i.e., "Bob's Text Viewer") here.

    PackageName="name"

Should you want to, you can also include the following information.

  • A version number. Version numbers are in the form a,b,c,d (that is, 1,0,5,10). This prevents downloading the same library if the user has the latest version. (This is a recommended practice.) The following code excerpt from Master.inf sets the version number.

    ; Replace <aa...> with the version number (like 1,0,0,1) of this
    ; version of your library. This is so that when you want to update
    ; your libraries, you can change the version rather then the classId
    ; and the problems that go with that. If the version number here
    ; and in the OBJECT tag match the version already stored on the
    ; user's machine, it will not download the classes again, which
    ; also saves time and energy.

    HKLM,"SOFTWARE\Classes\CLSID\%ClassId%\InstalledVersion",,,"aa,bb,cc,dd"
  • A filename. This file can be examined by the browser to determine if the library files have already been installed on the system. This is illustrated in the following code example.

    ; Here, replace <file> with the name of one of the class files in
    ; your package, including the virtual path to that file.
    ; This will make sure that the classes exist on the
    ; user's system; if they don't, they will be downloaded, regardless
    ; of version numbers.

    HKLM,"Software\Classes\CLSID\%ClassId%\InstalledVersion","Path",,"%49000%\<file>"
  • The names of any native code that you want to install from your cabinet file (the one containing the .inf and .cab file). These files are installed automatically in the <windir>\System directory. The following code excerpt from Master.inf sets the code names.

    ;; If you are installing native code, you will want to uncomment all
    ;; the lines in the remainder of this section, except for the ones
    ;; that are descriptive (and have two semicolons).

    ; CopyFiles=OtherFiles

    ;[DestinationDirs]
    ;OtherFiles=11

    ;[OtherFiles]
    ;; List the name of each file (delimited by returns) here.
    ;; Just list the local name--no need for paths, and so on. Example:
    ;; foo1.dll,,,32
    ;; foo2.dll,,,32

    ;[SourceDisksFiles]
    ;; For each name listed in the above section, you will want to put
    ;; <filename>=1 on this list. So it would look like
    ;; foo1.dll=1
    ;; foo2.dll=1

    ;[SourceDisksNames]
    ;1=%PackageName%,"",0
Instructions for Building Cabinet Files for Libraries

The following steps will help you create a cabinet file for installing Java libraries on a user's computer.

  1. Make sure that the SDK-Java\Bin directory, which contains Cabarc.exe, is in your path.
  2. Run Cabarc.exe to build your cabinet containing all your class files. For command-line syntax for the cabarc tool, see the section of this document. It is a good ideato put your vendor name as the package name preceding all your classes to avoid having them overwritten by other installed classes. For example, your classes should be in the form suggested by the following example (where "vendor" is your unique vendor name).

        vendor.util.loader.class
        vendor.util.builder.class
        vendor.applet.start.class

    For example, say your company is called CoolTools. You have a package called "widgets" located on your development computer at c:\JavaCode\CoolTools\Widgets\*.class. You want to install this package in the user's <windir>\Windows\Java\Lib directory. You would change directory to c:\JavaCode\ and run cabarc as follows.

cabarc -r -p -P javacode\ n CTClasses.cab CoolTools\*.*

    In this syntax, -r tells cabarc to recursively archive everything under CoolTools, maintain the directory structure (-p), strip off javacode from directories (-P javacode\), and create a cabinet file called CTClasses.cab.

    When this is installed on the user's system, all classes would be placed under the <windir>\Java\Lib unless the .inf file was modified to place them in the TrustLib directory.

  3. Make a copy of the Master.inf template in the SDK-Java\Bin directory and edit the copy. This sets up the layout and instructions for installing the libraries. The Master.inf file is heavily commented and includes places to put the information you have gathered. For details about what goes into this file, see .

    Remember to run the guidgen tool to create a ClassId and copy it into the correct place in the .inf file.

    Following on with the CoolTools example, you would create a file (for example, Cool.inf) based on Master.inf, create a ClassId using guidgen, copy it into the file, and then edit the name of the .inf file and the .cab file in Cool.inf.

    The following code excerpt from the Cool.inf file shows the mandatory edits that must be made.

[hook1]

; In this line, replace CabFileName.cab with the your CAB filename.

run=extrac32.exe /e /a /y /l %49000% CTClasses.cab

[hook2]

; Change the name of master.inf to the name you are assigning this
; file. Leave the second line alone.

InfFile=cool.inf
InfSection=RegistryData

[Strings]
; Running uuidgen in the SDK generates the ClassId you need to fill
; in here. This classId also goes in the OBJECT tag.
; Don't forget the set braces!

ClassId="{4439E200-6FCC-11d0-89AA-00A0C9054129}"

; Put the name by which your packages should be referred to
; (i.e. "Bob's Text Viewer") here.

PackageName="CoolTool Java Classes"
  4. Run Cabarc.exe again. This step builds the cabinet file containing the class cabinet, the .inf file, and any other files you might want to include. The following example demonstrates how to create a cabinet file called CoolDown.cab, which includes the Cool.inf and the CTClasses.cab files.

       cabarc  n CoolDown.cab CTClasses.cab Cool.inf
  5. Digitally sign the cabinet file.

    Code-signing is important for users, so that they know to trust your code before placing it on their computers. The default settings in Internet Explorer will reject unsigned code. For the latest information on how to get your code signed, see the signcode article and http://www.microsoft.com/workshop/ External Link.

Accessing the Cabinet From a Web Page

For Java applets, you use the CABBASE parameter in an APPLET tag to point to the .cab file. If the applet is not already present on the user's system, the .cab file is downloaded, the contents are extracted, and the applet is started.

To use the APPLET tag, you set the parameters as shown in the following example.

<APPLET CODE="sample.class" WIDTH=100 HEIGHT=100>
<PARAM NAME="cabbase" VALUE="vendor.cab">
</APPLET>

Using the CABBASE parameter does not conflict with CODEBASE or any other parameters necessary for other browsers. Using CABBASE along with the other tags allows Internet Explorer 3.0 and other cabinet file-supporting browsers to use .cab files without impeding the ability of other browsers to download and execute applets.

For Java libraries, you use the OBJECT tag to point to the .cab file. If the classes (in the current version) are not already present on the user's system, the .cab file is downloaded, and the contents are extracted and placed in the appropriate location on the user's system. This step should be done according to following syntax.

<OBJECT CLASSID="<classid>" CODEBASE="<path to cab>#Version=x,x,x,x">
</OBJECT>

For example,

<OBJECT
    CLASSID="clsid:12345678-9abc-def1-1234567890ab"
    CODEBASE="cabs/vendor.cab#Version=1,0,0,12">
</OBJECT>

As in the preceding example, the CODEBASE attribute can specify a version number, which enables the libraries to be downloaded and installed if the version on the user's system is out-of-date.

Both the ClassId and the version number are also stored in the .inf file inside the outer cabinet file. Including the version number is optional but highly recommended. This step permanentlyinstalls the classes on the user's system, so only use this for libraries.

After libraries are installed in this manner, APPLET tags can refer to the classes placed in the library specified by Cabs/Vendor.cab. Those applets work like normal, with classes brought in through CABBASE or CODEBASE.

Using the Cabarc Utility

Cabinets are created by using the n command, which is followed first by the name of the cabinet to create and then by a filename list. This is shown in the following example.

cabarc n mycab.cab prog.c prog.h prog.exe readme.txt

The previous command creates the cabinet Mycab.cab containing the files Prog.c, Prog.h, Prog.exe, and Readme.txt in a single folder by using the default compression mode, MSZIP.

Command Line Usage

Cabarc is used as follows.

cabarc [<options>] <command> [<file list>]

Three commands are currently supported: n (creates a new cabinet), l (lists the contents of an existing cabinet), and x (extracts files from a cabinet). These commands are described later in this document.

Using Wildcards

Cabarc supports wildcards in the filename list, as shown in the example below.

cabarc n mycab.cab prog.* readme.txt

Creating Folders

All files are added to a single folder (compression history) in the cabinet. It is possible to instruct cabarc to begin a new folder by using the plus sign (+) for the file to be added, as shown in the following example.

cabarc n mycab.cab test.c main.c + test.exe *.obj

The previous command creates the cabinet mycab.cab with one folder containing test.c and main.c and a second folder containing test.exe and all files matching *.obj.

Preserving Directory Paths

By default, directory names are not preserved in the cabinet—only the filename component is stored. For example, the following command stores prog.c in the cabinet.

cabarc n mycab.cab c:\source\myproj\prog.c

To preserve paths, use the -p option as shown in the following example.

cabarc -p n mycab.cab c:\mysource\myproj\prog.c

This command puts mysource\myproj\prog.c in the cabinet. Be aware that the c:\ prefix is still stripped from the filename. Cabarc will not enable absolute paths to be stored in the cabinet, nor will it extract such absolute paths.

Stripping Paths

Path stripping is an option that preserves part of a path name. The following example shows how the path stripping option can archive everything in the c:\mysource\myproj\ directory but store only the myproj\ component of the path.

cabarc -p -P mysource\ n mycab.cab c:\mysource\myproj\prog.c

The -P option strips any strings that begin with the string provided. Be aware that wildcards are not supported by the -P option, which is a simple text match. Absolute path prefixes, such as c:\ or \, are stripped before the comparison takes place. Do not include absolute path prefixes when using the -P option.

The -P option may be used more than once to strip out multiple paths. Cabarc builds a list of all paths to be stripped and applies only the first one that matches. Consider the following example.

cabarc -p -P mysrc\ -P yoursrc\ n mycab.cab c:\mysrc\myproj\*.* d:\yoursrc\yourproj\*.c

The trailing slash at the end of the path name is important. Entering -P mysrc instead of -P mysrc\ would cause files to be added as \myproj\<filename>.

Using Recursive Directory Search

Cabarc can archive files in a directory and all of its subdirectories by using the -r option. For example, the following command example archives all files ending in .h that are in c:\msdev\include\, c:\msdev\include\sys, and c:\msdev\include\gl (assuming these directories exist on your system).

cabarc -r -p n mycab.cab c:\msdev\include\*.h

The -p option is used here to preserve the path information when the files are added to the cabinet. Without this option, only the filename components would be stored, although sometimes it might be desirable behavior to not use -p.

Reserving Space for Code Signature

Cabarc can reserve space in the cabinet for a code signature. This is done with the -s option, which reserves a specified amount of empty space in the cabinet. For code signatures, reserve 6144 bytes. Consider the following example for doing so.

cabarc -s 6144 n mycab.cab test.exe

Be aware that the -s option does not actually write the code signature; it merely reserves space for it in the cabinet. Use the appropriate code signing utility to fill out the code signature.

Setting the Cabinet ID

Cabinet files have a 16-bit cabinet ID field that is designed for application use. The default value of this field is zero; however, use the -i option of cabarc to set this field to any 16-bit value. Consider the following example.

cabarc -i 12345 n mycab.cab test.exe

Setting the Compression Type

Set the compression type with the -m option. The default compression type for a cabinet is MSZIP . The three supported compression modes are MSZIP compression (-m MSZIP), no compression (-m NONE), and LZX compression. LZX compression is selected by -m LZX:<w> where <w> is a number in the 15 to 21 range denoting the size of the compression history window, 2 to the power of <w>. A larger history window requires more memory when compressing or decompressing, but it provides better compression. LZX compression must not be used when creating cabinets that will be read by the browser from the CABBASE parameter—Internet Explorer 3.xx does not support the LZX compression mode. However, Internet Explorer version 4.0 does.

The following command stores files in the cabinet with MSZIP compression.

cabarc -m MSZIP n mycab.c *.*

Using a File List from a File

Cabarc can input its list of files from a text file instead of from the command line by using the @file option followed by the name of the file from which to take the inputs. Consider the following example.

cabarc n mycab.cab @file filelist.txt

The text file must list the physical filenames of the files to be added, one per line. As is the case when specifying filenames on the command line, the plus sign (+) can be used as a filename to specify the beginning of a new folder. If a filename contains any embedded spaces, it must be enclosed as quotes, as follows.

test.c
myapp.exe
"output file.exe"

Quotation marks are required because each physical filename can be followed (on the same line) by an optional logical filename, which specifies the name under which the file will be stored in the cabinet. Consider the following example.

test.c myapp.c
myapp.exe
"output file.exe" myfile.exe

If the logical filename contains spaces, it also must be enclosed in quotation marks. Note that the logical filename overrides the -p (preserve path names) and -P (strip path name) options; the file is added to the cabinet exactly as indicated. Wildcards can be used in the physical filename, but in this situation, a logical filename is not allowed.

The @file option can be used more than once to retrieve file lists from multiple files. Cabarc does not check for the presence of duplicate files, so if the same physical file appears in more than one file list, the file will be added to the cabinet as often as needed.

The @file option can be combined with filenames on the command line. The files from the use of -l option are added first. Consider the following example.

cabarc -l filelist1.txt -l filelist2.txt n mycab.cab *.c *.h

Note that the @file option is available only when creating cabinets, not when extracting or listing cabinets.

Listing Cabinet Contents

It is possible to view the contents of a cabinet using the l (list) command, as shown below.

cabarc l mycab.cab

Cabarc displays the cabinet identifier in the cabinet. (See the -s option for cabinet creation.) Cabarc also displays the following file information: size, date, time, and attributes.

Extracting Files from Cabinets

The x (extract) command extracts files from a cabinet. The simplest use of the X command is shown in the following example, which extracts all files from the cabinet.

cabarc x mycab.cab

Alternatively, it is possible to extract files selectively by providing a list of filenames, wildcards, or both.

cabarc x mycab.cab readme.txt *.exe *.c

Full path names (if they are present in the cabinet) are not preserved upon extraction by default. For example, if a file named mysrc\myproj\test.c is present in the cabinet, the command cabarc x mycab.cab will cause the file test.c to be extracted into the current directory. To preserve filenames upon extraction, the -p option must be used. The -p option causes any required directories to be created, if necessary.

Only the filename component is considered in the matching process. The path name is ignored. For example, the command "cabarc x mycab.cab test.c" causes the file mysrc\myproj\test.c to be extracted to the current directory as test.c, as will cabarc x mycab.cab *.c (which also extracts any other files matching *.c).

By default, the extracted files are stored in the current directory (and its subdirectories, if the -p option is used). However, it is possible to specify a destination directory for the extracted files. This is accomplished by appending a directory name to the command line. The directory name must end in a backslash (\). Consider the following examples.

cabarc x mycab.cab c:\somedir\
cabarc x mycab.cab *.exe c:\somedir\


Introduction

Working with MS VM
In this topic

* Distributing Software Using Distribution Units

* Split Distribution Units

* Registering ActiveX Controls as JavaBeans

* Packaging a Java Library with Dubuild

* More Information

Tools | Previous | Tools | Next
Using DUBuild | Previous | Tools | Next

Introduction

A Distribution Unit (DU) is a cabinet file that contains an Open Software Distribution (OSD) manifest file (also known as a Distribution Unit Profile [DUP]), as well as content files. DUs are a new method for distributing software that is supported by the code download feature of Microsoft® Internet Explorer 4.0. The OSD manifest file included in the cabinet file archive contains details on the version of the DU, the contents and their versions, and how to install the contents. It is written in XML.

The dubuild utility writes the OSD file and places it in a cabinet file archive with any specified contents. Although this document focuses specifically on using dubuild to distribute and install Java packages with the Java Language Package Manager (JPM), dubuild is a general distribution standard; it can be used to distribute applications, libraries, and native code.

The dubuild utility is similar to cabarc, but uses the OSD manifest instead of .inf files. DUs written with dubuild (the OSD manifest in particular) are not recognized by earlier versions of Internet Explorer.

The dubuild utility has three separate functions.

  1. Creates an OSD and packages a Distribution Unit.
  2. Creates a Split, or Delta, Distribution Unit.
  3. Packages Microsoft® ActiveX® controls as JavaBeans objects.

Distributing Software Using Distribution Units

The primary function of the dubuild utility is to create DUs for software distribution targeted at Internet Explorer.

Traditionally, Java software distribution has been inefficient. You would archive classes in a .zip file, and then archive the .zip in another .zip file along with any documentation or other included files. Users would unpack the first archive (but not the second), add the included .zip to a path, set their classpath, and reboot.

DUs make this approach unnecessary. The OSD manifest included in the DU includes installation instructions for the Java Language Package Manager. The DUs still need to be created with a hierarchical directory, as with augmented cabinet files, but installation requirements are handled by Internet Explorer and the JPM. The distribution is provided through a special HTML script that includes an <applet> and useslibrary HTML tag set.

Creating DUs for Internet Explorer 3 is more involved. You can follow the MASTER.INF template and procedures as you would for creating a cabinet file, then add the .INF to your package, and finally, use the dubuild utility to package it. By default, the dubuild utility uses LZX compression, but Internet Explorer 3 uses MSZIP compression. You can use the /Z command line option to build DUs with MSZIP compression that are compatible with Internet Explorer 3.

Applet and Useslibrary

The HTML tag set is similar to any applet script. The <applet> tag specifies the applet to run, and the extra <param> tags supply additional information to Internet Explorer 4.0 about the name and version of the DU that contains the Java classes needed to run the applet. There are three parameters associated with the applet tag.

<applet code=com.ms.JPMBrowser.BrowserApplet
width=200
height=200>
<PARAM NAME=useslibrary VALUE="JPM Browser">
<PARAM NAME=useslibrarycodebase VALUE="jpm.cab">
<PARAM NAME=useslibraryversion VALUE="1,1,2,3">
</applet>
  • The useslibrary element specifies the friendly name of the DU. This name is registered with Internet Explorer and is used in conjunction with the DU's version number to indicate presence or absence of the contents of the DU in the Java Language Package Manager.
  • The useslibrarycodebase element specifies a URL and cabinet file archive to download (in this example, the cabinet file is local), if the DU is not already present on the current system.
  • The useslibraryversion element specifies the version number of the DU. This is used to update the Java Language Package Manager when new versions, or Split DUs, are encountered.

Using DUs to distribute code enables users to run applets without constantly downloading them in a networked environment. For example, where once you had to interact with security managers every time you visited a site and encountered a signed cabinet file or code, you can now install the code into the Java Language Package Manager on the first visit and avoid subsequent security interactions; the code is already installed. If the DU's cabinet file is signed, all security and permissions apply the first time the cabinet is downloaded.

Installing Distribution Units

The Java Language Package Manager and Internet Explorer go through several steps before a DU is installed.

  1. The Java Language Package Manager first determines if the DU is already registered by checking the friendly name of the DU, which is specified as a string in the useslibrary parameter.
    If the DU is not present on the current system, the appropriate cabinet file archive is downloaded from the URL specified by the useslibrarycodebase parameter.
    If the DU is present on the current system, the version number, specified in the useslibraryversion parameter, is checked to determine whether the DU is current with the version offered. This eliminates the need to download, open, and examine the contents of the archive to determine if it is current (as is the case when you use <object> tags with Internet Explorer 3).
  2. If the local version number matches or is newer than the offered version, no action is performed. If the local version is older, the DU is downloaded and the OSD manifest is examined.
  3. Internet Explorer and the JPM install the included packages according to the OSD.
  4. The applet is executed.

Note Internet Explorer 3.x does not recognize useslibrary and its associated parameters. You have to use the <applet> and <object> tags to emulate this distribution.

Split Distribution Units

The second function of the dubuild utility is to create Split, or Delta, DUs. This functionality is useful for updated versions of software where some of the files in the original DU have been modified (a service pack, for example).

In order to build a Split DU, you need to specify a new (version 2) cabinet file, the original directory tree, and the original DU. The changed files are packaged in the Split DU, and the OSD manifest contains a pointer to the original DU. A command line to build a split DU follows:

C:\..\>dubuild newcab.cab tree oldcab.cab

When Internet Explorer encounters a Split DU in useslibrarycodebase, it follows the same steps previously described, with an additional step. If the newer version of the Split DU is not present on the local system, it will be downloaded, and the OSD manifest is examined. If the earlier version of the software, pointed to by the OSD file, does not also exist on the local system, it is downloaded as well. However, if the earlier version of the Split DU is already present on the system, no further action is performed.

Registering ActiveX Controls as JavaBeans

The third function of the dubuild utility is to register ActiveX controls as JavaBeans.

C:\..\>dubuild /B package,class,regmode,progid,guid,iconfile,
                                  flags,tlbguid,tlbfile,bitmap32

Simple Bean identification is done by only supplying the package name and class filename. ActiveX registration requires the regmode argument and at least the guid argument in addition. See dubuild command line options for more information on command line options.

Packaging a Java Library with Dubuild

The following material presents a step-by-step tutorial for installing a set of Java libraries into the Microsoft Win32 VM for Java using the dubuild utility. This example uses the creation and distribution of the JPMBrowser package and covers the creation of DUs. They can be installed on machines with the Microsoft VM and Internet Explorer 4.0.

There are three steps to creating and distributing DUs.

  1. Decide on a package name.
  2. Create the DU with the dubuild utility.
  3. Test install the DU from an HTML page.

Decide on Your Package Names

The package name for JPMBrowser is com.ms.JPMBrowser. There are guidelines to naming packages (this example is a Microsoft library for Java so it uses the com.ms. prefix; your package will use the form that follows the com.company.packagename naming convention), but generally choose a meaningful and descriptive name.

Make sure your directory structure reflects the package name, as demonstrated below in the Microsoft® Windows Explorer window for the example package.

Create the Distribution Unit

  1. From a DOS prompt, change your working directory to the top-level project directory. For this example, it is C:\projects\JPMBrowser, the first directory shown in the previous Windows Explorer view.
  2. Run the dubuild utility, found in your Microsoft SDK for Java bin\packsign\ directory. Use the /D option to specify a friendly name for your DU, and use the /I option to specify that only Java class files are included. You must use full paths when using dubuild.
  3. It is a good idea to run extract /D to view the resulting cabinet file and to verify that the proper files are included with the correct directory paths.

A demonstration of the preceding steps follows.

C:\>cd \projects\JPMBrowser

C:\projects\JPMBrowser>path
PATH=C:\WIN95;C:\WIN95\COMMAND;C:\SDK-JAVA.20\BIN\PACKSIGN;
C:\SDK-JAVA.20\BIN;

C:\..\JPMBrowser>dubuild JPM.cab . /D "JPM Browser" /I C:\..\*.class /V 1,1,2,3

Microsoft (R) Distribution Unit Builder - version 4.79.2220
Copyright (C) Microsoft Corporation 1997. All rights reserved.

C:\projects\JPMBrowser>extract /D jpm.cab
Microsoft (R) Diamond Extraction Tool - version (16) 1.00.0530 (04/3/95)
Copyright (c) Microsoft Corp 1994-1995. All rights reserved.

 Cabinet jpm.cab

07-30-1997  5:50:32p ----    295 JPM Browser.osd
07-20-1997  6:38:42p A---  1,960 com\ms\JPMBrowser\JPMPanel.class
07-20-1997  6:38:42p A---    678 com\ms\JPMBrowser\BrowserFrame.class
07-20-1997  6:38:42p A---  1,289 com\ms\JPMBrowser\BrowserApplet.class
                 4 Files   4,222 bytes

The Open Software Distribution (OSD) file that is packaged with the DU is automatically generated by the dubuild utility. The OSD file contains a list of the included Java packages and sets the version number to be 1.1.2.3. Note that when specifying version numbers on the command line, the version number must be comma-separated.

Make sure that your packages are in the appropriate (in this case, com\ms) subdirectory, as shown above.

Test Install the DU with an HTML Page

To test the installation of the DU, you can write an HTML page that installs and runs the application or applet. The HTML script for the JPMBrowser sample applet uses an <applet> tag and several special useslibrary parameters. These parameters specify the friendly name, location, and version of the DU. For more information on the <applet> tag and associated parameters, see Distributing Software Using Distribution Units.

<applet code=com.ms.JPMBrowser.BrowserApplet
width=200
height=200>
<PARAM NAME=useslibrary VALUE="JPM Browser">
<PARAM NAME=useslibrarycodebase VALUE="jpm.cab">
<PARAM NAME=useslibraryversion VALUE="1,1,2,3">
</applet>

You can place this applet in an HTML file that is in the same directory as your cabinet file, or you can specify a remote location for the cabinet file in the useslibrarycodebase parameter. To test the installation, browse the HTML page in Internet Explorer. Internet Explorer should install the cabinet file and show the applet on the page.

More Information

For more information on dubuild command-line options, see the Dubuild Quick Reference.


Signing a Cabinet File with Java Permissions Using Signcode

Working with MS VM
In this topic

* Overview

* Cabinet File Permission Levels

* A Brief Introduction to Zones

* Using Signcode with Java Permission Information

* How to Sign a Cabinet File with Java Permissions

Tools | Previous | Tools | Next
Signing a Cabinet File | Previous | Tools | Next

Signing a Cabinet File with Java Permissions Using Signcode

Overview

Signing a cabinet file with Java permissions gives developers more detailed control over the security restrictions placed on their applet when it is used over the Internet or an intranet.

While encoding permissions inside an applet is optional, it provides several additional benefits over regular signing:

Applets and controls can be granted only specific permissions they need. | If an applet is signed in the old style (without Java information), the user must choose between running it in the Java "sandbox," or allowing it to be fully trusted. For example, permission signing enables applets to request permission to store only temporary files on the client hard disk. Users of a permission signed applet can allow the it to run, without worrying that it will have full access to their system.
Fewer dialog boxes are presented to the user. | When Microsoft® Internet Explorer zones are used, applets might automatically receive some permissions when they are downloaded from a certain zone. When an applet is signed with the specific permissions it needs, the user will not even be queried if the zone automatically grants the permissions that the applet needs.

Cabinet File Permission Levels

The signcode utility enables you to sign a cabinet file at three different security levels. They are as follows:

High | The High security level ensures that all Java code contained in the cabinet file will run in the Java "sandbox." High is the most stringent level of signing, and is equivalent to the same permissions that an unsigned applet is granted. Signing a cabinet file with High ensures that it will never be able to do more than it would in the sandbox, regardless of where the code comes from and what the user allows it to do. A cabinet file signed High will always be allowed to run without any user intervention.
Medium | The Medium security level places the same restrictions on the applet as High, but with a few exceptions. Applets signed with the Medium level request user-directed file I/O as well as the ability to store 1 MB of data in the client computer's scratch space. This storage can be accessed through the com.ms.io.clientstorage API. Applets signed with Medium permissions may also call user-directed file I/O routines. These routines will present dialogs to the user and ensure that all file operations are done with user intervention. A cabinet file signed Medium will run without intervention in Low and Medium security zones. Because the requested permissions are greater than a High security zone can automatically give, a Medium signed cabinet file will prompt the user before allowing code to run in a High security zone.
Low | The Low security level means the code in the cabinet file is requesting to be fully trusted. Only a zone set at Low security can grant this much access without first asking the user. The other two zones prompt the user before running the applet.

Cabinet Files and ActiveX

Cabinet files may contain both Microsoft® ActiveX® Controls and Java code when downloaded using the uselibrary parameter. Because ActiveX controls must be fully trusted to run, they are treated differently from Java code. The previous security levels apply only to Java code, and ActiveX controls in the cabinet file will not be allowed to run.

For ActiveX controls to run when they are in a cabinet file that uses Java Permission signing, you must specify that the cabinet file contain ActiveX controls in the signature. Do so by specifying the LowX, MediumX, or HighX flags instead of Low, Medium, or High. These three flags have the same meaning as their respective flags without the X. However, if you include ActiveX controls in the cabinet file, they will be denied, allowed to run, or will query the user, based on the security settings of the zone.

Note If your cabinet file has only ActiveX controls, do not use the Java signing method. Instead, use signcode without JavaSign.dll.

A Brief Introduction to Zones

Zones are a way of reducing the complexity of system security by assigning security policies to entire groups of sites.

Microsoft® Internet Explorer 4.0 divides your Internet world into zones, so you can assign specific security settings to each zone, and then assign Web sites to a zone with a suitable security level. The name of the current zone appears on a status bar in the lower-right corner. Whenever you attempt to open or download content from the Web, Internet Explorer checks the security settings for that Web site's zone. Internet Explorer provides four zones:

Corporate Intranet | Addresses that don't require a proxy server (those listed in the Proxy Settings as not requiring a proxy server). The addresses included in this zone are defined by the system administrator in the Internet Explorer Administrator's Kit (IEAK). The default security level for the Corporate Intranet zone is Low.
Trusted Sites | Sites you trust enough to require low security before downloading or running files from the Internet. You can assign sites to this zone. By default, the security level for the Trusted Sites zone is Low.
Restricted Sites | Sites you don't trust, requiring medium or high security before downloading or running files from the Internet. You can assign sites to this zone. By default, the security level for the Restricted Sites zone is High.
Internet | By default, the Internet is anything not on your computer, the Intranet, or assigned to any other zone. The default security level for the Internet zone is Medium.

Each zone can be set to a specific security level. The security level applies to all code downloaded from sites within the zone:

High Security | Java applets will run in the sandbox without intervention from the user. Any requests beyond the sandbox will query the user. ActiveX controls will never be allowed to run.
Medium Security | A zone set for Medium Security will allow applets to have up to 1 MB of scratch space on the client computer, if it is requested in the cabinet file signature. Any requests beyond those restrictions will cause the user to be queried. Applets signed with Medium permissions may also call user-directed file I/O routines. These routines will present dialogs to the user and ensure that all file operations are done with user intervention. ActiveX controls will also prompt the user before running.
Low Security | A zone set for Low Security will allow applets to run fully trusted, if they request to do so in their signature. ActiveX controls will prompt the user before running.
Custom | The user or the administrator defines Custom Security levels. They may also allow ActiveX Controls to run without prompting, whereas the predefined zones do not have that option.

For more information on how zones are configured and used, see the online Help for Internet Explorer.

How Cabinet File Signing Works with Internet Explorer Zones

When a signed cabinet file is downloaded from a page, the signature is examined to see if it contains permission information. If so, Internet Explorer and the Microsoft VM for Java work together to determine what the applet will be allowed to do. This determination is based on the security level of the Zone the cabinet file is downloaded from, the permissions requested in the cabinet signature, and the response of the user, if needed.

If a cabinet file is signed at a certain security level, it will be allowed to run with that level of permissions without any intervention from the user, but only if the Zone is set at that same level or less secure. However, if a cabinet file is requesting permissions greater than those that can be automatically granted by a zone, the user is presented with a query. If the user agrees to let the applet run, it is run with the signed permissions. Otherwise, the applet will not be allowed to run.

The following chart details this behavior.

Cabinet files signed with this level
 |  | High | Medium | Low
Zone | High | Runs in High | Query (Yes = Medium) | Query (Yes = Low)
Level | Medium | Runs in High | Runs in Medium | Query (Yes = Low)
 | Low | Runs in High | Runs in Medium | Runs in Low

If the user is presented with a query and denies the request, the applet will not run.

Using Signcode with Java Permission Information

To add the Java permission information into the signature, use the -j JavaSign.dll option to signcode. You may also specify the -jp option for finer control over the exact permissions in the signature.

The command line for signcode with the Java permission information is as follows:

signcode [options] -j JavaSign.dll [-jp level] [more options]
-j JavaSign.dll The option that tells signcode to use Java permission information.

-jp level Level is an optional string that tells what level of permissions to encode in the cabinet file. This string must appear immediately after the -j parameter. You can use any of the flags shown in the following table.

Low | Medium | High
LowX | MediumX | HighX

If this option is not specified, a default level of LowX will be used. These exact permissions associated with these flags are described in Cabinet File Permission Levels and Cabinet Files and ActiveX.

If the string is not one of the six predefined levels, it is accepted as the name of an .INI file that specifies the permissions to encode. You can create this .INI file by hand, following the example provided by the sample permissions .INI file, or you can use the piniedit tool to generate the .INI file for you. The following example shows a section of a sample permissions .INI file that you can use to specify special permissions.

;
; ClientStoragePermission
;
[com.ms.security.permissions.ClientStoragePermission]
; Limit is in bytes
Limit=100
RoamingFiles=true
GlobalExempt=true

;
; ThreadPermission
;
[com.ms.security.permissions.ThreadPermission]
AllThreadGroups=true
AllThreads=true

The ClientStoragePermission class represents a permission for controlling access to client-side storage that is available through the ClientStore class. The ThreadPermission class represents a permission that controls the ability to create and manipulate threads and thread groups. For more information on these and other permissions, see the com.ms.security.permissions package.

Using the Chkjava Utility

To examine the permission information in a signed cabinet file, run

chkjava filename

where filename is the name of the filename to verify.

How to Sign a Cabinet File with Java Permissions

The following steps show you how to sign a cabinet file with Java permissions.

  1. First, create a certificate with the MakeCert program.
    C:\..\>makecert -sk MyKeyName -n "CN=My Publisher Name" MyTestCert.cer

  2. Turn your certificate into a test Software Publisher Certificate (SPC). A valid SPC is obtained from a Certification Authority.
    C:\..\>cert2spc MyTestCert.cer MyTestCert.spc

  3. Sign the cabinet file with the permissions. The following command line signs MyApplet.CAB with medium permissions, using the key and certificate created previously.
    C:\..\>signcode -j javasign.dll -jp medium -spc MyTestCert.spc
   -k MyKeyName MyApplet.cab

  4. Verify that the appropriate permissions have been correctly encoded in the file.
    C:\..\>chkjava MyApplet.cab

More Information

For more information on all of the parameters for makecert, cert2spc, signcode, and chktrust, see the Microsoft SDK for Java Tools quick reference section.

For more information on how zones are configured and used, see the online help for Internet Explorer.


Using Cprmedit

Working with MS VM
In this topic

* Overview

* Using CPrmEdit

* Editing Permission Sets

Tools | Previous | Tools | Next
Custom Permission Editor | Previous | Tools | Next

Overview

The cprmedit tool enables you to edit Java permissions for specific security zones using a graphical user interface. The permissions set by cprmedit are recognized by Microsoft® Internet Explorer 4.0 and later. The user interface presented by the cprmedit tool is similar to the dialog boxes in Internet Explorer 4.01 that enable administrators to set security options.

Using CPrmEdit

To run the Custom Permission Editor, type cprmedit on the command line. The Custom Permission Editor dialog box will appear. To edit the permissions for a particular zone, choose one of the zones listed in the drop-down list box. For each zone, there are three sets of permissions that you can edit.

Permission Set | Description
Unsigned Permissions | Permissions that are granted to unsigned content.
Trusted Signed Permissions | Permissions (requested by signed content) that do not require user approval.
Untrusted Signed Permissions | Permissions (requested by signed content) that require user approval or permissions that are absolutely denied.

Each permission set has its own area in the dialog box, and each area contains check boxes and buttons that are used to define the group. The following paragraphs explain how you can use these check boxes and buttons to define a permission set.

Unsigned Permissions

When editing Unsigned Permissions, you can select the "Unsigned content is fully trusted" check box to give all permissions to unsigned content. However, this setting is not recommended because damaging content could be run on your computer. If you do not select this check box, you can select the Edit button to specify a set of permissions to give to unsigned content.

Trusted Signed Permissions

Similarly, for Trusted Signed Permissions, you can select the "Grant all permissions requested by signed content" check box to give signed content all requested permissions. (This setting is not recommended either.) If you do not choose this check box, you can select the Edit button to specify a set of permissions to give to the Trusted Signed Permissions group.

Untrusted Signed Permissions

When editing the Untrusted Signed Permissions group, you must choose a radio button to indicate whether the group of untrusted signed permissions is a group that causes the user to be queried or causes the signed content to be refused. The following table explains the meaning of the two buttons.

Button Name | Description
Ask for approval of untrusted permissions | Indicates that if the content is signed and the requested permission set is not a subset of the Trusted Signed Permissions group and the requested permission set is a subset of the Untrusted Signed Permissions set, then the user will be queried. Signed content requesting any other permission set that is not a subset of the Trusted Signed Permission set is automatically refused.
Refuse untrusted permissions without asking | Indicates that if the content is signed and the requested permission set is not a subset of the Trusted Signed Permissions group, then if the requested permission set is a subset of the Untrusted Signed Permissions group, the content is automatically refused. The user is queried if any other permission set is requested.

If you choose the "Apply to all permissions not specifically allowed" check box, all permissions are included in the Untrusted Signed Permissions group. Any permission set that is not a subset of the Trusted Signed Permissions group will be queried or denied based on the setting of the radio button. Specifically, one of the following results will occur, depending on which radio button you selected.

Button Selected | Result
Ask for approval of untrusted permissions | The user will be queried about all signed content that requests a permission that is not in the Trusted Signed Permissions group
Refuse untrusted permissions without asking | Signed content will be automatically refused if a requested permission is not in the Trusted Signed Permissions group

If you do not select the "Apply to all permissions not specifically allowed" check box, you can select the Edit button to specify a set of permissions to give to the Untrusted Signed Permissions group.

Editing Permission Sets

To edit a set of permissions, select the Edit button in the area designated for the permission set you are interested in. The Edit Custom Permissions dialog box appears. There are seven tabs on this box, each of which indicates permissions that can be edited.

Tab Name | Permission Description
File | The ability to read, write, or delete files.
Registry | The ability to read, write, delete, create, or open keys in the registry.
Network | The ability to connect or bind to various hosts or ports on the network.
Client Services | The ability to access client storage, perform user-directed file I/O, access user interface functionality, print, use multimedia libraries, and access security classes.
System | The ability to run programs, access system properties, manipulate threads, and redirect system streams.
Reflection | The ability to access public or declared members of a class, based on the class loader.
Custom | The ability to use a non-system permission designed by the user.

Choose the tab for the permission that you want to edit.

To edit a permission, Select the access types from the drop-down list boxes and fill in the text boxes to indicate parameters for the permission. For File, Registry, and Network permissions as well as property and execution permissions under the System tab, you can use the asterisk (*) and the question mark (?) as wildcard characters in any text box. For property and execution permissions, you can use the semicolon (;) as a delimiter.

You can use the Medium, High, or Clear button to set all the permissions in the set to a Medium security setting, High security setting, or to clear the permission settings, respectively. Be aware that using the Medium, High, or Clear button affects all of the permissions, not just the currently selected Tab. Any previous edits to the permissions will be erased and reset to Medium, High, or Clear. You can navigate between permissions by selecting the Tab buttons.

When you have finished editing a set of permissions, select OK. This returns you to the Custom Permission Editor dialog box. You can edit another permission group if you want to. To save the chosen settings but continue to edit other permission settings, select the Apply button. To save the settings you have chosen and close the dialog box, select OK. To quit without saving your settings, select the Cancel button.

The following reference section lists each permission tab and explains in further detail how to edit the permissions under that tab.

File

Select the access type that you want to edit from the drop-down list box. This can be Read, Write, or Delete. To add file that you want to include, in the Include files text box, enter the name of the file (or a pattern that uses * and/or ?). Then select the Add button. For example, if you want to add read permission for all files ending in .doc, you would select Read from the drop-down list box, type *.doc in the Include files text box, and then select the Add button.

To add a file that you want to exclude, in the Exclude files text box, enter the name of the file (or a pattern that uses * and/or ?). Then select the Add button.

To remove a file, select the name of the file from the included or the excluded file list, and then select the Remove button.

Repeat this process until you have added or removed the appropriate included or excluded files from the access types.

Registry

Select the access type from the drop-down list box. This can be either Read, Write, Delete, Create, or Open. To add a key that you want to include, enter the name of the key (or a pattern that uses * and/or ?) in the Include keys text box. Select the Add button.

To add a key that you want to exclude, enter the name of the key (or a pattern that uses * and/or ?) in the Exclude keys text box. Select the Add button.

To remove a key, select the name of the key from the included or the excluded key list, and then select the Remove button.

Repeat this process until you have added or removed the appropriate included or excluded keys from the access types.

Network

Select the access type from the drop-down list box. This can be either Connect, Bind, Multicast, or Global Ports.

To add a host to include, enter the name or the IP address in the host text box. You can specify a list of single ports, port ranges, or both by entering them in the Include Ports text box, separated by commas. For example, 27-80, 95, 100-102 would be a valid list of ports. With the Multicast access type, you can only specify the host. If you have chosen the Global Ports access type, you can only specify the ports, not the host. Select the Add button.

To add a host to exclude, enter the host name or the IP address in the Exclude host text box. You can enter the list of ports and port ranges in the Exclude Ports text box, separated by commas. Select the Add button.

To remove a host or port, select the name of the host or port from the included or excluded list, and then select the Remove button.

Repeat this process until you have added or removed the appropriate included or excluded hosts or ports from the access types.

Client Services

Client Storage

To modify the amount of storage allowed for client storage, you can enter a new number of kilobytes in the "Storage Limit" check box.

To make client storage exempt from global storage limits, select the "Exempt from global storage limit" check box. To allow access to roaming files, select the "Access to roaming files" check box.

Miscellaneous

You can allow or deny access to printing services by selecting or clearing the "Access to printing services" check box.

You can allow or deny access to multimedia libraries by selecting or clearing the "Access to multimedia libraries" check box.

You can allow or deny access to security classes by selecting or clearing the "Access to security classes" check box.

User Directed File I/O

To allow or deny user-directed read access to files, select or clear the "Read access" check box.

To allow or deny user-directed write access to files, select or clear the "Write access" check box.

User Interface Restrictions

To allow or deny the creation of file dialog boxes, select or clear the "Create file dialogs" check box.

To allow or deny the creation of top-level windows, select or clear the "Create top level windows" check box. If you allow top-level window creation, you can enable or disable the applet warning banner by clearing or selecting the "Turn off applet warning banner" check box.

To allow or deny access to the Clipboard, select or clear the "Clipboard access" check box.

System

System Property Access

To allow access to specific system properties, enter the name of the property or properties (or a pattern that uses an asterisk (*) or a question mark (?)) in the Include properties text box, separating property names with semicolons (;).

To deny access to specific system properties, enter the name of the property or properties (or a pattern that uses an asterisk (*) or a question mark (?)) in the Exclude properties text box, separating property names with semicolons (;).

To allow access to properties that are described by a particular suffix, enter the suffix in the Suffixes text box. For instance, entering the "applet" suffix would allow access to a system property "X" if the system property "X.applet" exists and is set to true.

To allow or deny unrestricted access to system properties, select or clear the "Unrestricted Access" check box.

Thread Access

To allow or deny access to Thread objects, select or clear the "Thread objects" check box.

To allow or deny access to Thread group objects, select or clear the "Thread group objects" check box.

Execution Access

To allow specific files to be executed, enter the name of the file in the Include text box. You can use the asterisk (*) or the question mark to indicate a pattern. For instance, you could allow all files beginning with "my" to be executed by entering my* in the text box. Similarly, you could allow all files that have "j" as the second character to be executed by entering ?j* in the text box.

To deny the right to execute specific files, enter the name of the file in the Exclude text box.

To allow or deny the right for all applications to be executed, select or clear the "Unrestricted execution of applications" check box.

System Stream Redirection Access

To allow or deny the ability to redirect the standard system input stream, System.in, select or clear the "Standard input stream" check box.

To allow or deny the ability to redirect the standard system output stream, System.out, select or clear the "Standard output stream" check box.

To allow or deny the ability to redirect the standard system error stream, System.err, select or clear the "Standard error stream" check box.

Reflection

Public Member Reflection

To allow or deny access to public members of classes loaded by the same class loader, select or clear the "Same loader" check box.

To allow or deny access to public members of classes loaded by a different class loader, select or clear the "Different loader" check box.

To allow or deny access to public members of classes loaded by a system loader, select or clear the "System loader" check box.

Declared Member Reflection

(A declared member is any member of a class.)

To allow or deny access to declared members of classes loaded by the same class loader, select or clear the "Same loader" check box.

To allow or deny access to declared members of classes loaded by a different class loader, select or clear the "Different loader" check box.

To allow or deny access to declared members of classes loaded by a system loader, select or clear the "System loader" check box.

Custom

To add a parameter to a Custom permission (a non-system permission), enter the name of the permission class in the Class name text box. Then enter the parameter in the Parameters text box. Select the Add button.

To remove a parameter from a Custom permission, enter the name of the permission class in the Class name text box. Then enter the parameter in the Parameters text box. Select the Remove button.

The class must be on the class path, or it will not be found. In addition, the class should support the EncodeFormats.TEXT encoding if it requires parameters and needs to support the Custom Permission Editor.

Note: If you edit a custom permission class that does not have the thread permission, the Custom Permissions Editor will add the thread permission so that unrestricted access to threads and thread groups is denied.

Note: When using a character such as an asterisk, a question mark, or a semicolon as a literal in expressions, you must enclose the entire expression in double quotes and precede the character with a backslash when it is used as a literal. You must also precede each literal backslash with a backslash. For example, if you want to specify all file names in the c:\windows\ directory whose second character is an asterisk (*), you would enter the following, including the double quotes: "c:\\windows\\?\**" .

For more information on security for the Microsoft VM for Java, see the Trust-Based Security for Java article, the com.ms.security package, and the com.ms.security.permissions package.


Java Permissions .INI Values Reference

Custom Java permissions can be set by specifying a custom permissions .ini file when using the signcode tool's -jp command line option. These .ini files can be generated by hand, or by using the cprmedit and piniedit tools included with the Microsoft SDK for Java. For more information on setting Java permissions with the signcode tool for Microsoft® Internet Explorer 4.01 (and later), see Using Signcode with Java Permission Information.

When using an .ini file to set custom permissions, you set permission variables to values that define the permissions you want. The following table can be used as a reference to help you decide how to set these variables. For each permission, the variables are listed and the meaning of each variable is described.

Permissions

ExecutionPermission

Variable | Meaning
Unrestricted | If true, any application can be executed.
IncludeNames | These applications can be executed.
ExcludeNames | These applications cannot be executed.

ClientStoragePermission

Variable | Meaning
Limit | The maximum number of bytes of data that can be written.
RoamingFiles | If true, roaming files can be created.
GlobalExempt | If true, the storage limit is an absolute limit. If false, the limit is also bounded by the global storage limit.

FileIOPermission

Variable | Meaning
IncludeRead | These files can be read.
ExcludeRead | These files cannot be read.
IncludeWrite | These files can be written to.
ExcludeWrite | These files cannot be written to.
IncludeDelete | These files can be deleted.
ExcludeDelete | These files cannot be deleted.
ReadFileURLCodeBase | If true, classes that have this permission will have read access to the directory that they were loaded from if that location is a file://URL.

MultimediaPermission

No specific settings are required.

NetIOPermission

Variable | Meaning
IncludeConnectIPs | General communication with the hosts at these IP addresses is allowed.
ExcludeConnectIPs | General communication with the hosts at these IP addresses is not allowed.
IncludeBindIPs | Listening for connections on these local IP addresses is allowed.
ExcludeBindIPs | Listening for connections on these local IP addresses is not allowed.
IncludeMulticastIPs | The multicast groups specified by these IP addresses can be joined.
ExcludeMulticastIPs | The multicast groups specified by these IP addresses cannot be joined.
IncludeConnectHosts | General communication with these hosts is allowed.
ExcludeConnectHosts | General communication with these hosts is not allowed.
IncludeBindHosts | Listening for connections with these hosts is allowed.
ExcludeBindHosts | Listening for connections with these hosts is not allowed.
IncludeMulticastHosts | The multicast groups specified by these hosts can be joined.
ExcludeMulticastHosts | The multicast groups specified by these hosts cannot be joined.
IncludeConnectGlobalPorts | General communication with allowed hosts or IP addresses using the specified ports is allowed.
ExcludeConnectGlobalPorts | General communication with allowed hosts or IP addresses using the specified ports is not allowed.
IncludeBindGlobalPorts | Listening for connections with allowed hosts on the local IP addresses using the specified ports is allowed.
ExcludeBindGlobalPorts | Listening for connections with allowed hosts on the local IP addresses using the specified ports is not allowed.
ConnectToFileURLCodebase | If true, connection permissions are adjusted so that general communication is allowed with the location that the class with this permission is loaded from if that location is a file://URL/codebase.
ConnectToNonFileURLCodebase | If true, connection permissions are adjusted so that general communication is allowed with the location that the class with this permission is loaded from if that location is a non-file://URL/codebase.

PrintingPermission

No specific settings are required.

PropertyPermissison

Variable | Meaning
Unrestricted | If true, any system property can be accessed.
AllowedSuffixes | These suffixes indicate system properties that could be accessed based on the following rule: If suffix "x" is listed, you have access to a system property "y" if a second system property named "y.x" exists that is set to true.
IncludedProperties | System properties represented by these WildcardExpressions can be accessed.
ExcludedProperties | System properties represented by these WildcardExpressions cannot be accessed.

ReflectionPermission

Variable | Meaning
PublicSame | If true, access is allowed to public members of any class loaded by the same loader as the class initiating the reflection operation.
PublicDifferent | If true, access is allowed to public members of a non-system class loaded by a different loader than the class initiating the reflection operation.
PublicSystem | If true, access is allowed to public members of any system class.
DeclaredSame | If true, access is allowed to any member of any class loaded by the same loader as the class initiating the reflection operation.
DeclaredDifferent | If true, access is allowed to any member of a non-system class loaded by a different loader than the class initiating the reflection operation.
DeclaredSystem | If true, access is allowed to any member of any system class.

RegistryPermission

Variable | Meaning
IncludeOpen | These keys can be opened.
ExcludeOpen | These keys cannot be opened.
IncludeRead | These keys/values can be read.
ExcludeRead | These keys/values cannot be read.
IncludeWrite | These keys/values can be modified.
ExcludeWrite | These keys/values cannot be modified.
IncludeDelete | These keys/values can be deleted.
ExcludeDelete | These keys/values cannot be deleted.
IncludeCreate | These keys/values can be created.
ExcludeCreate | These keys/values cannot be created.

SecurityPermission

No specific settings are required.

SystemStreamsPermission

Variable | Meaning
SetSysIn | If true, the system stream java.lang.System.in can be set.
SetSysOut | If true, the system stream java.lang.System.out can be set.
SetSysErr | If true, the system stream java.lang.System.err can be set.

ThreadPermission

Variable | Meaning
AllThreadGroups | If true, all thread groups can be accessed.
AllThreads | If true, all threads can be accessed.

UIPermission

Variable | Meaning
ClipboardAccess | If true, the system clipboard can be accessed.
TopLevelWindows | If true, top-level windows can be created.
NoWarningBanners | If true, top-level windows do not require warning banners.
FileDialogs | If true, file dialog boxes can be created.
EventQueueAccess | If true, the AWT event queue can be accessed.

UserFileIOPermission

Variable | Meaning
CanRead | If true, user-directed read operations are allowed.
CanWrite | If true, user-directed write operations are allowed.


Sample Permissions .INI File

This is a sample .INI file, complete with comments, that shows you the format that is accepted by signcode for special permissions. You can generate your own .INI file by using this one as a template or by using the piniedit tool included with the SDK for Java. Each section represents one of the com.ms.security.permissions classes.

For a complete reference to the permissions and their values, see the Java Permissions .INI Values Reference. See Using Signcode with Java Permission Information for more information on using .INI files to specify special permissions when signing code.

;
; PermissionDataSet INI encoding
;
; Sample INI File
;
;

; A semi-colon (;) at the beginning of a line signifies a
; comment to the end of the current line.

; AllowActiveX tells the sign tool to sign with full ActiveX
; permissions, in addition to any other permissions.
;[AllowActiveX]

; If the FullyTrusted section exists, all other
; permissions are ignored.
;[FullyTrusted]

;
; ExecutionPermission
;
[com.ms.security.permissions.ExecutionPermission]
; If Unrestricted is true, the other settings are ignored.
;Unrestricted=true
Unrestricted=false
IncludeNames=*.exe;*.txt;activextest
ExcludeNames=foo.exe

;
; ClientStoragePermission
;
[com.ms.security.permissions.ClientStoragePermission]
; Limit is in bytes.
Limit=100
RoamingFiles=true
GlobalExempt=true

;
; FileIOPermission
;
[com.ms.security.permissions.FileIOPermission]
IncludeRead=blah;c*
ExcludeRead=crayon
IncludeWrite=89kandaf;-l?daf;s
ExcludeWrite=s;-lddaf
IncludeDelete=45*.4;*.*.*.*;****a;??4nf
ExcludeDelete=ff4nf
ReadFileURLCodebase=true

;
; MultimediaPermission
;
[com.ms.security.permissions.MultimediaPermission]
; No specific settings required for MultimediaPermission

;
; NetIOPermission
;
[com.ms.security.permissions.NetIOPermission]
IncludeConnectIPs=1.2.3.4:1-102
ExcludeConnectIPs=
IncludeBindIPs=4.4.4.4:4-55,97;4.4.4.4:4
ExcludeBindIPs=4.4.4.4:8
IncludeMulticastIPs=
ExcludeMulticastIPs=
IncludeConnectHosts=www.microsoft.com:80
;IncludeConnectHosts=www.microsoft.com
ExcludeConnectHosts=
IncludeBindHosts=
ExcludeBindHosts=
IncludeMulticastHosts=
ExcludeMulticastHosts=
IncludeConnectGlobalPorts=3-100, 999
ExcludeConnectGlobalPorts=43, 999
IncludeBindGlobalPorts=43
ExcludeBindGlobalPorts=
ConnectToFileURLCodebase=true
ConnectToNonFileURLCodebase=true

;
; PrintingPermission
;
[com.ms.security.permissions.PrintingPermission]
; No specific settings required for PrintingPermission

;
; PropertyPermission
;
[com.ms.security.permissions.PropertyPermission]
; If Unrestricted is true, the other settings
; are ignored.
Unrestricted=false
AllowedSuffixes=applet;foobar
IncludedProperties=*system*
ExcludedProperties=*cryptsystem*

;
; ReflectionPermission
;
[com.ms.security.permissions.ReflectionPermission]
PublicSame=true
PublicDifferent=true
PublicSystem=true
DeclaredSame=true
DeclaredDifferent=true
DeclaredSystem=true

;
; RegistryPermission
;
[com.ms.security.permissions.RegistryPermission]
IncludeOpen=hk*
ExcludeOpen=*N
IncludeRead=fdjl
ExcludeRead=
IncludeWrite=*?5$$
ExcludeWrite=gd5$$
IncludeDelete=*
ExcludeDelete=d
IncludeCreate=*
ExcludeCreate=s

;
; SecurityPermission
;
[com.ms.security.permissions.SecurityPermission]
; No specific settings required for SecurityPermission

;
; SystemStreamsPermission
;
[com.ms.security.permissions.SystemStreamsPermission]
SetSysIn=true
SetSysOut=true
SetSysErr=true

;
; ThreadPermission
;
[com.ms.security.permissions.ThreadPermission]
AllThreadGroups=true
AllThreads=true

;
; UIPermission
;
[com.ms.security.permissions.UIPermission]
ClipboardAccess=true
TopLevelWindows=true
NoWarningBanners=false
FileDialogs=true
EventQueueAccess=true

;
; UserFileIOPermission
;
[com.ms.security.permissions.UserFileIOPermission]
CanRead=true
CanWrite=true


About the Microsoft Virtual Machine

Welcome
Release Notes
Download the SDK
Articles
Packages
Tools
Microsoft VM
AFC
J/Direct
Java & Native Code
Package Manager
Security
Internationalization

Microsoft VM | Welcome!
 | Welcome!

About the Microsoft Virtual Machine

The Microsoft Win32 Virtual Machine (VM) for Java provides a variety of APIs that give ISVs and tools vendors access to the VM's underlying features. This information is especially useful if you are developing Java development tools for use with the Microsoft VM for Java.

Microsoft VM for Java Object Model
Describes the benefits of the VM Object Model as it applies to object decomposition and performance.
Java Debugger Interfaces
Describes the debugging APIs provided by the Microsoft VM for Java. Use these to implement your Java debugger.
Invocation Interfaces
Describes the invocation APIs provided by the VM.
Just-In-Time Compilation and the Microsoft VM for Java
Describes the Just-In-Time (JIT) compiler used by the Microsoft VM for Java for improved performance.
Overview of the COM Attributes for Java Class Files
Describes the extended Microsoft COM attributes.


Introduction

The following sections describe the benefits of the object model as it applies to object decomposition and performance.
Goals of the Object Model
Object Components


Goals of the Object Model

This object model facilitates efficient decomposition of objects into their member components. It enhances operational performance by providing very fast and deterministic access to multiply inherited interface members (abstract members and constant fields) and singly inherited virtual methods, while conforming to the current Java language and VM specification.

The Microsoft VM Object Model also provides very low per-object overhead while still containing information required for distinguishing between objects and arrays, synchronizing objects through monitors and Wait and Notify functionality. This additional information is allocated in a "lazy" fashion, requiring additional overhead only as necessary.

Operations that this model optimizes include:

  • Fast resolution of an object's interface vtables, which you can use to access interface methods quickly and efficiently.
  • Accessing data fields in the object.
  • Accessing virtual methods of the class or interface hierarchy.
  • Entering an object's monitor.
  • Blocking a thread on an object until that object has been "notified."


Object Components

In the Microsoft VM for Java, a class is a description of an object type that includes declarations of data and method members. Classes can inherit all types of members from parent classes including constants (static final fields), static fields and methods that exist once for all instances of a class in one namespace and are shared between instances, dynamic fields that exist separately in every instance of the class type, and dynamic methods that operate on specific instances of a class through a "this" pointer.

Interfaces declare only abstract, dynamic methods, constants fields, and properties (which you can think of as "virtual fields"). The methods declared in an interface can be implemented only in a class, not in an interface. When a class implements an interface, it is guaranteed to contain an implementation for every method in that interface, and all interfaces that the interface extends.

This object model specifies layout of the following object components.

  • Synchronization block
  • Methods
  • Interfaces
  • Dynamic fields

When a base interface is loaded, vtables are created for its member methods, fields, and interfaces that it extends. The field tables are simply arrays of the field description structures; methods also are described by arrays of methods descriptions, but have vtables associated with them that can be accessed by indexes that remain constant throughout the hierarchy of a class.

When a base class is loaded, the Microsoft VM creates tables just as with interfaces for its member fields and methods. The class vtable differs from an interface vtable only in that its header contains the number of interface slots found below the object, and a pointer to the actual class descriptor that owns the vtable. These elements are followed by interface vtables and then by method pointers which are not declared in any of the implemented interfaces. Method pointers are pointers to the native Just-In-Time (JIT) code entry points or a native interpreter stub (call compatible with JIT code) of methods implemented in the class or its superclasses. An interface vtable consists simply of an array of methods.

Now that you know what a vtable looks like, look at how it is used in the context of creating an object—treating it as an instance of one of its superclasses, or treating it as an instance of one of its implemented interfaces.

The following example class contains one field and one method. The class, "foo", looks like the following:

public class foo {

public int Field1;

    void Method1()  {}
}

Normally, a Java-compatible compiler will create a constructor for this class, and the object will inherit methods from the Object class. For the purpose of this example, pretend that all you get is one field, Field1, and one method, Method1. The vtable for this class would look like:

An object of type foo would contain space for Field1, a main vtable pointer, and a pointer to the synchronization block. Note that the synchronization block for an object is not really present unless it is used. It is created "lazily" to conserve space in nonsynchronized objects. The vtable exists only once per class and is shared among objects of that class type, but the synchronization block is per instance.

The following illustration shows an object of type foo.

If you declare two interfaces, IFCA and IFCB, IFCA contains one method, Method2; IFCB contains two methods, Method3 and Method4. If you then declare another class, "bar", which extends foo and implements IFCA and IFCB, you get an object that looks like the following illustration.

An interface's vtable is simply an array of Just-In-Time–compiled, code-callable methods. If an interface extends other interfaces, it has those interface vtables inside it. When the Microsoft VM for Java resolves an object that implements an interface, that interface vtable is copied to the main vtable when it is encountered. The nested interface offsets are calculated by adding their offsets in the implemented interface to the current position in the new vtable.

Since some aspects of the object model used internally in the Microsoft VM for Java are subject to change, all data structures besides the object data itself should be considered abstract and accessed only through functions available in Java.


Introduction

The following sections describe the debugging APIs provided by the Microsoft Win32 VM for Java.
Registration and Notification Interfaces
Static Information Interfaces
Dynamic Information Interfaces
Execution Control Interfaces
Implementation Notes
Pseudocode Debugger Initialization Example


Registration and Notification Interfaces

Working with MS VM
In this topic

* IRemoteDebugManager : IUnknown

* IEnumRemoteProcess : IUnknown

* IRemoteDebugManagerCallback : IUnknown

* IRemoteProcess : IUnknown

* IRemoteProcessCallback : IUnknown

Microsoft VM | Previous | VM | Next
Java Debugger Interfaces | Previous | VM | Next

Registration and Notification Interfaces

Use these interfaces to register namespaces for debugging and to receive notification of new namespaces.

IRemoteDebugManager : IUnknown

Provides access to all currently running namespaces. Also provides a way to debug new namespaces.

RegisterCallback

HRESULT RegisterCallback(IRemoteDebugManagerCallback *pCallback)

Parameter | Description
[in] pCallback | Callback that should receive notification about new namespace creations.

Detach

HRESULT Detach(void)

Detaches the IRemoteDebugManagerCallback attached by the previous call to RegisterCallback.

GetActiveProcesses

HRESULT GetActiveProcesses(IEnumRemoteProcess **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for all the currently running namespaces in the system.

RequestCreateEvent

HRESULT RequestCreateEvent(LPCOLESTR pcszProcessName, DWORD dwParentProcessId)

Notifies the debug manager that the debugger is interested in debugging the named applet when it is run in the given host Microsoft® Win32® process.

Parameter | Description
[in] pcszProcessName | Name of the applet class to debug.
[in] dwParentProcessId | Win32® process ID of the process that the applet will be run in.

IEnumRemoteProcess : IUnknown

Enumerates running namespaces.

Next

HRESULT Next(ULONG celt, IRemoteProcess *rgelt[], ULONG *pceltFetched)

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteProcess **ppEnum)

IRemoteDebugManagerCallback : IUnknown

Notifies the debugger about requested new namespace creations.

ProcessCreateEvent

HRESULT ProcessCreateEvent(IRemoteProcess *pProcessNew, IRemoteProcess *pProcessParent)

This notification is sent when a new namespace is being created. The pProcessParent parameter is NULL if the namespace is not being created as the child of another namespace.

Parameter | Description
[in] pProcessNew | Namespace being created.
[in] pProcessParent | Namespace that caused the new namespace to be created.

IRemoteProcess : IUnknown

Represents a single Java namespace running within a Java VM. Note that it does not represent the operating system process that the Java VM is being run in.

RegisterCallback

HRESULT RegisterCallback(IRemoteProcessCallback *pCallback)

Tells the namespace that it is being debugged, and provides a callback that is to receive debug event notifications.

Parameter | Description
[in] pCallback | Address of the interface that is to receive notifications for this namespace.

Detach

HRESULT Detach(void)

Detaches the IRemoteProcessCallback registered by the previous call to RegisterProcess.

Break

HRESULT Break(void)

Performs an asynchronous break on all threads in this namespace. All threads will be stopped in break state. This is an asynchronous function call.

GetGlobalContainerObject

HRESULT GetGlobalContainerObject(IRemoteContainerObject **ppGlobalContainerObject)

Parameter | Description
[out] ppGlobalContainerObject | Returns the global object for this namespace.

FindClass

HRESULT FindClass(LPCOLESTR pcszClassName, IRemoteClassField **ppClassType)

Parameter | Description
[in] pcszClassName | Name of the class to find.
[out] ppClassType | Returns the specified class. If the class is not already loaded in the namespace, it is loaded.

TraceMethods

HRESULT TraceMethods(BOOL bTraceOn)

When method call tracing is on, each method call generates a call to IRemoteProcessCallback::TraceEvent.

Parameter | Description
[in] bTraceOn | Set to TRUE to enable method call tracing, or FALSE to disable method call tracing.

GetThreadGroups

HRESULT GetThreadGroups(IEnumRemoteThreadGroup **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the thread groups in the namespace.

IRemoteProcessCallback : IUnknown

Communicates asynchronous notifications from the Java VM to the debugger. No debuggee execution occurs during the handling of these events. The debugger returns S_OK to leave execution suspended in the source namespace, or S_FALSE to continue execution in the source namespace. The pThread input argument to each event notification method is a thread object that represents the thread that generated the event.

DebugStringEvent

HRESULT DebugStringEvent(IRemoteThread *pThread, LPCOLESTR pcszDebugString)

Notification sent when the debuggee outputs a string.

Parameter | Description
[in] pcszDebugString | String from the debuggee.

CodeBreakpointEvent

HRESULT CodeBreakpointEvent(IRemoteThread *pThread)

Notification sent when a code breakpoint has been hit in the debugger.

DataBreakpointEvent

HRESULT DataBreakpointEvent(IRemoteThread *pThread, IRemoteObject *pObject)

Notification sent when a data breakpoint has been hit in the debugger.

Parameter | Description
[in] pObject | Object that changed to cause the breakpoint to be triggered.

ExceptionEvent

HRESULT ExceptionEvent(IRemoteThread *pThread, IRemoteClassField *pExceptionClass, EXCEPTIONKIND exceptionKind)

Notification sent when an exception occurs.

Parameter | Description
[in] pExceptionClass | Class of the thrown object.
[in] exceptionKind Kind of exception that occurred.
typedef enum exceptionkind {
    EXCEPTION_KIND_FIRST_CHANCE	= 0x01,
    EXCEPTION_KIND_LAST_CHANCE	= 0x02,
} EXCEPTIONKIND;

StepEvent

HRESULT StepEvent(IRemoteThread *pThread)

Notification sent when an execution step completes.

CanStopEvent

HRESULT CanStopEvent(IRemoteThread *pThread)

Notification sent during a range step when the debuggee makes a function call.

BreakEvent

HRESULT BreakEvent(IRemoteThread *pThread)

Notification sent when an asynchronous break occurs in response to IRemoteProcess::Break.

ThreadCreateEvent

HRESULT ThreadCreateEvent(IRemoteThread *pThread)

Notification sent when a thread is created.

ThreadDestroyEvent

HRESULT ThreadDestroyEvent(IRemoteThread *pThread)

Notification sent when a thread is destroyed.

ThreadGroupCreateEvent

HRESULT ThreadGroupCreateEvent(IRemoteThread *pThread, IRemoteThreadGroup *pThreadGroup)

Notification sent when a thread group is created.

Parameter | Description
[in] pThreadGroup | New thread group.

ThreadGroupDestroyEvent

HRESULT ThreadGroupDestroyEvent(IRemoteThread *pThread, IRemoteThreadGroup *pThreadGroup)

Notification sent when a thread group is destroyed.

Parameter | Description
[in] pThreadGroup | Destroyed thread group.

ClassLoadEvent

HRESULT ClassLoadEvent(IRemoteThread *pThread, IRemoteClassField *pClassType)

Notification sent when a class is loaded.

Parameter | Description
[in] pClassType | Loaded class.

LoadCompleteEvent

HRESULT LoadCompleteEvent(IRemoteThread *pThread)

Notification sent when all classes have been loaded.

ClassUnloadEvent

HRESULT ClassUnloadEvent(IRemoteThread *pThread, IRemoteClassField *pClassType)

Notification sent when a class is unloaded.

Parameter | Description
[in] pClassType | Unloaded class.

TraceEvent

HRESULT TraceEvent(IRemoteThread *pThread)

Notification sent while tracing is enabled when a method is entered.

ProcessDestroyEvent

HRESULT ProcessDestroyEvent(IRemoteThread *pThread)

Notification sent when the namespace terminates. No further notifications are sent after ProcessDestroyEvent.


Java Debug Interfaces

Overview

The Java debug interfaces allow developers to write sophisticated programs for debugging Java applications and applets run in the Microsoft Win32 Virtual Machine for Java (Microsoft VM). These interfaces can also be used for debugging Java applications and applets that mix Java classes with native code for Win32.

The Java debug interfaces consist of a series of Component Object Model (COM) objects and interfaces implemented by the Microsoft VM. A debugger application is usually written in C, C++, or some other language that can access these published COM interfaces and objects for communicating with the Microsoft VM and control the Java execution environment. A debugger program written to use these COM interfaces must also implement two COM interfaces that are used as callback interfaces through which the Microsoft VM communicates with the debugger. Because these debug interfaces are all based on COM, debugger programs can be easily extended to allow remote debugging using Distributed COM (DCOM). These debug interfaces are also provided as wrapped COM interfaces in Java as a set of classes under the com.ms.debug package, enabling developers to write debugger programs in Java as well as C++. For simplicity, the examples that follow are written using C++ and local COM objects to illustrate the use of the Java debug interfaces.

To use these Java debug interfaces, debugging must be enabled in the Microsoft VM before the Java application or applet begins its execution. Debugging can be enabled in the Microsoft VM through particular environment variables or with Win32 registry settings.

The debug interfaces used by the Microsoft VM can be organized into several categories as shown in the following table.

Category | Purpose
Registration | Interfaces called by the debugger program to register with the Microsoft VM and request to be notified when specific events occur.
Notification | Callback interfaces that must be implemented by the debugger through which the Microsoft VM notifies the debugger of various events and returns requested information.
Static Information | Interfaces used by the debugger program to gather static information about the Java application or applet.
Dynamic Information | Interfaces used by the debugger program to gather dynamic information about the Java application or applet when it is executing.
Execution Control | Interfaces used by the debugger program to control the execution of a Java application or applet within the Microsoft VM.

The Microsoft VM includes sample code for two debugger applications that illustrate how to use these Java debug interfaces. One sample is written in C++ using these interfaces. A second example is written in Java using the com.ms.debug package, which consists of a set of Java-wrapped classes for these COM interface objects. These samples are installed under the Samples\Debugger subdirectory of the SDK for Java.


Using the Java Debug Interfaces

The following sections describe in detail how to use the Java debug interfaces. They include discussion of the following topics:

General Considerations when Using the Java Debug Interfaces

Enabling Debugging in the Microsoft VM

Registering with the Java Debug Manager

Enumerating Active Java Processes

Registering with a Remote Process

Implementing Callback Notification Interfaces

Retrieving Static Information

Enumerating Static Fields

Enumerating Line Number Information

Retrieving Dynamic Information

Enumerating Dynamic Fields

General Considerations when Using the Java Debug Interfaces

The Java debug interfaces consist of a large collection of COM objects with many methods. The design of many of these interfaces and methods, however, follow a consistent design pattern.

Communication between the debugger and the VM is handled through COM interfaces. The debugger requests information and communicates with the VM by calling methods on COM objects implemented by the VM. Similarly, the Microsoft VM runtime notifies the debugger program of events, and then and provides the requested information by calling methods on COM objects that the debugger implements. The debugger registers these callbacks by calling a register callback method.

The COM objects implemented by the Microsoft VM use consistent class factory and get methods to handle lists of similar objects. Many of the Getxx methods return an enumerator object. These different enumerator objects (for processes, threads, fields, and so on) implement a nearly identical set of methods. These methods support returning an array of objects, skipping some number of objects, resetting the enumerator to the beginning of the list, copying the current enumerator position to another object (cloning), and getting only the next object.

The Java debug interfaces use a consistent hierarchy of objects. The enumeration methods allow the debugger program to move down the hierarchy of objects. Various Getxx methods (GetContainer, GetSuperClass, and so on) allow the debugger program to move up the hierarchy.

Because the Java debug interfaces are based on COM, some general considerations apply when calling the interfaces that are implemented by the Microsoft VM.

Any memory that a debugger program allocates for use as a buffer that is passed as a parameter to any of these COM interfaces (an [in,out] or an [out] parameter as documented in the reference section on the Java debug interfaces) must be allocated using the CoTaskMemAlloc function. When this memory is no longer needed, it must be released using the CoTaskMemFree function. This is a COM requirement because the memory is being allocated across processes. It is also a necessity for DCOM compatibility.

If the debugger program continues to use any COM objects that are created as parameters to a method, the reference count for that object may need to be incremented to ensure that the object remains viable for the duration of the method call. This can be accomplished by calling the Addref method on the COM interface. The debugger program decrements the reference count on the object using the Release method when this object is no longer needed.

Enabling Debugging in the Microsoft VM

For the Java debug interfaces to be used, debugging must be enabled in the Microsoft VM before the Java application or applet begins execution. Debugging can be enabled in the Microsoft VM for Java in two ways:

  • Defining particular environment variables

  • Creating particular Win32 registry settings

The preferred method to enable debugging is to set special environment variables before starting the Microsoft VM (before launching Microsoft® Internet Explorer, for example) and executing the Java application or applet. Note that the value of these environment variables (when set) override the equivalent settings in the registry as shown in the following table.

Environment Variable | Description and Values
MSJAVA_ENABLE_DEBUGGING | Enables debugging when set to some value greater than 0. Valid values must be less than the value of a GUID.
MSJAVA_DEBUGGING_FLAGS | Specifies options for debugging, most of which deal with issues when debugging a mixture of native code and Java.

If the MSJAVA_ENABLE_DEBUGGING string exists in the Win32 environment space and is set to some value greater than 0 for a process, debugging is enabled in any Microsoft VM that subsequently begins executing within this environment.

If the MSJAVA_DEBUGGING_FLAGS string exists in the Win32 environment space, the value it is set to specifies a set of options that control special features of the Microsoft VM. These options can be a combination of the following.

Option | Value | Description
MSJDBG_AD2_DEBUGGING | 0x04 | When set, this enables additional semantics, enabling some new Java interfaces and changing the behavior of some older Java interfaces.
MSJDBG_NO_HARDWARE_BREAKPOINTS | 0x08 | When set, this notifies the Microsoft VM that hardware breakpoints should not be used on Microsoft® Windows NT® being run on Intel processors. If this value and the following value are not set, data breakpoints are available. When using a native debugger, such as Microsoft® Visual C++®, set this value. This option is ignored on DEC alpha systems running Windows NT. Hardware breakpoints are not used on Microsoft® Windows 95®.
MSJDBG_NO_PAGE_BREAKPOINTS | 0x10 | When set, this notifies the Microsoft VM that memory page faults for data breakpoints should not be used (applies to both Microsoft® Windows 95 and Windows NT being run on Intel processors). If this value and the previous value are not set, data breakpoints are available. When using Visual C++ for debugging, set this value. This option is ignored on DEC alpha systems running Windows NT.
MSJDBG_ENABLE_JIT_COMPILED_CODE_DEBUGGING | 0x40 | When set, this notifies the Microsoft VM that Just-In-Time (JIT) code debugging is disabled.

Debugging can also be enabled and debug options can be configured through the use of registry settings on Windows 95 and Windows NT. The registry settings that affect the Microsoft VM when used with these debug interfaces are located under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM

Note the presence of a space between Java and VM in this registry node.

Under this node, the following entries and values must be entered or modified.

Debug

When this key exists before the Microsoft VM begins execution, debugging will be enabled.

DebuggingFlags

Set the value of this entry to a DWORD that indicates the value of the debug options.

By default, when the Microsoft VM is installed, neither of these registry entries are created.

HKEY_LOCAL_MACHINE\CurrentUser\Software\Microsoft\Java VM

Note the presence of a space between Java and VM in this registry node.

Under this node, the following entry and value must be entered or modified.

EnableJitCompiledCodeDebugging

Set the value of this entry to a DWORD that indicates whether Just-In-Time (JIT) code debugging is enabled. A non-zero value enables JIT code debugging, while a value of zero disables this feature. The default value for this option is enabled.

By default, when the Microsoft VM is installed, this registry entry is not created. Registry settings can be set using code similar to the following:

const char s_cszDebugKey[] = "Software\\Microsoft\\Java VM\\Debug";

// Create the Microsoft VM Debug key; return TRUE on success.
static BOOL CreateDebugKey(void)
{
    BOOL bResult;
    DWORD dwDisposition;
    HKEY hkeyDebug;

    bResult = ( RegCreateKeyEx(HKEY_LOCAL_MACHINE, s_cszDebugKey, 0,
                NULL, 0, KEY_WRITE, NULL, &hkeyDebug, &dwDisposition)
                == ERROR_SUCCESS);

    if (bResult) RegCloseKey(hkeyDebug);

    return(bResult);
}

Exercise caution when using these registry settings for enabling use of the Java debug interfaces because these settings will affect all Java applications and applets started under the Microsoft VM. Enabling debugging disables certain optimizations in the Microsoft VM and requires more resources to be used. This option may disable the JIT compiler and invoke a slower than usual version of the Java bytecode interpreter, which will slow down the execution of all Java applications and applets. If the Debug registry entry is not explicitly removed when debugging is no longer needed, the execution performance of all Java applications and applets will be adversely affected. Registry settings can be removed using code similar to the following.

// Delete the Microsoft VM Debug key; return TRUE is successful.
static BOOL DeleteDebugKey(void)
{
    return ( RegDeleteKey(HKEY_LOCAL_MACHINE, s_cszDebugKey) ==
           ERROR_SUCCESS);
}

Registry entries can also be removed or modified using the regedit.exe utility that is included with Windows 95 and Windows NT.

Registering with the Java Debug Manager

To use the Java debug interfaces, a debugger program must call specific methods of the registration interfaces implemented by the Microsoft VM. Its registration interfaces are implemented as follows.

Registration Interfaces | Description
IRemoteDebugManager | This object manages all the processes that can be debugged and connects a debugger program to them when requested. This COM object must be initialized first before any other registration interfaces are used. The debugger program must then call the RegisterCallback method on this object's interface to provide a callback through which the Microsoft VM communicates with the debugger.
IEnumRemoteProcess | This object allows a debugger to enumerate all Java processes currently running in the Microsoft VM.
IJavaEnumRemoteProcess | This object extends the IEnumRemoteProcess interface (adds one new method) and allows a debugger to enumerate all Java processes currently running in the Microsoft VM.
IRemoteProcess | The interface pointer to this object represents a single Java process running within the Microsoft VM. Note that this object does not represent the Win32 operating system process that the Microsoft VM is being run in.

To register with the Microsoft VM, an application must first call the COM library function CoCreateInstance or CoCreateInstanceEx, passing in the class identifier (CLSID) of the debug manager, CLDID_RemoteJavaDebugManager, and interface identifier (IID) of the IRemoteDebugManager interface. CoCreateInstanceEx takes an additional parameter that specifies the host for use with DCOM. The COM library then uses the CLSID to find the entry for this object’s class in the system registry and starts the appropriate COM server.

The CLSID for the IRemoteDebugManager is defined in the JDbgGUID.h file. The IID for the IRemoteDebugManager object and the other Java debug interfaces are defined in the JavaDbg.h file that is installed in the Include directory of the SDK for Java. The JavaDbg.h include file also contains function prototypes for the methods supported by these interfaces.

The following sample code illustrates how these functions might be used to start a local server.

#include <JavaDbg.h>
#include <JDbgGUID.h

    HRESULT hr;
    hr = CoInitialize(NULL);   // Initialize OLE on this thread.

    if (SUCCEEDED(hr)) {
        IRemoteDebugManager *pirdm;

        // Create a RemoteJavaDebugManager to initiate debugging.

        hr = CoCreateInstance(CLSID_RemoteJavaDebugManager, NULL,
                              CLSCTX_LOCAL_SERVER,
                              IID_IRemoteDebugManager,
                              (PVOID *)&pirdm);

        if (hr == S_OK) {
            // Continue working if okay.
        }
        // Uninitialize OLE on this thread when done.
        CoUninitialize();

The debugger program must then register with the Debug Manager in the Microsoft VM, passing its own callback interface pointer through which this virtual machine will communicate with the debugger. The callback functions provided by the debugger must be implemented as methods on COM objects that represent the Notification interfaces, which will be addressed later in this topic.

The IRemoteDebugManager interface implements the following methods that may be called by a debugger.

Method | Description
RegisterCallback | The debugger program calls this method to provide a callback for receiving notification when new Java processes are created. The debugger must pass an interface to its own COM object that implements IRemoteDebugManagerCallback. The Microsoft VM communicates with the debugger by calling various methods on this callback interface.
Detach | The debugger program calls this method to detach its callback (IRemoteDebugManagerCallback) that was attached by some previous call to RegisterCallback. Call this method before the debugger exits.
GetActiveProcesses | This method is used to return an interface to an enumerator object (IJavaEnumRemoteProcess) for all the Java processes currently running in the Microsoft VM.
RequestCreateEvent | This method notifies the Debug Manager in the Microsoft VM that a debugger program will be debugging a specific Java class. The debugger can specify a Java class name (for an applet or an application) or request interest in debugging all Java classes. The debugger can also specify interest in Java classes run in a specific host Win32 process or any Win32 process.

Once an interface pointer to IRemoteDebugManager object has been obtained, the debugger program must call the RegisterCallback method on this interface. The following code illustrates registering a callback in a sample Initialize method of a Java debugger class.

// Initialize is passed. The interface pointer to
//    IRemoteDebugManager is called.
HRESULT JavaDebugger::Initialize(IRemoteDebugManager *pirdm)
{
    HRESULT hr;

    // Register this JavaDebugger's IRemoteDebugManagerCallback with the
    // debug manager so it can be notified when new processes are run.

    hr = pirdm->RegisterCallback(this);

    if (hr == S_OK) {
        m_pirdm = pirdm;
        m_pirdm->AddRef();    // Increment the reference count.
    }
    return(hr);
}

Once a debugger has registered its callback interface, it can request that it be notified when new Java processes are started. The debugger calls the RequestCreateEvent method of the IRemoteDebugManager interface to request being informed when the Microsoft VM creates new Java processes. The RequestCreateEvent method takes two parameters that allow the debugger to register to receive notifications of all new processes created, or in a specific process (a particular Java class) when it is created within a particular Win32 process. There are four possible combinations of these two parameters. The debugger can pass –1 for the process ID registering to receive notifications for any Win32 process. Any other value for the dwProcessID parameter indicates a specific Win32 process. The debugger can pass a zero-length string for the process name (Java class name) registering to receive notification of any Java process that is started. Any other value for the pcszProcessName parameter indicates a specific Java class name.

The sample code below illustrates registering an interest to receive all process create events.

// Ask the debug manager to notify us when any Java class is run.
HRESULT hr;
DWORD dwProcessID = -1;             // For any Win32 process ID,
                                    // use –1.
LPCOLESTR pcszProcessName = ""; // Zero-length string for all processes.

hr = m_pirdm->RequestCreateEvent(&pcszProcessName, dwProcessID);

At this point, a Java applet or application that is to be debugged can be started. If the Java application or applet was previously started using the Win32 CreateProcess function was in a suspended state, it can now be resumed. When any new Java processes are started, the debugger is notified through its IRemoteDebugManagerCallback interface.

Enumerating Active Java Processes

Using the RequestCreateEvent method of the IRemoteDebugManager object, a debugger can request to be informed of new Java processes that are created. A debugger program can also keep track of active processes by the calling GetActiveProcesses method on this object to retrieve a pointer to an enumerator object (IJavaEnumRemoteProcess) for all active Java processes. Two other registration interfaces, IJavaEnumRemoteProcess and IEnumRemoteProcess, can be used to enumerate all Java processes currently running in the Microsoft VM.

These interfaces implement the following methods that may be called by a debugger.

Method | Description
Next | Used to retrieve IRemoteProcess objects that represent active Java processes into an array. The number of Java processes to be retrieved is passed as one of the parameters; the enumeration pointer is incremented by that amount.
Skip | Moves the position of the enumeration forward. The number of objects to be skipped is based on a parameter passed to the method.
Reset | Sets or resets the positions the enumerator to the beginning of the list of Java processes.
Clone | Copies a pointer to the current position in the list to another enumerator object.
GetNext | Retrieves the next IRemoteProcess object being pointed to by the enumerator object and increments the enumeration pointer by one. Note that this method is only implemented by the IJavaEnumRemoteProcess object.

Registering with a Remote Process

Once a debugger has obtained a list of active Java processes—either through enumeration or from receiving ProcessCreateEvent method calls—it can attach to and debug a specific Java process.

To debug a specific process, a debugger program must first register a callback to receive notifications and information from the Microsoft VM regarding that process. The IRemoteProcess object, another registration interface, is used for this task.

The IRemoteProcess interface implements the following methods that can be called by a debugger.

Methods | Description
RegisterCallback | The debugger program calls this method to provide a callback that should receive notification and information regarding this active Java process. The debugger must pass an interface to its own COM object that implements IRemoteProcessCallback. This is the primary interface that the Microsoft VM communicates with the debugger. The VM sends information to the debugger regarding this process by calling various methods on this callback interface.
Detach | The debugger program calls this method to detach its callback (IRemoteProcessCallback) that was attached by some previous call to RegisterCallback.
Break | This method issues a break on all threads in this Java process, resulting in all threads being stopped. This method is asynchronous, so threads won't necessarily stop immediately.
GetGlobalContainerObject | This method returns a pointer to an IRemoteContainerObject, representing the root of all objects in this Java process. This method is used by a debugger to collect static information on all class objects in a Java process.
FindClass | This method finds a specific Java class. If the class isn't already loaded in the Java process, it’s loaded by the Microsoft VM.
TraceMethods | This method enables or disables TraceEvent callbacks used for notification of method calls. It is being deprecated. Developers should use the newer Java Profiler interfaces.
GetThreadGroups | This method returns an enumerator object (IJavaEnumRemoteThreadGroup) for all the thread groups in the Java process. The method is used by a debugger to collect dynamic information on all threads and class objects in a Java process.

Implementing Callback Notification Interfaces

For the Microsoft VM to communicate with a debugger, it registers with the Java Debug Manager and passes in pointers to COM objects that implement its notification interfaces. The Java debugger must implement two COM objects for this callback mechanism. The first provides global notification of new process creation. The second interface is used for debugging a specific Java process.

The notification interfaces that must be implemented by the debugger are as follows.

Notification Interfaces | Description
IRemoteDebugManagerCallback | This object is the initial callback through which the Microsoft VM communicates with the debugger. This callback must be registered by the debugger with the Java Debug Manager. This object has a single method that receives notification from the VM when new Java processes are created.
IRemoteProcessCallback | This object is the primary callback through which the VM communicates with the debugger and passes notifications and information requested concerning a specific Java process.
IRemoteDebugManagerCallbackEx | This COM object is not required to be implemented. This object inherits from and is a replacement for the IRemoteDebugManagerCallback object. This interface and is only necessary if the debugger wants to support JIT debugging.
IRemoteProcessCallbackEx | This COM object is not required to be implemented. This object is a replacement for the IRemoteProcessCallback object and is only necessary if the debugger wants to receive notification of the class for which the Microsoft VM was started.

A debugger will normally implement either the IRemoteDebugManager interface or the IRemoteDebugManagerEx interface, which extends the former interface by adding one new method. Under normal circumstances, JIT debugging is disabled when a Java process is being debugged. The IRemoteDebugManagerEx interface is only used when the debugger wants to receive notification of the classes for which the Microsoft VM started to support JIT debugging.

When the debugger program starts execution, it must register with the Java Debug Manager in the VM passing its own callback interface pointer to IRemoteDebugManagerCallback (or IRemoteDebugManagerCallbackEx).

The IRemoteDebugManagerCallback and IRemoteDebugManagerCallbackEx interfaces implement the following methods that may be called by the Microsoft VM.

Method | Description
ProcessCreateEvent | Notifies the debugger that a new Java process has been created and passes back a pointer to the IRemoteProcess object for this new Java class.
StartClassEvent | Only implemented by the IRemoteDebugManagerEx object and notifies the debugger regarding the Java class it has started. This method is only used for JIT debugging.

When a Java process starts in the Microsoft VM, the debugger will be notified through its ProcessCreateEvent method that a new Java process has been created. If the debugger decides to, it can register to receive notifications regarding this specific Java process. The IRemoteProcessCallback (or the IRemoteProcessCallbackEx) object is the primary way the Microsoft VM communicates with the debugger about a specific Java process. This callback has a large number of methods that must be implemented by the debugger.

A debugger will normally implement either the IRemoteProcessCallback or the IRemoteProcessCallbackEx interface (which extends the former interface by adding one new method). The Microsoft VM senses which interface the debugger supports by calling QueryInterface on the callback object passed to IRemoteProcess::RegisterCallback.

The IRemoteProcessCallback and the IRemoteProcessCallbackEx interfaces implement the following methods that may be called by the Microsoft VM.

Method | Description
DebugStringEvent | Notifies the debugger when the Java process being debugged outputs a string.
CodeBreakPointEvent | Notifies the debugger when a code breakpoint is hit by the Java process being debugged.
DataBreakPointEvent | Notifies the debugger when a data breakpoint is hit by the Java process being debugged.
ExceptionEvent | Notifies the debugger when an exception occurs in the Java process being debugged.
StepEvent | Notifies the debugger when an execution step completes in the Java process being debugged.
CanStopEvent | Notifies the debugger during a range step when the Java process being debugged makes a function call.
BreakEvent | Notifies the debugger when an asynchronous break occurs in response to the debugger calling IRemoteProcess:Break.
ThreadCreateEvent | Notifies the debugger when a thread is created.
ThreadDestroyEvent | Notifies the debugger when a thread is destroyed.
ThreadGroupCreateEvent | Notifies the debugger when a thread group is created.
ThreadGroupDestroyEvent | Notifies the debugger when a thread group is destroyed.
ClassLoadEvent | Notifies the debugger when a Java class is loaded and indicates the thread on which the class was loaded.
LoadCompleteEvent | Notifies the debugger when all Java class have been loaded.
ClassUnloadEvent | Notifies the debugger when a Java class is unloaded.
TraceEvent | Notifies the debugger while tracing is enabled when a method is entered in a Java class. This method is being deprecated. Developers should use the newer Java Profiler interfaces.
ProcessDestroyEvent | Notifies the debugger when a Java process terminates. No further notifications are sent to the debugger regarding this Java process after this method is called.
StartClassEvent | Only implemented by the IRemoteDebugManagerEx object; notifies the debugger regarding the Java class it has started. This method is only used for JIT debugging.

After a debugger registers an interest in a particular Java process (IRemoteProcess), it will begin to receive a large number of calls to its LoadClassEvent method for each class that was loaded before the debugger was attached. The debugger might receive a flurry of over 100 calls for a typical Java process. These notifications to the debugger are initially made asynchronously by the Microsoft VM. After notifications are made for all the currently loaded classes, a LoadCompleteEvent is received. After this notification, any other ClassLoadEvent notifications are sent synchronously for the thread that caused the class to be loaded.

If the debugger returns S_OK from a ClassLoadEvent method, this Java process is suspended and class loading by the Microsoft VM becomes synchronous. The execution of the Java process can be resumed once the debugger calls IRemoteThread::Go. If the debugger returns S_FALSE from each ClassLoadEvent call, the process of loading Java classes continues.

All these callback methods implemented by the debugger use the same return values. If the debugger returns S_FALSE, execution of the Java process continues. If the debugger returns S_OK, the Java process is suspended. This process can be resumed once the debugger calls IRemoteThread::Go.

The IRemoteProcess:FindClass method can be used to force a class to be loaded into the Microsoft VM if it is not already loaded. This method has side effects and the debugger will receive ClassLoadEvent method calls. The initializer for the Java class may also run and the debugger will not receive events during execution of the initializer. For example, if an exception occurs in the initializer, the debugger won't receive an exception event.

Thread groups are used to group threads together. Thread groups have special meaning for security purposes. Each Java applet is given its own thread group, and the applet can only manipulate threads within that group. These thread groups may be used to differentiate threads between multiple applets.

The debugger will receive notifications for a large number of events. The debugger is notified when thread groups and individual threads are created and destroyed. Threads are used extensively to get dynamic information when debugging a Java applet or application.

The debugger will also receive notifications on breakpoint and step events. The debugger sets breakpoints and controls execution by calling methods on the execution control interfaces. The objects to control execution control are also based using threads. In this case, threads are used to retrieve stack frames, calling frames and program counters.

Retrieving Static Information

Static information on a Java process is available through the IRemoteField hierarchy of interfaces. These interfaces represent fields that are members of classes. These fields can be methods, objects, inner classes, or nested class definitions. Because all the attributes of a field are constant during the lifetime of the field, this information can be cached by the debugger.

Global classes (classes not defined within other classes) can be thought of as fields of a global class. Access to static information in a Java process is based on using the IRemoteClassField and thread passed on each ClassLoadEvent notification to the debugger. The IRemoteProcess:GetGlobalContainerObject method (one of the interfaces used for retrieving dynamic information) can also be used to access the root of this object hierarchy and descend down it to retrieve IRemoteClassField objects.

The static information interfaces consist primarily of the IRemoteField interface and a collection of other interfaces designed for a specific Java object (primitive data types, arrays, classes, methods, and so on) that inherit from IRemoteField or from other interfaces that extend IRemoteField. The static information interfaces implemented by the Microsoft VM are as follows.

Static Information Interfaces | Inherits From | Description
IRemoteField | IUnknown | This object represents a field in a Java process.
IRemoteDataField | IRemoteField | This object represents a field that is not a method or a class definition. This interface inherits from IRemoteField. This interface is not used except as a base interface for IRemoteArrayField.
IRemoteArrayField | IRemoteDataField | This object represents arrays (special data fields). The only major difference between data and arrays (IRemoteDataField and IRemoteArrayField) is that arrays have a size. This interface inherits from IRemoteDataField.
IRemoteContainerField | IRemoteField | The object represents fields that contain other fields. This interface inherits from IRemoteField.
IRemoteClassField | IRemoteContainerField | This object represents a class definition. This interface inherits from IRemoteContainerField.
IRemoteMethodField | IRemoteContainerField | This object represents a method within a class. This interface inherits from IRemoteContainerField.
IEnumRemoteField | IUnknown | This object allows a debugger to enumerate fields in a Java process running in the Microsoft VM.
IJavaEnumRemoteField | IEnumRemoteField | This object extends the IEnumRemoteField interface (adds one new method) and allows a debugger to enumerate fields in a Java process running in the Microsoft VM.
IEnumLINEINFO | IUnknown | This object enumerates line number information for a method.

Fields are classified and defined by the FIELDKIND enum as follows:

FIELDKIND enum | Value | Description
FIELD_KIND_DATA_OBJECT | 0x0001 | A class instance.
FIELD_KIND_DATA_PRIMITIVE | 0x0002 | A primitive Java data type.
FIELD_KIND_ARRAY | 0x0004 | An array.
FIELD_KIND_CLASS | 0x0008 | A Java class.
FIELD_KIND_METHOD | 0x0010 | A Java class method.
FIELD_KIND_LOCAL | 0x1000 | A local variable in a Java method.
FIELD_KIND_PARAM | 0x2000 | A parameter passed to a Java method.
FIELD_KIND_THIS | 0x4000 | A THIS pointer to an object.
FIELD_KIND_INNER_CLASS | 0x8000 | An Java inner class.

If a field is not FIELD_KIND_LOCAL, FIELD_KIND_PARAM, or FIELD_KIND_THIS, it may be a class field or an array element. This may be determined by getting the kind of the field’s container. For an array element, the container field is FIELD_KIND_ARRAY. For a class field, the container field is FIELD_KIND_CLASS.

The following Java code sample illustrates the FIELDKINDs for a sample Java class.

class <globals>                           // FIELD_KIND_CLASS
{
    class FooClass                        // FIELD_KIND_CLASS
   {
       boolean bDone;                     // FIELD_KIND_DATA_PRIMITIVE
       class BarClass                     // FIELD_KIND_CLASS
      {
           String username[20];           // FIELD_KIND_ARRAY
      }
      BarClass mybar;                     // FIELD_KIND_DATA_OBJECT
      int BarMethod();                    // FIELD_KIND_METHOD
    };
};

Fields also have a set of modifiers contained in a flag attribute bitmask. These modifier bits are the same as those used in the access_flags field of the class file header. These bitmasks are defined in Java Virtual Machine specification published by JavaSoft.

These modifier bits are defined by the FIELD_ACC enum as follows:

FIELDKIND enum | Value | Description
FIELD_ACC_PUBLIC | 0x0001 | Is public and may be accessed from outside its package (visible to everyone).
FIELD_ACC_PRIVATE | 0x0002 | Visible only to the defining class.
FIELD_ACC_PROTECTED | 0x0004 | Visible to this class and subclasses.
FIELD_ACC_STATIC | 0x0008 | A static field or method.
FIELD_ACC_FINAL | 0x0010 | Is final and no further subclassing or assignment is allowed.
FIELD_ACC_SYNCHRONIZED | 0x0020 | Use monitor lock when the method is invoked.
FIELD_ACC_VOLATILE | 0x0040 | The value of this field cannot be cached.
FIELD_ACC_TRANSIENT | 0x0080 | This field cannot be read or written by a persistent object manager.
FIELD_ACC_NATIVE | 0x0100 | This method is implemented using native code.
FIELD_ACC_INTERFACE | 0x0200 | Is an interface (used to distinguish between an interface and a class).
FIELD_ACC_ABSTRACT | 0x0400 | An abstract class or interface that may not be instantiated.
FIELD_ACC_SUPER | 0x0800 | Treat superclass methods specially in invokespecial (used for backward compatibility).
FIELD_ACC_SYNTHETIC | 0x1000 | Set on fields that the compiler had to generate (used by inner classes).

The IRemoteField interface and the other IRemoteXXXField interfaces that inherit from IRemoteField implement a standard set of methods used to get the name, kind, type, and modifiers of a field as well as the field representing the class that contains the field. The GetContainer method provides a way for a debugger to maneuver up the field hierarchy in a class.

The following methods of IRemoteField (and the objects that inherit from it) can be called by a debugger.

Methods | Description
GetName | Returns the identifier (the class, variable, or method name) for this field.
GetKind | Returns the kind (FIELD_KIND enum) of this field.
GetType | Returns the type of this field. The relationship between a field and its type depends on the FIELD_KIND of the field. The type will be either a class type or a Java native object type (boolean, short, integer, long, and so on).
GetContainer | Returns the field representing the class that contains the field.
GetModifiers | Returns a bitmask of flags containing the modifiers (FIELD_ACC enum) for this field. If a bit is set, the type is modified in that way.

The following methods are specific to the interfaces that inherit from IRemoteField and can be called by a debugger.

Methods | Description
GetSize | Returns the number of elements in an array. This method is implemented only by the IRemoteArrayField interface.
GetFields | Returns an enumerator (IJavaEnumRemoteField) for the fields that are contained by this field and match given characteristics. The characteristics are determined by three parameters passed to the method that specify the name of the field, the modifiers bitmask, and the kind. A null parameter passed for the name is used to include all names. A bitmask of 0 is used to include all modifiers. A FIELD_KIND of 0 is used to include all kinds. This method is implemented only by the IRemoteContainerField, IRemoteClassField, and the IRemoteMethodField interfaces.
GetFileName | Returns the full name of the class if it is available (c:\classes\HelloWorld.class, for example). This method is implemented only by the IRemoteClassField interface.
GetSourceFileName | Returns the name of the source file attribute from the class file if it is available (HelloWorld.java, for example). This method is implemented only by the IRemoteClassField interface.
GetSuperclass | Returns the class (an IRemoteClassField) from which this class is derived. For Java.Lang.Object, the top of the hierarchy, this method returns NULL. This method is implemented only by the IRemoteClassField interface.
GetInterfaces | Returns an enumerator (IJavaEnumRemoteField) for the interfaces that this class implements. If the class has no interfaces, an enumerator is returned that enumerates nothing. This method is implemented only by the IRemoteClassField interface.
GetConstantPoolItem | Returns the raw contents for the constant pool and is used for disassembly. This method is implemented only by the IRemoteClassField interface. Any indices contained within the CP item are converted from big endian to platform byte order.
GetIndexedField | Empty

The IRemoteMethodField, which inherits from the IRemoteContainerField, represents a method within a class. This interface implements a number of methods that can be used by a debugger to set and clear breakpoints, get line number info, return Java bytecodes, and other information.

The following methods are specific to the IRemoteMethodField and can be called by a debugger.

Methods | Description
SetBreakpoint | Sets a code breakpoint at a given byte offset from the start of a method. The VM will not validate the given location of the breakpoint; a breakpoint may be set at any offset within the method’s bytecodes. Breakpoints are reference counted and may be set multiple times at the same byte offset.
ClearBreakpoint | Clears a code breakpoint at a given byte offset from the start of a method. This method will only clear breakpoints set by SetBreakpoint. If a breakpoint is set multiple times, it must be cleared the same number of times to eliminate it completely.
GetLineInfo | Returns an enumerator of LINEINFO structures (IJavaEnumLINEINFO objects) describing the mapping between source lines and byte offset within the Java bytecodes representing the method. This mapping is in order of increasing offsets. The last element in the list is a “dummy” node with a line number field set to the last line of the method + 1 and the offset field set to the last offset in the method +1.
GetBytes | Returns an interface (ILockBytes) that can be used to access the Java bytecode of the method. This method can be used by a debugger to display a disassembly of the bytecode.
GetScope | Returns the range of byte offsets (within which the object is in scope) that can be used by a debugger to obtain the value of some field within this method.
GetIndexedField | Obtains a local variable or parameters field from a method by local variable index and byte offset.

Enumerating Static Fields

Several of the interfaces that inherit from the IRemoteField object (IRemoteContainerField, IRemoteClassField, and IRemoteMethodField) implement a GetFields method that returns an enumerator for the fields contained by this field. Two other static information interfaces, IJavaEnumRemoteField and IEnumRemoteField, can be used to enumerate all these fields contained within a class, method, or container. The IJavaEnumRemoteField object inherits from IEnumRemoteField, extending this interface with one additional method.

These interfaces implement the following methods that may be called by a debugger.

Method | Description
Next | Used to retrieve IRemoteField objects that represent fields. The number of fields to be retrieved is passed as one of the parameters; the enumeration pointer is incremented by that amount.
Skip | Moves the position of the enumeration forward. The number of objects to be skipped is based on a parameter passed to the method.
Reset | Sets or resets the positions the enumerator to the beginning of the list of fields.
Clone | Copies a pointer to the current position in the list to another enumerator object.
GetCount | Returns the number of fields being pointed to by the enumerator object.
GetNext | Retrieves the next IRemoteField object being pointed to by the enumerator object and increments the enumeration pointer by one. Note that this method is only implemented by the IJavaEnumRemoteField object.

Enumerating Line Number Information

Line number information represents the mapping between Java source code line numbers and byte offsets in the method. This information is represented as an array of LINEINFO structures maintained for each method. The IEnumLINEINFO interface provides access to this information.

The IEnumLINEINFO interface implements the following methods that may be called by a debugger.

Method | Description
Next | Used to retrieve LINEINFO structures that represent the mapping between Java source code line numbers and byte offset in the method. The number of LINEINFO structures to be retrieved is passed as one of the parameters; the enumeration pointer is incremented by that amount.
Skip | Moves the position of the enumeration forward. The number of LINEINFO structures to be skipped is based on a parameter passed to the method.
Reset | Sets or resets the positions the enumerator to the beginning of the list of LINEINFO structures.
Clone | Copies a pointer to the current position in the list to another enumerator object.
GetNext | Retrieves the next LINEINFO structure being pointed to by the enumerator object and increments the enumeration pointer by one. Note that this method is only implemented by the IJavaEnumLINEINFO object.
GetCount | Returns the number of fields being pointed to by the enumerator object. Note that this method is only implemented by the IJavaEnumLINEINFO object.

Retrieving Dynamic Information

Dynamic information on a Java process is available through the IRemoteObject hierarchy of interfaces. These interfaces provide bound access to objects of different types. An object does not necessarily refer to an instance of a class, but represents an instance of any type. The information obtained from an IRemoteObject is only valid during the lifetime of the actual object that it represents. Consequently, dynamic information cannot be cached by the debugger.

Access to dynamic information in a Java process is based on using the IRemoteThreadGroup and IRemoteThread passed on each ThreadGroupCreateEvent and ThreadCreateEvent notification to the debugger. The IRemoteProcess:GetGlobalContainerObject method can also be used to access the root of this object hierarchy and descend down it to retrieve IRemoteClassField objects.

The dynamic information interfaces consist primarily of the IRemoteObject, IEnumRemoteObject, and the IEnumRemoteValue interfaces and a collection of other interfaces designed for a specific Java object (primitive data types, arrays, or classes) that inherit from IRemoteObject or IEnumRemoteValue. The dynamic information interfaces implemented by the Microsoft VM are as follows.

Dynamic Information Interfaces | Inherits From | Description
IRemoteObject | IUnknown | Represents bound access to objects of different types in a Java process.
IRemoteBooleanObject | IRemoteObject | Provides run-time access to the value of a boolean variable.
IRemoteByteObject | IRemoteObject | Provides run-time access to the value of a byte variable.
IRemoteCharObject | IRemoteObject | Provides run-time access to the value of a char variable.
IRemoteContainerObject | IRemoteObject | Provides run-time access to container objects.
IRemoteClassObject | IRemoteContainerObject | Provides run-time access to class objects.
IRemoteDoubleObject | IRemoteObject | Provides run-time access to the value of a double variable.
IRemoteFloatObject | IRemoteObject | Provides run-time access to the value of a float variable.
IRemoteIntObject | IRemoteObject | Provides run-time access to the value of an int variable.
IRemoteLongObject | IRemoteObject | Provides run-time access to the value of a long variable.
IRemoteShortObject | IRemoteObject | Provides run-time access to the value of a short variable.
IRemoteArrayObject | IRemoteObject | Provides run-time access to array objects.
IEnumRemoteObject | IUnknown | Allows a debugger to enumerate objects in a Java process running in the Microsoft VM.
IEnumRemoteValue | IUnknown | Allows a debugger to enumerate the value of a variable in a Java process running in the Microsoft VM.
IEnumRemoteBooleanValue | IEnumRemoteValue | Enumerates boolean values.
IEnumRemoteByteValue | IEnumRemoteValue | Enumerates byte values.
IEnumRemoteCharValue | IEnumRemoteValue | Enumerates char values.
IEnumRemoteDoubleValue | IEnumRemoteValue | Enumerates double values.
IEnumRemoteFloatValue | IEnumRemoteValue | Enumerates float values.
IEnumRemoteIntValue | IEnumRemoteValue | Enumerates int values.
IEnumRemoteLongValue | IEnumRemoteValue | Enumerates long values.
IEnumRemoteShortValue | IEnumRemoteValue | Enumerates short values.
IJavaEnumRemoteValue | IEnumRemoteValue | Allows a debugger to enumerate the value of a variable in a Java process running in the Microsoft VM.
IJavaEnumRemoteBooleanValue | IJavaEnumRemoteValue | Enumerates boolean values.
IJavaEnumRemoteByteValue | IJavaEnumRemoteValue | Enumerates byte values.
IJavaEnumRemoteCharValue | IJavaEnumRemoteValue | Enumerates char values.
IJavaEnumRemoteDoubleValue | IJavaEnumRemoteValue | Enumerates double values.
IJavaEnumRemoteFloatValue | IJavaEnumRemoteValue | Enumerates float values.
IJavaEnumRemoteIntValue | IJavaEnumRemoteValue | Enumerates int values.
IJavaEnumRemoteLongValue | IJavaEnumRemoteValue | Enumerates long values.
IJavaEnumRemoteShortValue | IJavaEnumRemoteValue | Enumerates short values.

The IRemoteObject interface and the other IRemoteXXXObject interfaces that inherit from IRemoteObject implement a standard set of methods used to get the type of an object, and set or clear data breakpoints on the object. The breakpoint will fire when the value of the object changes. For classes, a data breakpoint will fire when the object references a different instance of that class. For arrays, a data breakpoint will fire when the object references a different instance of the array (when one array is assigned or copied to another). The GetFieldObject method of the IRemoteContainerObject interface provides a way for a debugger to access fields in a container (class).

The following methods of IRemoteObject (and the objects that inherit from it) can be called by a debugger.

Methods | Description
GetType | Returns the type of the object (an IRemoteField object). A debugger would normally then call the GetKind method of the IRemoteField interface to determine the FIELD_KIND of the object. The type will be either a class type or a Java native object type (boolean, short, integer, long, and so on.).
SetBreakpoint | Sets a data breakpoint on the object. The breakpoint fires when the value of the object changes.
ClearBreakpoint | Clears a data breakpoint on the object previously set with the SetBreakpoint method.
GetValue | Gets the value of a primitive Java type. This method is implemented by the IRemotexxxObject interfaces that inherit from IRemoteObject, where xxx represents one of the primitive Java data types.
SetValue | Sets the value of a primitive Java type. This method is implemented by the IRemotexxxObject interfaces that inherit from IRemoteObject, where xxx represents one of the primitive Java data types.

Enumerating Dynamic Information

Several of the interfaces that inherit from the IRemoteObject object (IRemoteContainerObject and IRemoteClassObject) implement a GetFieldObject method that returns an object representing a specific field.

Several other dynamic information interfaces, IEnumRemoteObject, IEnumRemoteValue, and IJavaENumRemoteValue, can be used to enumerate objects and enumerate values. The IJavaEnumRemoteValue object inherits from IEnumRemoteValue, extending this interface with one additional method.

These interfaces implement the following methods that may be called by a debugger.

Method | Description
Next | Used to retrieve objects (IRemoteObject). The number of objects to be retrieved is passed as one of the parameters; the enumeration pointer is incremented by that amount.
Skip | Moves the position of the enumeration forward. The number of objects to be skipped is based on a parameter passed to the method.
Reset | Sets or resets the positions the enumerator to the beginning of the list of fields.
Clone | Copies a pointer to the current position in the list to another enumerator object.
GetCount | Returns the number of objects being pointed to by the enumerator object.
GetNext | Retrieves the next LINEINFO structure being pointed to by the enumerator object and increments the enumeration pointer by one. Note that this method is only implemented by the IJavaEnumRemoteValue object and the interfaces that inherit from it.


Static Information Interfaces

Working with MS VM
In this topic

* IRemoteField : IUnknown

* IRemoteDataField : IRemoteField

* IRemoteArrayField : IRemoteDataField

* IRemoteContainerField : IRemoteField

* IRemoteClassField : IRemoteContainerField

* IRemoteMethodField : IRemoteContainerField

* IEnumRemoteField : IUnknown

* IEnumLINEINFO : IUnknown

Microsoft VM | Previous | VM | Next
Java Debugger Interfaces | Previous | VM | Next

Static Information Interfaces

Use these interfaces to retrieve information about classes, methods, and fields.

IRemoteField : IUnknown

The IRemoteField hierarchy of interfaces represents fields that are members of classes. These fields can be methods, objects, or nested class definitions. You can think of global classes (classes not defined within other classes) as being fields of a global class. For example:

class <globals>					// FIELD_KIND_CLASS
{
    class FooClass				// FIELD_KIND_CLASS
    {
        boolean m_i;			// FIELD_KIND_DATA

        class BarClass			// FIELD_KIND_CLASS
        {
            String m_rgstr[5];	// FIELD_KIND_ARRAY
        };

        BarClass m_bar;			// FIELD_KIND_DATA

        int Method();			// FIELD_KIND_METHOD
    };
};

Since all the attributes of a field are constant during that field's lifetime, the debugger can cache this information.

GetName

HRESULT GetName(LPOLESTR *ppszName)

Parameter | Description
[out] ppszName | Returns the identifier for this field; for example, "FooClass", "m_i", "m_bar", "Method", and so on.

GetKind

HRESULT GetKind(FIELDKIND *pKind)

Parameter Description
[out] pKind Returns the kind of this field.
typedef enum fieldkind {
    FIELD_KIND_DATA_OBJECT		= 0x0001,
    FIELD_KIND_DATA_PRIMITIVE	= 0x0002,
    FIELD_KIND_ARRAY			= 0x0004,
    FIELD_KIND_CLASS			= 0x0008,
    FIELD_KIND_METHOD			= 0x0010,
    FIELD_KIND_LOCAL			= 0x1000,
    FIELD_KIND_PARAM			= 0x2000,
    FIELD_KIND_THIS			= 0x4000,
} FIELDKIND;

GetType

HRESULT GetType(IRemoteField **ppType)

Parameter | Description
[out] ppType | Returns the type of this field.

Remarks:

The relationship between a field and its type depends on the "kind" of the field. This relationship is defined in the interfaces derived from IRemoteField.

GetContainer

HRESULT GetContainer(IRemoteContainerField **ppContainer)

Parameter | Description
[out] ppContainer | Returns the field representing the class that contains the field. For example, calling this method on the field that represents "m_rgstr" in the preceding example will return the field for its containing class "BarClass".

GetModifiers

HRESULT GetModifiers(ULONG *pulModifiers)

Parameter | Description
[out] pulModifiers | Returns a bitmask of flags containing the modifiers for this type.

Remarks:

If a bit is set then the type is modified in that way. The modifier bits are the same as those used in the access_flags field of the .class file header.

typedef enum fieldmodifiers
{
    FIELD_ACC_PUBLIC		= 0x0001,
    FIELD_ACC_PRIVATE		= 0x0002,
    FIELD_ACC_PROTECTED	= 0x0004,
    FIELD_ACC_STATIC		= 0x0008,
    FIELD_ACC_FINAL		= 0x0010,
    FIELD_ACC_SYNCHRONIZED	= 0x0020,
    FIELD_ACC_VOLATILE	= 0x0040,
    FIELD_ACC_TRANSIENT	= 0x0080,
    FIELD_ACC_NATIVE		= 0x0100,
    FIELD_ACC_INTERFACE	= 0x0200,
    FIELD_ACC_ABSTRACT	= 0x0400,
}
FIELDMODIFIERS;

IRemoteDataField : IRemoteField

Represents a field that is not a method (FIELD_KIND_METHOD), or a class definition (FIELD_KIND_CLASS).

GetKind

HRESULT GetKind(UINT *piKind)

Parameter | Description
[out] piKind | Returns FIELD_KIND_DATA.

GetType

HRESULT GetType(IRemoteField **ppType)

Parameter | Description
[out] ppType | Returns the type of the data field.

Remarks:

The type will always be a class (built-in types also have IRemoteClassField objects that represent them). For the previous example, calling this method on the field representing "m_bar" will return the IRemoteClassField that represents the class "BarClass". Calling this method for "m_b" will return the IRemoteClassField representing the built-in class "boolean".

IRemoteArrayField : IRemoteDataField

Represents special data fields—arrays. The only major difference between data fields and arrays is that arrays have a size. You cannot access the elements of an array through its field because the field is not bound to an instance of the array. You can use the IRemoteArrayObject interface to extract the elements from an instance of an array.

GetKind

HRESULT GetKind(UINT *piKind)

Parameter | Description
[out] piKind | Returns FIELD_KIND_ARRAY.

GetType

HRESULT GetType(IRemoteField **ppType)

Parameter | Description
[out] ppType | Returns the type of the array's elements.

GetSize

HRESULT GetSize(UINT *pcElements)

Parameter | Description
[out] pcElements | Returns the number of elements in the array.

IRemoteContainerField : IRemoteField

Represents fields that contain other fields. IRemoteContainerField is an abstract interface.

GetFields

HRESULT GetFields(IEnumRemoteField **ppEnum, FIELDKIND ulKind, FIELDMODIFIERS ulModifiers, LPCOLESTR lpcszName)

Parameter | Description
[out] ppEnum | Returns an enumerator for the fields that are contained by this field and match the given characteristics.
[in] ulKind | Bitmask of flags indicating the kinds of fields to be included in the enumeration. Use zero to include all kinds.
[in] ulModifiers | Bitmask of flags indicating the modifiers of fields to be included in the enumeration. Use zero to include all modifiers.
[in] lpcszName | Name of the field to be included in the enumeration. Use NULL to include all names.

IRemoteClassField : IRemoteContainerField

Represents a class definition.

GetKind

HRESULT GetKind(UINT *piKind)

Parameter | Description
[out] piKind | Returns FIELD_KIND_CLASS.

GetType

HRESULT GetType(IRemoteField **ppType)

Parameter | Description
[out] ppType | Returns NULL.

GetFileName

HRESULT GetFileName(LPOLESTR *ppszFileName)

Parameter | Description
[out] ppszFileName | Returns the full path of the file that contains this class if it is available; for example, "c:\classes\HelloWorld.class".

GetSourceFileName

HRESULT GetSourceFileName(LPOLESTR *ppszSourceFileName)

Parameter | Description
[out] ppszSourceFileName | Returns the name of the source file used to create this class; for example, "HelloWorld.java".

GetSuperclass

HRESULT GetSuperclass(IRemoteClassField **ppSuperclass)

Parameter | Description
[out] ppSuperclass | Returns the class from which this class is derived.

GetInterfaces

HRESULT GetInterfaces(IEnumRemoteField **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the interfaces that this class implements.

GetConstantPoolItem

HRESULT GetConstantPoolItem(ULONG indexCP, BYTE **ppCPBytes, ULONG *plength)

Parameter | Description
[in] indexCP | Index in the constant pool of this class of the entry to be retrieved.
[out] ppCPBytes | Returns the constant pool data of the requested entry.
[out] plength | Returns the length of the returned constant pool entry, in bytes.

IRemoteMethodField : IRemoteContainerField

Represents a method within a class.

GetKind

HRESULT GetKind(UINT *piKind)

Parameter | Description
[out] piKind | Returns FIELD_KIND_METHOD.

GetType

HRESULT GetType(IRemoteField **ppType)

Parameter | Description
[out] ppType | Returns the return type of this method.

SetBreakpoint

HRESULT SetBreakpoint(UINT offPC)

Sets a code breakpoint at a given byte offset from the start of the method.

Parameter | Description
[in] offPC | Byte offset within this method.

ClearBreakpoint

HRESULT ClearBreakpoint(UINT offPC)

Clears a code breakpoint at a given byte offset from the start of the method.

Parameter | Description
[in] offPC | Byte offset within this method.

GetLineInfo

HRESULT GetLineInfo(IEnumLINEINFO **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator of LINEINFO structures describing the mapping between source lines and byte offset within this method. This mapping is in order of increasing offsets. The last element in the list is a dummy node with the line number field set to (the last line of the method + 1) and the offset field set to (the last offset in the method + 1).

GetBytes

HRESULT GetBytes(ILockBytes **ppLockBytes)

Parameter | Description
[out] ppLockBytes | Returns an ILockBytes interface that you can use to access this method's bytecode.

GetScope

HRESULT GetScope(IRemoteField *pField, ULONG *poffStart, ULONG *pcbScope)

Parameter | Description
[in] pField | Field whose scope within this method is to be determined.
[out] poffStart | Byte offset within this method where the scope of the given field begins.
[out] pcbScope | Length of the scope of the given field in this method, in bytes.

GetIndexedField

HRESULT GetIndexedField(ULONG slot, ULONG offPC,  IRemoteField **ppField)

Parameter | Description
[in] slot | Slot in this method of the field to be retrieved.
[in] offPC | Byte offset within this method indicating the given slot's execution context.
[out] ppField | Field contained by the given slot at the given byte offset.

IEnumRemoteField : IUnknown

Enumerates fields.

Next

HRESULT Next(ULONG celt, IRemoteField *rgelt[], ULONG *pceltFetched)

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteField **ppEnum)

IEnumLINEINFO : IUnknown

Enumerates line number information for a method.

Next

HRESULT Next(ULONG celt, LPLINEINFO rgelt, ULONG *pceltFetched)

Remarks:

typedef struct lineinfo {
    USHORT iLine;		// line number
    USHORT offPC;		// byte offset in method
} LINEINFO;

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumLINEINFO **ppEnum)

GetCount

HRESULT GetCount(ULONG *pcelt)

Parameter | Description
[out] pcelt | Returns the number of elements available through this enumerator.


Dynamic Information Interfaces

Working with MS VM
In this topic

* IRemoteObject : IUnknown

* IRemoteBooleanObject : IRemoteObject

* IRemoteXXXObject : IRemoteObject

* IRemoteArrayObject : IRemoteObject

* IEnumRemoteObject : IUnknown

* IEnumRemoteValue : IUnknown

* IEnumRemoteBooleanValue : IEnumRemoteValue

* IEnumRemoteXXXValue : IEnumRemoteValue

* IRemoteContainerObject : IRemoteObject

* IRemoteClassObject : IRemoteContainerObject

Microsoft VM | Previous | VM | Next
Java Debugger Interfaces | Previous | VM | Next

Dynamic Information Interfaces

Use these interfaces to retrieve information about objects.

IRemoteObject : IUnknown

The IRemoteObject hierarchy provides bound access to objects of different types. "Object" does not necessarily refer to an instance of a class; it refers to an instance of any type. The information obtained from an IRemoteObject is valid only during the lifetime of the actual object that it represents.

GetType

HRESULT GetType(IRemoteField **ppType)

Calls to GetType for two objects of the same type in the same namespace will return an address of the same IRemoteField object, thus enabling the debugger to cache type information.

Parameter | Description
[out] ppType | Returns the type of this object.

SetBreakpoint

HRESULT SetBreakpoint(void)

Sets a data breakpoint on the object. The breakpoint will fire when the object's value changes. For arrays, this is when any of its elements change. For classes, it is either when the object references a different instance of that class, or when any of the instance's data members change.

ClearBreakpoint

HRESULT ClearBreakpoint(void)

Clears a data breakpoint on the object.

IRemoteBooleanObject : IRemoteObject

Provides run-time access to the value of a Boolean variable.

GetValue

HRESULT GetValue(JAVA_BOOLEAN *pvalue)

SetValue

HRESULT SetValue(JAVA_BOOLEAN value)

IRemoteXXXObject : IRemoteObject

IRemoteByteObject : IRemoteObject
IRemoteCharObject : IRemoteObject
IRemoteDoubleObject : IRemoteObject
IRemoteFloatObject : IRemoteObject
IRemoteIntObject : IRemoteObject
IRemoteLongObject : IRemoteObject
IRemoteShortObject : IRemoteObject

Each of the preceding interfaces contains type-safe methods for getting and setting the values of objects of built-in types. They follow the same pattern as the IRemoteBooleanObject interface.

//
// Java primitive types
//
typedef unsigned char	JAVA_BOOLEAN;
typedef signed char	JAVA_BYTE;
typedef unsigned short 	JAVA_CHAR;
typedef double		JAVA_DOUBLE;
typedef float		JAVA_FLOAT;
typedef signed long	JAVA_INT;
typedef signed __int64	JAVA_LONG;
typedef signed short	JAVA_SHORT;

IRemoteArrayObject : IRemoteObject

Provides access to array objects.

GetElementObjects

HRESULT GetElementObjects(IEnumRemoteObject **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the elements of this array, starting at index 0.

GetSize

HRESULT GetSize(ULONG *pcElements)

Parameter | Description
[out] pcElements | Returns the number of elements in the array.

GetElementValues

HRESULT GetElementValues(IEnumRemoteValue **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the values of the elements of this array, starting at index 0.

IEnumRemoteObject : IUnknown

Enumerates objects.

Next

HRESULT Next(ULONG celt, IRemoteObject *rgelt[], ULONG *pceltFetched)

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteObject **ppEnum)

GetCount

HRESULT GetCount(ULONG *pcelt)

Parameter | Description
[out] pcelt | Returns the number of elements available through this enumerator.

IEnumRemoteValue : IUnknown

Enumerates values.

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteObject **ppEnum)

GetCount

HRESULT GetCount(ULONG *pcelt)

Parameter | Description
[out] pcelt | Returns the number of elements available through this enumerator.

IEnumRemoteBooleanValue : IEnumRemoteValue

Enumerates Boolean values.

Next

HRESULT Next(ULONG celt, JAVA_BOOLEAN rgelt[], ULONG *pceltFetched)

IEnumRemoteXXXValue : IEnumRemoteValue

IEnumRemoteByteValue : IEnumRemoteValue
IEnumRemoteCharValue : IEnumRemoteValue
IEnumRemoteDoubleValue : IEnumRemoteValue
IEnumRemoteFloatValue : IEnumRemoteValue
IEnumRemoteIntValue : IEnumRemoteValue
IEnumRemoteLongValue : IEnumRemoteValue
IEnumRemoteShortValue : IEnumRemoteValue

Each of the preceding interfaces contains type-safe methods for enumerating values of built-in types. They follow the same pattern as the IEnumRemoteBooleanValue interface.

IRemoteContainerObject : IRemoteObject

Provides access to container objects (FIELD_KIND_METHOD or FIELD_KIND_CLASS).

GetFieldObject

HRESULT GetFieldObject(IRemoteField *pField, IRemoteObject **ppFieldObject)

Takes a field of this object's class and returns the instance of that field within the object. The IRemoteField interface is in no way bound to the instance of the object. In fact, you can use the same IRemoteField interface to extract the value of that field from many different IRemoteContainerObject interfaces in the same namespace.

Parameter | Description
[in] pField | Field to retrieve from this object.
[out] ppFieldObject | Returns the object contained in this object's field.

IRemoteClassObject : IRemoteContainerObject

Provides access to class objects.

GetDerivedMostType

HRESULT GetDerivedMostType (IRemoteClassField **ppDerivedMostField)

Parameter | Description
[out] ppDerivedMostField | Returns the class field representing the object's derived-most type.


Execution Control Interfaces

Working with MS VM
In this topic

* IRemoteStackFrame : IUnknown

* IRemoteThreadGroup : IUnknown

* IEnumRemoteThread : IUnknown

* IEnumRemoteThreadGroup : IUnknown

* IRemoteThread : IUnknown

Microsoft VM | Previous | VM | Next
Java Debugger Interfaces | Previous | VM | Next

Execution Control Interfaces

Use these interfaces to manage execution.

IRemoteStackFrame : IUnknown

Provides access to call stacks within the threads of the debuggee. Each stack frame represents the state of execution within a method.

GetCallingFrame

HRESULT GetCallingFrame(IRemoteStackFrame **ppCallingFrame)

Parameter | Description
[out] ppCallingFrame | Returns the frame representing the caller of this method.

GetMethodObject

HRESULT GetMethodObject(IRemoteContainerObject **ppMethodObject)

Parameter | Description
[out] ppMethodObject | Returns the instance of the method object

GetPC

HRESULT GetPC(UINT *offPC)

Parameter | Description
[out] offPC | Returns the byte offset from the start of this method of the next instruction to be executed.

SetPC

HRESULT SetPC(UINT offPC)

Parameter | Description
[in] offPC | Sets the byte offset from the start of this method of the next instruction to be executed.

GetKind

HRESULT GetKind(FRAMEKIND *pfk)

Parameter Description
[out] pfk Returns the kind of this stack frame.
typedef enum framekind {
    FRAME_KIND_INVALID	= 0x00,
    FRAME_KIND_INTERPRETED	= 0x01,
    FRAME_KIND_NATIVE		= 0x02,
    FRAME_KIND_JIT_COMPILED	= 0x03
} FRAMEKIND;

IRemoteThreadGroup : IUnknown

Provides access to thread groups.

GetName

HRESULT GetName(LPOLESTR *ppszName)

Parameter | Description
[out] ppszName | Returns the name of this thread group.

GetThreads

HRESULT GetThreads(IEnumRemoteThread **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the threads in this thread group.

GetThreadGroups

HRESULT GetThreadGroups(IEnumRemoteThreadGroup **ppEnum)

Parameter | Description
[out] ppEnum | Returns an enumerator for the thread groups in this thread group.

IEnumRemoteThread : IUnknown

Enumerates threads.

Next

HRESULT Next(ULONG celt, IRemoteThread *rgelt[], ULONG *pceltFetched)

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteThread **ppEnum)

IEnumRemoteThreadGroup : IUnknown

Enumerates thread groups.

Next

HRESULT Next(ULONG celt, IRemoteThreadGroup *rgelt[], ULONG *pceltFetched)

Skip

HRESULT Skip(ULONG celt)

Reset

HRESULT Reset(void)

Clone

HRESULT Clone(IEnumRemoteThreadGroup **ppEnum)

IRemoteThread : IUnknown

Provides access to threads.

GetName

HRESULT GetName(LPOLESTR *ppszName)

Parameter | Description
[out] ppszName | Returns the name of this thread.

GetCurrentFrame

HRESULT GetCurrentFrame(IRemoteStackFrame **ppCurrentFrame)

Parameter | Description
[out] ppCurrentFrame | Returns the currently executing stack frame on this thread.

GetThreadGroup

HRESULT GetThreadGroup(IRemoteThreadGroup **ppThreadGroup)

Parameter | Description
[out] ppThreadGroup | Returns the thread group that contains this thread.

Go

HRESULT Go(void)

Continues execution of this thread. This call returns immediately.

Step

HRESULT Step(void)

Steps a single instruction of bytecode. This call steps over method calls. It returns immediately. The StepEvent method is called when the execution is complete.

StepIn

HRESULT StepIn(void)

Steps over a single bytecode instruction. This call steps into method calls. It returns immediately. The StepEvent method is called when the execution is complete.

StepOut

HRESULT StepOut(void)

Continues execution until the end of the current method. The next instruction to be executed is the first instruction after the call in the calling method. This call returns immediately. The StepEvent method is called when the execution is complete.

RangeStep

HRESULT RangeStep(UINT offStart, UINT offEnd)

Continually steps until the PC is outside the given range. This call steps over method calls. The StepEvent method is called when the execution is complete.

Parameter | Description
[in] offStart, offEnd | Start and end byte offsets from the beginning of the current method.

RangeStepIn

HRESULT RangeStepIn(UINT offStart, UINT offEnd)

Continually steps until the PC is outside the given range. This call steps into method calls and calls StepEvent at the first instruction of the stepped-into method. If the debugger returns S_FALSE from StepEvent, then the VM continues executing to the end of this method, and continues executing within the given range. This call returns immediately. The StepEvent method is called when the execution is complete.

Parameter | Description
[in] offStart, offEnd | Start and end byte offsets from the beginning of the current method.

Destroy

HRESULT Destroy(void)

Destroys this thread. The ThreadDestroyEvent method is called when the operation is complete.

Suspend

HRESULT Suspend(void)

Suspends execution of this thread.

Resume

HRESULT Resume(void)

Resumes execution of this thread.

GetSuspendCount

HRESULT GetSuspendCount(ULONG *pcSuspend)

Parameter | Description
[out] pcSuspend | Returns this thread's current suspend count.


Introduction

This section describes the invocation interfaces, which include the following:
IJavaExecute
IJavaExecute2
IEnumJAVAPROPERTIES
Structures

See Structures for details about the structures these interfaces use.

The globally unique identifiers (GUIDs) for the invocation interfaces are defined in the file Javaexec.h.


IJavaExecute

// IUnknown methods
HRESULT QueryInterface(REFIID riid, LPVOID *ppv);
ULONG   AddRef();
ULONG   Release();

// IJavaExecute methods
HRESULT GetDefaultClassPath(LPOLESTR *ppszClassPath);
HRESULT Execute(LPJAVAEXECUTEINFO pjei, LPERRORINFO *pperrorinfo);

IJavaExecute::GetDefaultClassPath

HRESULT GetDefaultClassPath(LPOLESTR *ppszClassPath)

Sets ppszClassPath to a string describing the default class path (computed from the registry and the environment).

Parameter | Description
ppszClassPath | Address of the buffer to receive the class path. The elements in the class path are separated by semicolons, and elements are searched in the order they appear in the string.

Remarks:

The caller must free the returned string using the CoTaskMemFree function.

IJavaExecute::Execute

HRESULT Execute(LPJAVAEXECUTEINFO pJavaExecuteInfo, LPERRORINFO *ppErrorInfo);

Loads a Java class and executes its static main method.

The main method must have the following signature:

public static void main( String[] )

Return Value:

If the main method runs successfully and does not throw an uncaught Java exception, the Execute method returns S_OK, and ppErrorInfo is set to NULL.

If the main method runs successfully and throws an uncaught Java exception, the Execute method returns S_OK, and ppErrorInfo is set to an IErrorInfo object that describes the exception.

If the class is not found or does not expose a main method, or if there are insufficient resources to run the method, the Execute method returns a failing HRESULT.

Parameter | Description
pJavaExecuteInfo | This structure provides the name of the class, the arguments, and the execution environment. See JAVAEXECUTEINFO.
ppErrorInfo | Points to a buffer that receives an IErrorInfo interface object if the main method throws a Java exception. This parameter can be NULL if this information is not needed.


IJavaExecute2

// IUnknown methods
HRESULT QueryInterface(REFIID riid, LPVOID *ppv);
ULONG   AddRef();
ULONG   Release();

// IJavaExecute methods
HRESULT GetDefaultClassPath(LPOLESTR *ppszClassPath);
HRESULT Execute(LPJAVAEXECUTEINFO pjei, LPERRORINFO *pperrorinfo);

// IJavaExecute2 methods
HRESULT SetSystemProperties(LPENUMJAVAPROPERTY penum);
HRESULT SetClassSource(DWORD dwType, LPVOID pData, DWORD dwLen);

See also IJavaExecute.

IJavaExecute2::SetSystemProperties

HRESULT SetSystemProperties(LPENUMJAVAPROPERTY pEnumJavaProperty)

Sets property values for java.lang.System.

Parameter | Description
pEnumJavaProperty | Enumeration object that produces a set of key/value pairs. The SetSystemProperties method will enumerate through the entire collection and map each key to the associated value.

IJavaExecute2::SetClassSource

HRESULT SetClassSource(DWORD dwType, LPVOID pData, DWORD dwLen);

Inserts a special source of classes into the class path. These elements are searched before any other elements in the class path.

Parameter | Description
dwType Type of class source. The following types are recognized.
CLASS_SOURCE_TYPE_MODULERESOURCES
Allows classes to be stored within a Microsoft® Win32® resource.
CLASS_SOURCE_TYPE_ISTORAGE
Not currently implemented.

These values are defined in Javaexec.h

pData Address of an information structure whose format is type dependent.

For CLASS_SOURCE_TYPE_MODULERESOURCES, this is an address of a JAVACLASSRESOURCEINFO structure.

dwLen | Size in bytes of the structure pointed to by pData.


IEnumJAVAPROPERTIES

// IUnknown methods
HRESULT QueryInterface(REFIID riid, LPVOID *ppv);
ULONG   AddRef();
ULONG   Release();

// IEnumJavaPROPERTIES methods
ULONG   Next(ULONG celt, LPJAVAPROPERTY rgelt, ULONG *pceltFetched)
HRESULT Skip(ULONG celt)
HRESULT Reset()
HRESULT Clone(LPENUMJAVAPROPERTY *ppenum);

This enumerator lists key/value pairs for IJavaExecute2::SetSystemProperties.


Structures

JAVAEXECUTEINFO

typedef struct {
    DWORD     cbSize;
    DWORD     dwFlags;
    LPCOLESTR  pszClassName;
    LPCOLESTR *rgszArgs;
    ULONG     cArgs
    LPCOLESTR pszClassPath
} JAVAEXECUTEINFO, *LPJAVAEXECUTEINFO;

This structure is passed into IJavaExecute::Execute.

Parameter | Description
cbSize | Must be set to the size of JAVAEXECUTEINFO in bytes.
dwFlags Can be:
JEIF_VERIFYCLASSES Turn on verification of all classes. By default, the verification setting from the registry will be used.
pszClassName Name of the class to load. The class must have a public method that matches the signature:
public static void main(java.lang.String[]);
rgszArgs | Array of Unicode strings. This string is converted to a Java array of strings, which is then passed as the argument to the main method. The cArgs member indicates the number of strings in this array.
cArgs | Number of strings in rgszArgs.
pszClassPath Specifies additional class path elements (separated by semicolons). These class path elements will be searched before the elements in the default class path.

This member can be NULL if no additional elements are required.

Remarks:

The class path is a per-process variable. Any extensions made to the class path by means of the Execute method will persist after the Execute method has returned. Therefore, the Execute method is not suitable for use in a shared library.

See Also: IJavaExecute::Execute

JAVAPROPERTY

typedef struct {
    LPOLESTR pszKey;
    LPOLESTR pszValue;
}   JAVAPROPERTY, * LPJAVAPROPERTY;

This structure is used as part of IEnumJAVAPROPERTIES. The pszKey and pszValue members are both allocated using the CoTaskMemAlloc function, and are released by the caller of IEnumJAVAPROPERTIES::Next.

See Also: IEnumJAVAPROPERTIES

JAVACLASSRESOURCEINFO

struct {
    HMODULE   hModule;
    DWORD     dwResourceID;
};

This structure is passed to IJavaExecute::SetClassSource.

Parameter | Description
hModule | Handle to the module that contains the resource.
dwResourceID Identifies the resource that contains the class data. The resource must be of type RCDATA.

See JAVACLASSRESOURCE for the format of the resource data.

JAVACLASSRESOURCE

struct {
    DWORD dwSignature;
    DWORD dwNumClasses;
    DWORD dwFormatVersion;
    DWORD dwFlags;
    [Class Information Section]
    [Class Names Section]
    [Class Data Section]
};

Parameter | Description
dwSignature | Must be the value 0x43524E44.
dwNumClasses | Number of classes contained within this resource.
dwFormatVersion | Must be 1.
dwFlags | Reserved for future use.

Class Information Section:

The Class Information Section consists of an array of structures that detail the position of each class within the resource. Each class will have one of these structures. The format of this structure is:

struct {
    DWORD dwNameOffset;
    DWORD dwSize;
    DWORD dwDataOffset;
};
dwNameOffset | Offset from the beginning of the resource to the class name.
dwSize | Size of the class data.
dwDataOffset | Offset from the beginning of the resource to the class data.

Class Names Section:

The Class Names Section contains the names of the classes contained in the resource. The names are packed together, back-to-back, so that each name immediately follows the previous name. You must use a slash mark (/) to separate package names, and you must terminate each name with the null character.

Class Data Section:

The Class Data Section contains class file data for each class stored in the resource. The format for each class file is the same as the standard Java binary class file format.


Background

The standard model of a virtual machine (VM) for Java continually interprets a sequence of bytecodes that describe the intent of a Java applet or application. Each time the VM encounters a bytecode, whether it has interpreted it many times before or not, there is a (relatively) lengthy translation process. Even though various approaches exist for speeding up this approach somewhat, this interpretation process accounts for significantly slower execution performance compared to equivalent compiled native code.

To improve this performance, JIT compilers interact with the VM and compile appropriate bytecode sequences into an equivalent piece of native machine code. This process occurs at run time (that is, as the particular piece of code is going to be executed) rather than at compile time, as is traditionally the case with compiled languages such as C and C++. Rather than interpret the same bytecodes repeatedly, the hardware (the CPU) can run ("interpret") the native code. This can allow quite dramatic performance gains in the execution speed. There is, however, a tradeoff.

The time that the JIT compiler takes to compile the bytecodes is added to the overall execution time. For example, when a method executes only once and does not contain any loops, the overall performance might be reduced when JIT compilation occurs.

Note that JIT compilation has potential advantages over traditional code compilation techniques in some aspects: for example, it can target the specific machine on which the program is actually running (for example, 486 versus Pentium), rather than for a general CPU (or "the most likely" one), which is the best that traditional approaches (such as targeting a generic x86 platform) can achieve.


JIT Structure

The following diagram gives an overview of the JIT compiler's internal structure. The structure is similar to that used in typical static compiler environments. Bytecodes (together with requested symbol and other information) are converted ("imported") into an internal representation. The internal representation is then used to generate code, which is optimized appropriately. There is also a linker component that resolves references for the in-memory generated code, which is then ready to run.


The JIT Compiler/VM Interface

The following diagram illustrates the relationship between the JIT compiler and the Microsoft VM for Java.

The JIT compiler and the VM provide interfaces that both use to enable effective JIT code compilation. The "compilation unit" for the JIT compiler is a single method. The VM alone decides which method to compile. Tools vendors might want to provide facilities in their tools (for example, through language constructs or user interface) to augment .class files so that they indicate which methods to JIT (the precise format of such .class file attributes is TBD).

These interfaces are designed to allow clean separation and independence between the VM and the JIT compiler. This will enable other vendors to replace one JIT compiler with another, as appropriate.

A JIT compiler (vendor) can make the following assumptions.

  • Code and data blocks allocated through the respective VM helper functions will stay in place. Therefore, most references to methods and data members can be resolved at compilation time.
  • The first element in every object contains the reference to the respective class's vtable (method-pointer table).
  • For arrays (which are also Java objects) the offset for the element count as well as the offset for the first array element are always at the same fixed offset relative to the beginning of the object (array).
  • Every loaded interface is assigned a unique handle, which allows quick access at run time.
  • The vtable offsets of interface methods are always the same across all implementations of the interface. Therefore, all vtable offsets for methods can be resolved at compile time.

At the same time, the code and data that a JIT compiler generates for the Microsoft VM for Java must meet the following criteria.

  • All methods must have a local stack frame.
  • For the x86 platform, the calling convention is basically "__pascal": parameters must be pushed from left to right ("this" is pushed before any user arguments), the callee pops arguments, EBX/ESI/EDI are the callee-saved registers, and the FP stack is always empty on entry to methods, return values in EAX (32-bit scalars), EDX:EAX (64-bit integers), or on the FP stack (floats and doubles).
  • The JIT compiler must provide an API that enumerates all live references in a method while it calls a method (stack crawling support for GC).
  • Optionally, the JIT compiler may provide an API that enumerates all live references in a method at any time (this allows GC to occur at any time).
  • Currently only "base" pointers can be live at points where GC might occur (for example, the code might not have a pointer to the interior of an object/array that is live across a method call).
  • Code sharing across multiple namespaces is supported (optional).

The JIT compiler decides whether to allow interruption by the garbage collector at any time or just while a method calls another method. The latter is certainly easier to implement and needs less information at run time, but in certain scenarios it could disable the garbage collection process for an extended period of time (for example, a method executes a loop that does not contain a method call). In those cases, the JIT compiler must insert code that (conditionally) invokes the garbage collector directly unless it can be determined that the code will execute method calls frequently enough. To give the JIT maximal flexibility, it can make this decision for every method individually.

Beyond just generating code for a method, the JIT must provide additional information to enable proper execution and debugging of Java applications. Depending on the type of information, that is done in two ways:

  • Information defined by the VM: The JIT compiler provides this information at compile time to the VM, and the VM records and interprets it (for example, exception handler tables and line number information).
  • Private JIT information: The JIT compiler can store any private information along with each method so that it can provide the requested information to the VM at run time; the VM saves the information (to the VM it is just a single block of opaque data) and passes it back to the JIT compiler at run time (for example, enumeration of live object references in a stack frame, decision if a method is "GC-safe" at the current offset, and so on).


Introduction

This section provides an overview of the extended Microsoft Component Object Model (COM) attributes. These attributes are used to provide marshaling information between Java objects and COM objects. If a development environment generates these attributes, the Microsoft Win32 VM for Java (Microsoft VM) will use them to marshal parameters between COM and Java.
Java Object Categories
Identity of Java-Callable Wrappers and Java-Callable Data Wrappers
The Attribute Specification
Attribute Reference


Java Object Categories

In this model, all Java objects fall into one of the following categories.

  • Pure Java objects. These objects are allocated on the garbage-collected heap, and garbage collection controls their lifetime. Optionally, pure Java objects can have an associated proxy known as the COM-callable wrapper (CCW), which is a thread-safe, VM-created COM object that exports vtable or IDispatch interfaces. These proxies are implemented by the run time and marshal to methods on the Java object. As long as there is one outstanding AddRef method on the CCW, the CCW maintains a "root pointer" to the actual Java object to prevent it from being reclaimed.
  • Java-callable wrappers (JCWs). JCWs are stateless "wrapper" objects that represent a single COM object. JCWs can either be instances of special classes generated from typelibs, or be automatically made instances of the com.ms.com.CUnknown class. Unlike normal classes, which implement a fixed set of interfaces declared by the object's class, JCWs can be cast to any interface at will, provided that the underlying COM object accepts the QueryInterface of the interface's underlying IID (stored in attributes in the interface's .class file.) JCWs always inherit from java.lang.Object. They currently cannot derive from any other class.
  • Java-callable data wrappers (JCDWs). These are proxies for external data structures (structs, unions, and arrays.) In this case, the external data structure is passed in from native code through a COM interface. To avoid copying data, the proxy will maintain an address of the actual data, and the proxy's fields will be mapped by means of attributes to offsets within the data structure. A set of application programming interfaces (APIs) will allow byte-level traversal of the memory (as a fallback for very difficult structures such as DVTARGETDEVICE). Garbage collection controls a proxy's lifetime. Since no universal protocol exists for tracking an external data structure's lifetime, the burden is on the developer not to use the proxy after the underlying data structure has been released.


Identity of Java-Callable Wrappers and Java-Callable Data Wrappers

Java-callable wrappers (JCWs) for Component Object Model (COM) objects and proxies may contain Java-implemented methods, but no fields (other than those mapped to the underlying COM object) or any other dynamic state, because there is no way to specify a constructor to be called at marshaling time.

JCWs for COM objects will behave as expected with regard to the "==" operator. That is, "==" will yield a true value if and only if the underlying COM objects have the same IUnknown interface pointer.

The "==" operator will not be maintained for Java-callable data wrappers (data proxies). The cost of maintaining identity for data proxies (many of which will be temporary stack-allocated arguments) is too high and data proxies are already non-Java-like, in that their useful lifetimes are determined externally rather than by garbage collection.


Attribute Reference

This section describes, at the bit level, the details of the attributes that must be present in any .class file that is to be used to invoke a Component Object Model (COM) object from Java or expose a Java object as a COM object.

The following attributes must be present.
Level | Name | Description
Class | COM_ClassType | Denotes the implementation language
Class | COM_GuidPool | Stores IIDs and class identifiers (CLSIDs)
Class | COM_MethodPool | Stores distilled typelib information
Method | COM_ExposedAs_Group | Exposes a Java method to COM
Method | COM_ProxiesTo | Exposes a COM method to Java
Field | COM_MapsTo | Exposes external data to Java

All unused bits in Flag fields must be zero.

Data Type Sizes and Alignment

Except where noted, BYTEs, WORDs, and DWORDs are unsigned and stored in the .class file in Big-Endian format.
BYTE | 8 bits
WORD | 16 bits
DWORD | 32 bits

There is no implicit padding between the fields of the structures, or any padding after the last field of any structure.

COM_ClassType

typedef struct {
    WORD        Flags;          // Must be zero. Reserved for future use.
    WORD        ClassType;      // CCTCT_JCW or CCTCT_JCDW
    WORD        CLSIDIndex;     // Optional index to CLSID (-1 for none)
} CCT_Attr;

This attribute, of attribute level Class, denotes the implementation language.

Parameter | Description
Flags | This field must be zero.
ClassType The only legal values are CCTCT_JCW and CCTCT_JCDW.

The actual type of a class is determined as follows:

  • If the class has a ClassType of type "CCTCT_JCW", the class type is "JCW".
  • If the class has a ClassType of type "CCTCT_JCDW", the class type is "JCDW".
  • All other situations are illegal.
CLSIDIndex If ClassType is not CCTCT_JCW, the contents of the field must be 0xffff.

If ClassType is CCTCT_JCW, and the CLSIDIndex is not 0xffff, it must indicate a valid index into the GuidPool. The globally unique identifier (GUID) corresponding to this index will be used as the CLSID of the Component Object Model (COM) object to load when you create an instance of this class by using the new operator.

Restrictions:

If the class type is CCTCT_JCW, the access flags for the class must be a subset of:
ACC_ABSTRACT
ACC_FINAL
ACC_PUBLIC

If the class type is CCTCT_JCDW, the access flags for the class must be a subset of:
ACC_FINAL (required)
ACC_PUBLIC

The class's superclass must be java.lang.Object.

If the class type is CCTCT_JCDW, the ACC_FINAL access flag must be present, and all fields defined by the class must have a COM_MapsTo.

COM_GuidPool

typedef struct {
    WORD        nGuids;         // # of guids in table
    // GUID     aGuid[nGuids];
} CGP_Attr;

Stores IIDs and class identifiers (CLSIDs).

Parameter | Description
nGuids | Indicates the number of GUIDs defined in this table.
aGuid Stores the actual GUID representations. A GUID is a 16-byte integer that is subdivided into fields as follows:
struct _GUID {
    DWORD Data1;
    WORD  Data2;
    WORD  Data3;
    BYTE  Data4[8];
}

Each field is stored in LITTLE-ENDIAN format in the .class file. This is an exception from the normal rule that all integers are stored in Big-Endian.

Remarks:

This attribute stores IIDs and CLSIDs that are referenced by index from the MethodPool. Valid indexes range from 0 inclusive to nGuids exclusive. The index 0xffff is reserved to indicate the "null" index. Hence, the GuidPool can contain a maximum of 65,535 globally unique identifiers (GUIDs).

Restrictions:

The class access flags must be a subset of:
ACC_ABSTRACT
ACC_FINAL
ACC_INTERFACE
ACC_PUBLIC

COM_MethodPool

typedef struct {
    WORD        nFuncs;         // # of functions in table
    // CFuncDesc aCFunc[nFuncs]
} CMP_Attr;

Stores distilled typelib information.

Parameter | Description
nFuncs | Indicates the number of CFuncDesc structures defined in this table.
aCFunc | Stores the actual CFuncDesc structures. The CFuncDesc structures are variable-sized structures.

Remarks:

This attribute stores the "method signatures" of the COM methods that are invoked by and implemented by the Java methods in the .class file. These signatures (CFuncDesc structures) are referenced by index by other attributes in the class. Valid indexes range from 0 inclusive to nFuncs exclusive. The index 0xffff is reserved to indicate the "null" index.

Restrictions:

The class access flags must be a subset of:
ACC_ABSTRACT
ACC_FINAL
ACC_INTERFACE
ACC_PUBLIC

Though the CFuncDesc structure allows you to specify an IID for individual CFuncDesc, the Virtual Machine requires that all CFuncDesc structures in a .class file reference the same IID in the CGuidPool.

This restriction does not apply to IIDs embedded in the CTypeDesc structures within the parameter arrays and return types of the CFuncDesc structures.

CTypeDesc

typedef struct {
    BYTE        Type;       //TD_* value
    BYTE        Flags;      //TDF_* flags
    union {
        WORD    IIDIndex;   // (for TD_INTF only)
        WORD    SizeIndex;  // (for TD_STRUCT only)
    };
} CTypeDesc;

This structure describes the type of a parameter or return value of a COM method.

Parameter Description
Type Must a member of the following TD_* enumeration. Supported types are grouped as follows:
Void | TD_VOID | No value. Only valid as a return type.
Integral | TD_I1 | Signed 8-bit
TD_I2 | Signed 16-bit
TD_I4 | Signed 32-bit
TD_I8 | Signed 64-bit
TD_U1 | Unsigned 8-bit
TD_U2 | Unsigned 16-bit
TD_U4 | Unsigned 32-bit
TD_U8 | Unsigned 64-bit
Floating point | TD_R4 | 32-bit float
TD_R8 | 64-bit float
Pointer | TD_PTR | Value is a pointer to some data structure.
Struct | TD_STRUCT | Value is a structure that is being passed by value.
Interface | TD_INTF | Value is an IUnknown derivative.
String | TD_JSTR | Value is a BSTR (OLE Automation)
Array | TD_JARR | Value points to the first element of a fixed-sized array.
Flags Flags are grouped into in/out flags and thread-model flags.

In/out:

If you use CTypeDesc to describe a parameter, the flags must specify one of TD_IN, TD_OUT, or TD_INOUT. For all types other than TD_PTR, TD_JSTR, and TD_JARR, the value of this subflag must be TD_IN.

If you use CTypeDesc to describe a return value or a MapsTo type, this subflag must be set to zero.

Thread Marshaling Mode:

This subflag is meaningful only for the TD_INTF type. For all others, it must be set to zero. This subflag indicates the desired thread marshaling mode of the interface pointer. If the Virtual Machine creates a JCW to represent this COM interface, it will do the appropriate marshaling. If this TypeDesc is being used to marshal to a Java class that is not a Java-callable wrapper (JCW), this subflag must be have the value 0.

The Virtual Machine supports two marshaling modes:
TDF_AUTOMARSHAL | COM methods invoked through JCW methods will be marshaled by the Virtual Machine to the thread on which the JCW was created. This allows non-threadsafe COM objects to be invoked from multiple Java threads without explicit marshaling.
TDF_NOMARSHAL | COM methods invoked through JCW methods will occur on the calling thread. This mode is most suitable for thread-safe COM objects. If the object is not thread-safe and this mode is used, the caller must restrict calls to the JCW to the thread on which the JCW was received.

The marshaling mode is a property of an instance of a JCW class, not of the JCW class itself.

In certain cases, the Virtual Machine may produce a Java object that assumes a different marshaling mode than this subflag indicates. This can happen if the interface pointer was previously marshaled to Java through another method whose parameter was flagged with the less-restrictive marshaling mode. It can also happen if the Virtual Machine itself created the incoming interface pointer (these interface pointers are all thread-safe).

union {
    WORD IIDIndex;
    WORD SizeIndex;
    }

For types other than TD_STRUCT, TD_JARR, and TD_INTF, this union must be set to zero.

If the type is TD_STRUC, this field must be set to an index into the constant pool: the constant pool item must be type CP_Integer and must indicate the size of the struct in bytes.

If the type is TD_JARR, this field must contain the expected number of elements in the array. TD_JARR cannot be used to pass variable-sized arrays.

If the type is TD_INTF, this field must be set to a valid index into the GuidPool. 0xffff (the "null" index) is not valid.

CVtblMethod

typedef struct {
    WORD        IIDIndex;
    WORD        VtblIndex;
    WORD        nArguments;
    WORD        wRetValParameter;   // -1 means none
    CTypeDesc   RetType;
    // Followed by array of CTypeDesc's for parameters
    CTypeDesc   aParamType[1];
} CVtblMethod;

Describes a vtable-based method in a COM interface. References to this structure can appear in both ExposedAs_Group attributes and ProxiesTo attributes.

Parameter | Description
IIDIndex | Valid index into the GuidPool that describes the IID of the COM interface that implements this method. 0xffff is not valid here.
VtblIndex | Denotes which vtable element the method occupies. The values 0, 1, and 2 are not legal here, because these correspond to the IUnknown interface methods that cannot be overridden. In addition, if the method pool contains CDispMethod structures using the same IID, values 3, 4, 5, and 6 must be avoided (because they correspond to IDispatch interface methods that the Microsoft VM supplies).
nArguments Number of parameters in the aParamType member. This count does not include the automatic this parameter passed to all COM methods.

If the wRetValParameter member is 0xffff, this count must match the number of parameters in the corresponding Java signature exactly. Otherwise, the count must be exactly one greater than the corresponding Java signature.

wRetValParameter If this member contains a value other than 0xffff, it must contain a value between 0 (inclusive) and nArguments (exclusive). This indicates that the parameter whose index equals wRetValParameter is actually a pointer through which the method returns its "true" return value. The aParamType member for this parameter must indicate the type of the buffer (the "pointer to" is implicit), and the RetType must be TD_VOID. In addition, the return type of the Java method sig must be compatible with the retval parameter.

If this COM method is invoked from Java, the Virtual Machine will supply a return value buffer of the appropriate type to the COM method. Upon a successful return from the COM method, (see CFuncDesc.Flags for what constitutes a successful return).

If you use Java to implement this COM method, the Virtual Machine will remove the retval pointer parameter from the list of arguments presented to the Java method. When the Java method returns, the Virtual Machine will convert the Java method's return value to COM representation, then write it to the retval buffer passed in from COM. The Virtual Machine will then create a COM return value that indicates success (see CFuncDesc.Flags for what constitutes a successful return).

RetType | Describes the return type. This type must be TD_VOID if wRetValParameter contains a value other than 0xffff, or if CFuncDesc.Flags has the CMDF_HRESULT_RETVAL bit set.
aParamType | Describes the parameter of each COM method.

Remarks:

For vtable methods, the Virtual Machine supports the following pairings between Java and COM types.
Java | COM | As return type | Restrictions
Any integral | Any integral | Yes
boolean | TD_I4 or TD_U4 | Yes
float | TD_R4 | Yes
double | TD_R8 | Yes
JCDW | TD_PTR | Yes | [1]
JCDW | TD_STRUCT | No
java.lang.String | TD_JSTR | Yes
object | TD_INTF | Yes | [2]
array of integrals | TD_JARR | No
array of floats | TD_JARR | No
array of booleans | TD_JARR | No
array of java.lang.String | TD_JARR | No
array of objects | TD_JARR | No | [2]
[1] You cannot use JCDWs that have embedded Java object types as return types.
[2] You must declare the Java object type as a Java interface, JCW class, or java.lang.Object.

These values intentionally match the VT_* enum values that are allowed in a VARIANT.
VTD_BOOL
VTD_BSTR
VTD_CY
VTD_DATE
VTD_DISPATCH
VTD_EMPTY
VTD_ERROR
VTD_I2
VTD_I4
VTD_NULL
VTD_R4
VTD_R8
VTD_UI1
VTD_UNKNOWN
VTD_VARIANT

Modifiers to VTD_ types. These do not have the same values as their VT_* equivalents because those values do not fit in a byte.
VTD_ARRAY
VTD_BYREF

CVarTypeDesc

typedef struct {
    BYTE        type;         //VTD_* value
    WORD        optname;      //(0 or constant-pool index to utf8)
    BYTE        Flags;        // TDF_* values
} CVarTypeDesc;

Describes the type of a single parameter or return value to an IDispatch interface method.

Parameter | Description
type | Contains a "compressed VARTYPE" value, defined by the VTD_* values.
optname | If nonzero, this field must be a constant-pool index to a CP_Utf8 that gives the parameter's name. This field is optional.
Flags One of these values:
CMDF_DISPATCH This flag indicates that the function is a Dispatch method.
CMDF_HRESULT_RETVAL This flag cannot be used with CMDF_DISPATCH. This flag indicates that the return type of the method is an HRESULT and that it is to be mapped to an exception on the Java side.

If this flag is used, the declared type of the RetVal must be TD_VOID.

When this flag is on, the Virtual Machine will treat all return values from COM objects as HRESULTs and will throw a Java exception (details TBD) if the HRESULT is not S_OK.

Conversely, the Virtual Machine will map all uncaught exceptions from Java code into a failing HRESULT, and will supply a return value of S_OK otherwise.

CDispMethod

typedef struct {
    WORD           IIDIndex;
    DWORD          Dispid;
    WORD           disptype;
    WORD           dispname;
    WORD           nArguments;
    CVarTypeDesc   RetType;
    // Followed by array of CVarTypeDesc's for parameters
    CVarTypeDesc   aParamType[1];
} CDispMethod;

Describes an OLE Automation method or property.

Parameter | Description
IIDIndex | Must be a valid index into the GUID pool and denotes the IID (typically IID_IDispatch, but can be any interface that derives from the IDispatch interface) through which this method is exposed.
disptype Describes the dispmember type. One of:
DISPATCH_METHOD
DISPATCH_PROPERTYGET
DISPATCH_PROPERTYPUT
DISPATCH_PROPERTYPUTREF
dispname | If this field is nonzero, it must be a valid index into the constant pool and the index must reference a CP_Utf8 that provides the name of the method. This field is required only if CDispMethod is referenced by an ExposedAs_Group attribute.
nArguments | Number of arguments.
RetType | Describes the type of the return value.
aParamType | Describes the type of the return value.

Remarks:

For Dispatch methods, the Virtual Machine supports the following pairings between Java and COM types. Because IDispatch::Invoke relies on VariantChangeType to convert a wide variety of types to another, the actual possibilities are larger than are represented here.
Java | Variant | As return type
Any integral | Any integral | Yes
Any float | Any float | Yes
One element array of:
short | VT_BYREF|VT_I2 | No
int | VT_BYREF|VT_I4 | No
float | VT_BYREF|VT_R4 | No
double | VT_BYREF|VT_R8 | No
byte | VT_BYREF|VT_UI1 | No
Object/interface | VT_BYREF|VT_UNKNOWN | No
Object/interface | VT_BYREF|VT_DISPATCH | No
java.lang.String | VT_BYREF|VT_BSTR | No
Object or interface | VT_UNKNOWN | Yes
Object or interface | VT_DISPATCH | Yes
java.lang.String | VT_BSTR | Yes

CFuncDesc

typedef struct {
    WORD        cbSize;         // size of entire CFuncDesc in bytes
    WORD        Flags;          // CMDF_* values
    union {
        CVtblMethod mvm;
        CDispMethod mdm;
    };
} CFuncDesc;

Describes a single method in the method pool.

Parameter | Description
cbSize | Size of CFuncDesc (including the cbSize member), in bytes.
Flags One of these values:
CMDF_DISPATCH Indicates that the function is a Dispatch method.
CMDF_HRESULT_RETVAL This flag cannot be used with CMDF_DISPATCH. This flag indicates that the return type of the method is an HRESULT and that it is to be mapped to an exception on the Java side.

If this flag is used, the declared type of the RetVal must be TD_VOID.

When this flag is on, the Virtual Machine will treat all return values from COM objects as HRESULTs and will throw a Java exception (details TBD) if the HRESULT is not S_OK.

Conversely, the Virtual Machine will map all uncaught exceptions from Java code into a failing HRESULT, and will supply a return value of S_OK otherwise.

COM_ExposedAs_Group

typedef struct _COM_ExposedAs_Group {
    WORD       Flags;           //none defined
    WORD       nExposedAs;
    // followed by array of CExposedAs's.
} CEAG_Attr;

This attribute, of attribute level Method, is a collection of ExposedAs structures, each of which causes the Java method to be exposed as a COM method.

Parameter | Description
Flags | Must be zero.
nExposedAs | Number of ExposedAs attributes that follow.
CEA ExposedAs[nExposedAs] | Array of exposed as.

Restrictions:

The access flags for the method must be a subset of:
ACC_ABSTRACT
ACC_FINAL
ACC_NATIVE
ACC_PRIVATE
ACC_PROTECTED
ACC_PUBLIC
ACC_SYNCHRONIZED

The class cannot have a ClassType attribute.

_COM_ExposedAs

typedef struct _COM_ExposedAs {
    WORD        Flags;
    WORD        MethodPoolIndex;
} CEA;

Each ExposedAs structure causes the Java method to be exposed as a COM method.

Parameter | Description
Flags | Must be zero.
MethodPoolIndex | Must be a valid index into the MethodPool.

COM_ProxiesTo

typedef struct _COM_ProxiesTo {
    WORD        CP_Flags;
    WORD        MethodPoolIndex;
} CPT_Attr;

Denotes that the Java method is implemented using COM.

Parameter | Description
CP_Flags | Must be zero.
MethodPoolIndex | Must be a valid index into the MethodPool.

Restrictions:

The access flags for the method must be a subset of:
ACC_ABSTRACT (on interfaces only)
ACC_FINAL
ACC_NATIVE (required)
ACC_PRIVATE
ACC_PROTECTED
ACC_PUBLIC

COM_MapsTo

typedef struct _COM_MapsTo {
    WORD        Flags;      // MTF_* values
    WORD        wPad;
    DWORD       dwOffset;
    CTypeDesc   typedesc;
} CMT_Attr;

Denotes that data for the field is stored in externally allocated memory.

Parameter | Description
Flags Can be this value:
MTF_AUTOOFFSET: If this flag is set, dwOffset must be zero and the Virtual Machine will compute the offset for the hosting platform. This allows the structure definition to move freely between platforms.

Every MapsTo in a .class file must use the same setting for MTF_AUTOOFFSET.

The auto-packing algorithm for the x86 platform is the ZP4 (DWORD-aligned) packing order.

wPad | Must be zero.
dwOffset | Offset in bytes within the external data structure. If MTF_AUTOOFFSET is on, this field has no meaning and must be set to zero.
typedesc | Describes the native type of the field.

Restrictions:

The access flags for the field must be a subset of:
ACC_FINAL
ACC_PRIVATE
ACC_PROTECTED
ACC_PUBLIC


The Attribute Specification

Working with MS VM
In this topic

* The type Attribute

* The ExposedAs Attribute

* The ProxiesTo Attribute

* The MapsTo Attribute

* Method and Type Descriptions

Microsoft VM | Previous | VM | Next
Overview of COM Attributes for Java Class Files | Previous | VM | Next

The Attribute Specification

This section describes the attributes at a semantic level without getting into representational issues.

Note that the attributes specify detail at the method level whenever possible. That is, while you customarily think of interfaces having IIDs, the attribute specification specifies an IID for each method, so that one Java interface could conceivably proxy to methods on multiple IIDs. For performance reasons, however, the first version of the Microsoft VM will not support this full generality. All methods on an interface will be required to have the same IID. The attribute language itself, however, is consciously designed not to obstruct future flexibility.

This section describes the attributes using an informal representation in which normal Java syntax is augmented by an "attribute syntax," where brackets contain attribute information. This should not be construed as recommending the syntax to use in a commercial development environment.

The type Attribute

This section's model divides Java classes into "pure," "Java-callable-wrappers," and "Java-callable data wrappers."

The allowable attributes are:

          class [type jcw <options>] foo {...}  // denotes a Java-callable wrapper
          class [type jcdw <options>] foo {...}  // denotes a Java-callable data wrapper

A given class has at most one type attribute. When no type attribute is present for a given class, the type of the class is determined as pure.

The type attribute can appear only in a class that derives directly from java.lang.Object. Interfaces do not have type attributes.

Java-Callable Wrappers

Java-callable wrappers (JCWs) are stateless proxies for a single COM object. JCWs can have an optional CLSID subattribute, which the following example shows.

   [type jcw {CLSID=....}]

Each instance of a JCW has an implicit marshaling mode that is determined using the parameter type attribute through which the JCW is created. The marshaling mode is either "NoMarshal" or "AutoMarshal".

If the marshaling mode is AutoMarshal, the JCW's home thread will be the thread that was current at the time the JCW was bound to the COM object. The JCW can be freely passed to other threads. However, calls to the JCW from outside threads will involve overhead due to marshaling back to the home thread. On a Microsoft® Win32® implementation, the home thread for an AutoMarshal JCW must process window messages on a regular basis. Otherwise, this thread will block other applications that attempt system-wide broadcasts.

If a class identifier (CLSID) is given, JCW classes can be used as the argument to the Java new operator. What happens then depends on the ThreadingModel (determined by the Threading Model registry entry for the CLSID).

If the ThreadingModel is "Free", the COM object is instantiated using the Win32 CoCreateInstance function on the current thread. The JCW can be passed around freely between threads and calls to it are never marshaled.

If the ThreadingModel is "Apartment", the object's home thread is either a special apartment thread or the current thread, depending on certain thread attributes that are outside the scope of this document. The JCW can be passed around freely between threads, but calls to it from outside the apartment thread will cause marshaling overhead.

If the ThreadingModel is "Single", the Microsoft VM switches to the hosting process's main Apartment thread to create the object. This thread is presumed to have a message loop.

Java-Callable Data Wrappers

Java-callable data wrappers (JCDWs) are stateless proxies for external data structures.

The ExposedAs Attribute

The ExposedAs attribute prescribes the external interface of COM-callable wrappers (CCWs) created for a given Java object. More specifically, for a given Java method or field, it describes whether it is exposed as a vtable or Dispatch interface; what IID it is exposed on, what vtable offset or dispid it is assigned to, what name it is exposed as (for Dispatch only) and how the parameters are marshaled.

The following example denotes these.

//pure
class Foo {
    [ExposedAs { VtblLoc  | DispatchLoc } <MethodDesc>]
    void Method1(int whatever)
    {
        DoesSomething;
    }
}

where:

   VtblLoc ::= (IID = iid, VtblOffset = offset)
   DispatchLoc ::= (IID = iid, DispId = dispid, DispType = type,
                    [DispName = name])
   MethodDesc ::= (see later)

Note that a given member can have multiple ExposedAs attributes within the same class (akin to exporting the same function under multiple names from a dynamic-link library (DLL).) In addition, local classes can inherit ExposedAs attributes from superclasses and interface definitions. If a method overrides a method in a superclass, the local method is exposed through all the interfaces listed in the ExposedAs attributes of the overridden method, as well as its own (the overridden method is never exposed by this mechanism; this would violate the notion of overriding).

If two ExposedAs attributes within a class's inheritance tree specify equal vtbllocs or dispatchlocs, it is considered an error.

ExposedAs attributes may appear on interfaces that are named in the "implements" clause of JCW or JCDW classes. However, these attributes have no effect on those classes.

The ProxiesTo Attribute

The ProxiesTo attribute describes, for a given method or field of a Java-callable wrapper (JCW), exactly which Component Object Model (COM) member function it maps to in the underlying COM object.

//JCW
class Foo {
    void Method1(int whatever)
    {
        [ProxiesTo { VtblLoc  | DispatchLoc} <MethodDesc>]
    }
}

Since JCWs cannot subclass each other, there are no overriding or inheritance rules to define for classes. However, Java interfaces can also specify ProxiesTo attributes (this is convenient for standard interfaces). In addition, interfaces that extend other interfaces can also override the ProxiesTo attributes of their parent interfaces (this is what happens when a COM interface definition inherits off another: it has its own IID).

In the case of multiple ProxiesTo attributes, the ambiguity is resolved by the form of the method call used. That is, in the following example:

interface IOleThing {
    [ProxiesTo (IID=IID_A,...]
    void foo();
}

interface IOleThingEx extends IOleThing {
    [ProxiesTo (IID=IID_B,...]
    void foo();
}

class CoOleThing implements IOleThingEx {
    [ProxiesTo (IID_IID_C,...]
    public void foo();
}

If the call to foo is made using invokeinterface on IOleThing, IID_A is used. If the call to foo is made using invokeinterface on IOleThingEx, IID_B is used. If the call is made using invokevirtual, CoOleThing is used.

The MapsTo Attribute

The MapsTo attribute describes how the fields of a Java-callable data wrapper (JCDW) map to offsets in the underlying data structure. These are valid only on the fields of a JCDW class. JCDW classes cannot subclass each other, so there are no inheritance/overriding rules.

//JCDW
class Data {
    [MapsTo ( [AutoOffset], Offset=offset, TypeDesc = typedesc)]
    int x;
}

The TypeDesc structure is described in the next section. If the "AutoOffset" is set, the Offset must be zero and the Virtual Machine will compute the actual offset for the hosting platform. This allows the structure definition to move freely between platforms.

Method and Type Descriptions

The TypeDesc structure defines the type of a single method parameter or return value. TypeDesc structures come in two flavors: one for vtable methods and one for dispatch methods. TypeDesc structures do not attempt to describe the type of the corresponding Java. These attributes are always associated with a method attribute that specifies method signatures.

TypeDesc structures have in/out subattributes to aid in efficient marshaling. Also, if TypeDesc describes a Java-callable wrapper (JCW), you must tag it with a subattribute that indicates the expected marshaling model of the external COM object. JCWs have a "Marshaling Mode," which is one of "NoMarshal" or "AutoMarshal." On a NoMarshal JCW, all calls made from Java to COM are made on the calling thread. On an AutoMarshal JCW, the Microsoft VM marshals all calls back to the thread on which the JCW was created.

Vtable Types

VtblTypes can be one of the following:
void | For return values only: indicates method has no return value
signed(1|2|4|8) | Signed 1, 2, 4, and 8-byte characters
unsigned(1|2|4|8) | Unsigned 1, 2, 4, and 8-byte characters
real(4|8) | Float and double
ptr | A 32-bit linear address
struct(size) | A by-value structure or array
interface(IID) | An IUnknown interface derivative
jstring | Strings
jarray | Arrays

Dispatch Types

Dispatch types are denoted by the VARTYPE enumerations (the subset that is allowable in a VARIANT). In addition, the DispatchType encodes the expected IID for VT_UNKNOWN and VT_DISPATCH.

Method Descriptions

A MethodDesc structure appears in various method-level attributes. This structure is the equivalent of the "Java method signature" for a COM/dispatch type. Either it is an array of VtblTypeDesc structures along with a VtblTypeDesc structure for the return type; or it is an array of DispatchTypeDesc structures along with a DispatchTypeDesc structure.


NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEBSITE Any software that is made available to download from this server ("Software") is the copyrighted work of Microsoft and/or its suppliers. Use of the Software is governed by the terms of the end user license agreement, if any, which accompanies or is included with the Software ("License Agreement"). An end user will be unable to install any Software that is accompanied by or includes a License Agreement, unless he or she first agrees to the License Agreement terms.

The Software is made available for downloading solely for use by end users according to the License Agreement. Any reproduction or redistribution of the Software not in accordance with the License Agreement is expressly prohibited by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE SOFTWARE TO ANY OTHER SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PROHIBITED.

THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT AS WARRANTED IN THE LICENSE AGREEMENT, MICROSOFT CORPORATION HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT.

RESTRICTED RIGHTS LEGEND. Any Software which is downloaded from this Server for or on behalf of the United States of America, its agencies and/or instrumentalities ("U.S. Government"), is provided with Restricted Rights. Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software - Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399.

NOTICE SPECIFIC TO DOCUMENTS AVAILABLE ON THIS WEBSITE

Permission to use Documents (such as white papers, press releases, datasheets and FAQs) from this server ("Server") is granted, provided that (1) the below copyright notice appears in all copies and that both the copyright notice and this permission notice appear, (2) use of such Documents from this Server is for informational and non-commercial or personal use only and will not be copied or posted on any network computer or broadcast in any media, and (3) no modifications of any Documents are made. Use for any other purpose is expressly prohibited by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

Documents specified above do not include the design or layout of the microsoft.com website or any other Microsoft owned, operated, licensed or controlled site. Elements of Microsoft websites are protected by trade dress and other laws and may not be copied or imitated in whole or in part. No logo, graphic, sound or image from any Microsoft website may be copied or retransmitted unless expressly permitted by Microsoft.

MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS SERVER FOR ANY PURPOSE. ALL SUCH DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES

AND CONDITIONS WITH REGARD TO THIS INFORMATION, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THIS SERVER.

THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS SERVER COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME.

NOTICES REGARDING SOFTWARE, DOCUMENTS AND SERVICES AVAILABLE ON THIS WEBSITE.

IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF SOFTWARE, DOCUMENTS, PROVISION OF OR FAILURE TO PROVIDE SERVICES, OR INFORMATION AVAILABLE FROM THIS SERVER.

LINKS TO THIRD PARTY SITES

THE LINKS IN THIS AREA WILL LET YOU LEAVE MICROSOFT'S SITE. THE LINKED SITES ARE NOT UNDER THE CONTROL OF MICROSOFT AND MICROSOFT IS NOT RESPONSIBLE FOR THE CONTENTS OF ANY LINKED SITE OR ANY LINK CONTAINED IN A LINKED SITE, OR ANY CHANGES OR UPDATES TO SUCH SITES. MICROSOFT IS PROVIDING THESE LINKS TO YOU ONLY AS A CONVENIENCE, AND THE INCLUSION OF ANY LINK DOES NOT IMPLY ENDORSEMENT BY MICROSOFT OF THE SITE.

COPYRIGHT NOTICE. Copyright © 1998 Microsoft and/or its suppliers, One Microsoft Way, Redmond, Washington 98052-6399 U.S.A. All rights reserved.

TRADEMARKS. Microsoft, Windows, Windows NT, MSN, The Microsoft Network and/or other Microsoft products referenced herein are either trademarks or registered trademarks of Microsoft. Other product and company names mentioned herein may be the trademarks of their respective owners.

The names of companies, products, people, characters and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product or event, unless otherwise noted.

Any rights not expressly granted herein are reserved.


Implementation Notes

Dynamically allocated memory returned from method calls should be allocated by CoTaskMemAlloc and freed by CoTaskMemFree.


Release Notes Microsoft JDBC-ODBC Bridge

In this topic

* Introduction

* Installation

* Requirements

* Running the JDBC sample

Release Notes | Release Notes
Microsoft JDBC-ODBC Bridge | Introduction

Introduction

The Microsoft JDBC-ODBC bridge is part of the core set of classes that come with the Microsoft VM for Java.

Requirements

In order to use the JDBC/ODBC bridge you need to have the following installed:

  1. ODBC 3.0 or later.
  2. At least 1 ODBC driver for the type of data you need. For example, if you want to get to SQL Server data, you must have the appropriate ODBC SQL Server driver installed.

Running the JDBC sample

To run the JDBC Samples please follow the instructions in the Samples section.


Introduction

The following sections describe the Just-In-Time (JIT) compiler.
Background
JIT Structure
The JIT Compiler/VM Interface


Pseudocode Debugger Initialization Example

Outproc A Priori Debugging (from debugger's point-of-view)

CoCreateInstance(..., &CLSID_RemoteJavaDebugManager, &IID_IRemoteDebugManager, &pdbgmgr, ...)
pdbgmgr->RegisterCallback(MyDebugManagerCallback)
MyCreateProcess("iexplore.exe file:c:\\testpage.html", &dwProcessID, &hthread, CREATE_SUSPENDED)
pdbgmgr->RequestCreateEvent("Test", dwProcessID)
ResumeThread(hthread)