1. Trang chủ
  2. » Công Nghệ Thông Tin

NetBeans the Definitive User Guide phần 5 pps

64 429 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Extending NetBeans
Tác giả Tim Boudreau, Jesse Glick
Người hướng dẫn James Gosling
Trường học O'Reilly & Associates, Inc.
Chuyên ngành Computer Science
Thể loại draft
Năm xuất bản 2001
Thành phố Sebastopol
Định dạng
Số trang 64
Dung lượng 8,78 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

There any number of reasons to develop extensions to NetBeans: Perhaps you are a developer, working on a project that has some unique needs such as deployment to a particular application

Trang 3

Foreword—by James Gosling

1.Introduction

Who Should Read this Book? 249

What’s Different about NetBeans? 250

The Core and the Open APIs 250

TheLicense 251

Open-Source 252

The netbeans.org Web Site 252

NetBeans for Bean Counters 254

Getting and Installing the Open APIs Support Module 255

Life is Change 256

Source code for the examples 256

2 History of NetBeans

HumbleBeginnings 257

First Successes, First Costs 258

Sun Meets NetBeans 259

Open-Source, Fire-Drill Style 260

NetBeansToday 260

3 Understanding the NetBeans APIs

Design Philosophy of NetBeans 261

Abstracting the Abstractions—the Open APIs 262

Modularity 262

Hierarchy, Files and Nodes 263

Everything is a File—Virtually 263

Mapping Files to Java Objects 264

The System Filesystem 265

ModuleLayers 265

Layers in the System Filesystem 266

Exploring the System Filesystem 267

Data Objects—Wrappers for Persistent Data 270

NetBeans and JavaBeans 270

Nodes—the Application as Hierarchy 270

Presenting Nodes to the User—Explorer 271

User-LevelCustomization 273

Nodes in Action—Customizing the IDE without Writing Code 275

Modules—Overview 278

How Modules Add Functionality 278

How Modules Install Virtual Filesystem Layers 279

What Modules Can Do 279

DisablingModules 280

An Illustration—NetBeans with No Modules at All 280

Interacting with the IDE through Internal Execution 281

Setting the Status Bar Text 282

Setting the Current Workspace 283

4 The Open APIs

The IDE’s Architecture and the APIs 284

APIs versus Core versus Modules 285

Service Provider Interfaces and Client APIs 286

Overview of the APIs and Their Purposes 286

Modules 287

Trang 4

Datasystems 299

Explorer 299

Actions 304

Options 305

Compiler 305

Editor 306

WindowingSystem 307

Cookies 309

Execution 310

JavaHierarchy 310

Filesystems 311

Modules, JARs, and Class Loaders 312

Threading, Deadlocks, and How to Avoid Them 317

5 Developing Modules—the New Module Wizard

The HelloWorld Module 319

Creating a Module Using the New Module Wizard 319

The Source Files 320

6 Internals of the Running IDE

The Activated Node(s) 323

Cookies 324

A Peek under the Hood—Examining the Activated Nodes with the CurrentNodeViewer 325

Touring NetBeans with the Bean Browser 325

Data Objects, Nodes and Cookies 327

Filesystems and the Repository 327

Services 328

Lookup 329

Options 330

UIComponents 331

TopComponents, Modes and Workspaces 331

Actions 336

Presenters 337

Custom Property Editors 337

Localization 337

Wizards 338

Jumping-offPlaces 338

Special Folders in the System Filesystem 339

7 Creating the QuickPanel Module

Abstractions Covered in this Chapter 342

Creating the Project Files Drop-Down 343

FilterNode—Filtering Which Children of a Node are Displayed 347

Creating the Methods Drop-Down 349

Improving the Methods Drop-Down 350

Creating the Module 353

Creating a Container GUI Component 354

Creating the ShowQuickPanelAction 354

Creating the XML Filesystem Layer 355

Creating and Populating the Module JAR 356

Building and Testing the Module 356

A Little Homework 357

8 A Mail-Based Filesystem

Building a Mail Reader in the NetBeans Paradigm 358

Implementing MailFileSystem Using AbstractFileSystem and JavaMail 359

Trang 5

Mail Filesystem: AbstractFileSystem.List 361

Mail Filesystem: AbstractFileSystem.Change 362

Mail Filesystem: AbstractFileSystem.Attr 363

Other Parts of AbstractFileSystem 363

Creating Folder Objects for Attachments 366

Using FileSystem.Status Annotations to Mark Unread Messages 367

BeanInfo—Displaying Filesystem Properties 369

Using the Wizard Framework to Set Up Mail Accounts 371

Creating Wizard Classes 371

The IMAP Mail Server Template Wizard 372

9 Creating the User Interface for the Mail Client

Creating a DataLoader for Messages 381

Displaying and Editing Simple Messages and Unnamed Attachments 382

Handling Multipart Messages 386

Creating a Threaded Mail View Using Filter Nodes 387

Making a Basic Mail View 388

Making a Threaded Mail View as an Alternative 394

Creating a Mail Workspace 400

10 Score File Support

Overview—Functionality to be Implemented 406

Creating the Minicomposer Module—First Things 406

Creating the Manifest 406

Creating the Layer 407

Creating a JAR File Using Ant 408

Creating a UniFileLoader and MultiDataObject for *.score Files 408

Creating an Editor Support for Scores 411

Creating a Fixed ExecCookie to Play Scores 414

Creating a Simple Template 417

11 Creating a Structural View of the Score

Creating a ScoreCookie to Represent a Sequence of Notes 419

Examples of State-Based Supports in the NetBeans APIs 420

Creating a ScoreSupport 421

Why a Document is Used 421

Implementation of ScoreSupport 422

Lifecycle of the Score 426

AnOpenSupport 426

Creating an OpenCookie Implementation 427

Showing a GUI View of the ScoreCookie 429

Indicating Parse Errors on the Node 433

12 Compiling Scores

What Does NetBeans Mean by “Compilation”? 437

Creating the Compilers Themselves 437

Creating and Using the Compiler Cookie 441

Displaying an Out-of-Date Badge on Score Icons 445

13 Executing Scores

Execution Service Types—Internal and External 448

Creating the au Player Executor 448

The Internal Player 449

The External Player 451

Registering the Players as Services 454

Creating Player Configuration Support (ExecSupport) 457

Creating a SystemOption for the Default Executor 461

Trang 6

The Clip Length Property 467

Clearing the Cache and Firing Changes 469

Adding the Property to the Property Sheet 470

Representing Notes as Subnodes Using Children.Keys 470

Using Keys to Model Children 471

Being Lazy and Cleaning Up 473

Creating the Subnodes 474

Attaching the Children to the Parent 475

Permitting Subnodes to be Renamed or Deleted 476

Deletion of Notes 476

Renaming of Notes 477

Permitting Subnodes to be Added 479

Making Read/Write Properties on Subnodes 481

ReorderingSubnodes 484

Data Transfer—Cut, Copy, and Paste of Notes and Sequences 489

Overview of the Transferables 490

Cutting and Copying 491

Pasting 492

Drag & Drop 495

Converting Score # Text, Text # Score, Several Scores # One 495

15 Tuning Modules for Performance & Memory Footprint

Startup Performance vs Runtime Performance 501

OperatingPrinciples 501

“Nobody Will Ever Use My Module” 501

What Does My Module Really Need to Do on Startup? 501

What are the Critical Paths? 502

Techniques 503

LazyInitialization 503

Avoid Static Initializers 503

Avoid ModuleInstall Classes—Use XML Layers Instead 504

Partial Loading Considerations—InstanceCookie and InstanceDataObject 505

Use URLs Instead of CDATA Sections in XML Layers 505

Reduce the Number of Classes You Create 505

GUI Components—Wait for addNotify() 505

Using the addNotify() and removeNotify() Pattern Where Exposed by Non-GUI Classes 506

Use Weak and Soft References for Objects which May Not be Needed Forever 506

UseWeakListener 508

Avoid Excessive Event Firing 508

Avoid Overuse of Threads 508

BatchingEvents 509

SwingPerformance 509

16 Producing Modules (Packaging & Distribution)

Versioning 511

Version Numbers and What They Mean 511

SpecifyingDependencies 512

Managing Inter-Module Dependencies 513

Upgrading User Settings 516

Settings History and Physical Format 517

Upgrade Scenarios for Settings 518

What Happens When a Module is Disabled? 520

User Development Data 521

Bundling Extension Libraries 521

Referencing Libraries with Class-Path 522

Trang 7

Internationalization and Accessibility 526

I18N and L10N 526

A11Y 528

JavaHelp—Writing and Distributing 529

Creating a Help Set 529

Adding a Help Set to NetBeans 531

Adding Context Help 534

Separating Help from Code 535

Supporting User-Level Java APIs 535

Supplying a Parser Database 535

BundlingJavadoc 536

Adding to the Default Classpath 537

Templates 538

BeanInstallation 539

Creating the Module JAR File within the IDE 540

Creating a Build Script Using Ant 540

Producing the nbm File 541

Publishing Using the Update Center 543

Using ErrorManager to Log Problems 545

Testing 547

17 Building Your Distribution of NetBeans

Do You Need Your Own Distribution? 549

Licensing 550

Selecting a Baseline 550

Getting the Sources 551

How to Customize the Build Process to Add Your Modules 552

Adding Modules to a “Stock” Distribution 553

Creating Preconfigured Settings 555

Branding 555

Implementing Branding on a Distribution 556

Simple Branding: Text Strings and Images 557

Configuration Branding: Menu Bar, Workspaces, … 558

Advanced Branding: Patching Behavior 564

A A Tour of Existing Modules to Use and Learn From

Modules that Expose Functionality Your Module Might Need 569

The XML Modules 569

TheEditor 570

Version Control—the VCS Core Module 570

RemoteFS 571

The Ant Module 571

The Java Module 571

DebuggerCore 572

J2EEServer 572

FormEditor 572

HTTP Server Module 572

Classfile Reader Module 572

The Metadata Repository—a Whole Host of APIs 572

Socket-Based Editor Support—the External Editor Module 573

Incidental APIs, Utilities and Extensions 573

The Utilities Module 573

API Extensions (openidex) 573

Modules which Make Good Examples for Things You May Need to Implement 574

Trang 8

Adding Information to the View of Java Sources—the Beans Module 574

Adding a Debugger Type—the Applet Module 574

Multiplexing DataObjects, and Complex Cut/Copy/Paste Support—the Properties Module 574

Working with Network Protocols to Access Files—JavaCVS and RemoteFS 574

Domain-Specific XML Support—the Tomcat and Ant Modules 575

Stretching the Limits—the Web Modules 575

Complex Syntax Coloring—the JSP Module 575

Multi-Stage Compilation—the JSP, RMI, and CORBA Modules 575

Bridging to an Entirely Different Build System—the Ant and Makefile Modules 575

Use of the Compiler Infrastructure for Non-Compilation Tasks—the JAR Packager Module 576

Execution—the Applet and JSP/Servlet Modules 576

Custom Hyperlinking in the Output Window—the Ant Module 576

Specifying Windows, Workspaces and Components Using XML—the Core Window System and the Form Editor Module 576

Complex Work with MIMEResolvers and Multi-File DataObjects—the CPP Module 577

Cut/Copy/Paste—Data Transfer Support for Complex Elements—the Ant and Java Modules .577

Interconversion between Different Types of Clipboard Contents—JNDI, CORBA, and RMI 577

Integrating Other Programming Languages—the C++/Fortran, Scripting, and WebL Modules .577

Fancy Footwork with Nodes—the Java Module 578

Adding Nodes to the Runtime Tab in the Explorer—the RMI, CORBA, JNDI, and Database ExplorerModules 578

The Bare Essentials of Non-Data-Driven Nodes—the System Properties Module 578

Wizards—the CORBA, Java and New Module Wizard Modules 578

Embedding Property Panels into Wizards—the Java Module 578

Complex Explorer Views—the Debugger Core Module 578

Enabling/Disabling Sets of Actions based on Context—the VCS Core Module 579

B Useful Utility Classes

XMLUtilities 580

org.openide.xml.XMLUtil 580

org.openide.xml.EntityCatalog 580

Visual Components and Extensions to Standard Swing Components 580

LookupImplementations 581

Threading 581

Miscellaneous Utility Classes in org.openide.util 581

SerializationHelpers 582

C Future Plans

DeclarativeInstantiation 583

UniformLookup 583

DatasystemsII 584

The Looks API 584

DeclarativeActions 585

Deprecation of IDE-Specific Functionality in the Open APIs 585

The Metadata Repository 585

Standards Employed by the MDR 586

ProjectSupport 587

D Working with Open-Source and NetBeans

Practices 589

Governance 589

Consensus 590

How to Get Involved 595

Trang 9

CVS (Concurrent Versioning System) 602

Projects 602

MailingLists 602

Issuezilla 603

Interacting Effectively on Mailing Lists 604

E Additional Modules and Where to Find Them

Open-Source Modules Available via the Update Center 606

The Modules Marketplace on Flashline 606

IDEs that are Distributions of the NetBeans IDE 608

Open-Source Application Projects Based on NetBeans 609

Commercial Applications Built on the NetBeans Platform 609

Commercial Modules Available for NetBeans 610

Should You Create Your Own Update Server? 612

Glossary

Trang 10

3.1 MultiFileSystem merging constituent filesystems 264

3.2 Module adding XML layer to the system filesystem 265

3.3 Structure of the system filesystem 267

3.4 The system filesystem viewed from the Explorer window 268

3.5 Architectural domains underlying nodes 272

3.6 The menu configuration folders in the Options window 274

3.7 The File menu with the Build action added to it 275

3.8 The File menu with a custom executable class added to it 277

4.1 Mapping of files to Java class instances 289

4.2 Mapping from files to InstanceDataObjects to lookup 290

4.3 Anatomy of a node 296

4.4 Explorer views—BeanTreeView 300

4.5 Explorer views—ChoiceView 301

4.6 Explorer views—IconView 301

4.7 Explorer views—ListView 302

4.8 Explorer views—ListView 302

4.9 A “Pseudo-Windows Explorer” mock-up created using IconView and ContextTreeView 302

4.10 Explorer views—TreeTableView 303

4.11 Modes, TopComponents and Nodes—anatomy of the Explorer window 307

4.12 NetBeans class loaders (with three modules installed) 313

6.1 Bean Browser—master view 326

6.2 Bean Browser showing list of registered ServiceTypes 328

6.3 Browsing the live window system in the system filesystem 332

7.1 The FileSelector component 346

7.2 The improved FileSelector component 348

7.3 The final version of the QuickPanel component 356

8.1 Mail filesystem: BeanInfo 370

8.2 Mail filesystem: SelectServerPanel 373

8.3 Mail filesystem: SelectRootFolderPanel 376

8.4 Mail filesystem: IMAP Mail Server template 380

9.1 Mail filesystem: property sheet of a message 385

9.2 Mail filesystem: raw Filesystems view of a mail server 388

9.3 Mail filesystem: Message Servers in the Runtime tab 393

9.4 Mail filesystem: relationships among nodes and objects 397

9.5 Mail filesystem: threaded view 399

9.6 Mail filesystem: mail workspace 404

10.1 Minicomposer: editing a score as text 413

10.2 Minicomposer: using the Musical Score template 418

11.1 UML of the ScoreSupport lifecycle 426

11.2 Minicomposer: two-way editing of score files 432

13.1 Minicomposer: audio players in Options window 456

13.2 Minicomposer: choosing to use an external audio player 458

13.3 Minicomposer: configuring an external audio player 459

13.4 Minicomposer: selecting the audio player process 460

13.5 Minicomposer: settings displayed in Options window 465

14.1 Minicomposer: parent and child nodes with keys 472

14.2 Minicomposer: ScoreChildren lifecycle state diagram 474

14.3 Minicomposer: score file with note subnodes 476

14.4 Minicomposer: unrecognized tone dialog 478

14.5 Minicomposer: in-place rename 478

14.6 Minicomposer: add new note dialog 481

Trang 11

14.9 Minicomposer: Reordering the nodes 487

14.10 Minicomposer: moving a note up 488

14.11 Minicomposer: clipboard with three notes copied 490

14.12 Minicomposer: changing clipboard contents with convertor active 496

16.1 Autoload modules 524

16.2 Minicomposer: JavaHelp start page 531

16.3 Minicomposer: Help Sets submenu 533

16.4 Javadoc automatic (declarative) mounts 537

17.1 Branding: patching the core bundle 558

17.2 Branding: masking a file 561

17.3 Branding a layer with the Open APIs Support module 563

17.4 Showing the system filesystem in the Explorer 564

Trang 12

3.1 Adding a instance to the System Filesystem 264

3.2 Writing to the Status Bar 282

4.1 Sample Module Manifest—the Debugger Core Module 288

4.2 A Simple XML Layer Declaring a Java Instance 289

4.3 Specifying a Static Factory Method for Instances in a Module Layer 291

4.4 Factory Method to Instantiate a Class from a instance File 292

4.5 Specifying the Class that Will Be Created in a Layer 292

4.6 Specifying Initialization Data for a Java Instance Declared in a Layer 292

4.7 Simple Factory Method for an XML Layer Instance 293

4.8 Complex Factory Method for an XML Layer Instance 293

4.9 Declaring File Contents Using URLs in XML Layers 293

4.10 Ordering attributes in XML layers 294

5.1 MyAction.java for Hello World Module 320

5.2 Bundle.properties for Hello World Module 321

5.3 mf-layer.xml for Hello World Module 322

5.4 Manifest for Hello World Module 322

6.1 Locating a SystemOption 330

7.1 QuickPanel: FileSelector.java 344

7.2 QuickPanel: FilesOnlyChildren.java 347

7.3 QuickPanel: MethodSelector.java—Creating a Listener to Monitor the Active TopComponent 349

7.4 QuickPanel: MethodSelector.java—Full Listing TopComponent 351

7.5 QuickPanel: QuickPanel.java 354

7.6 QuickPanel: ShowQuickPanelAction.java 354

7.7 QuickPanel: layer.xml—Creating the QuickPanel Module’s XML Layer 355

7.8 QuickPanel: MANIFEST.MF—the QuickPanel Module’s Manifest 356

8.1 InfoImpl Implementation inside MailFileSystem.java 360

8.2 ListImpl Implementation inside MailFileSystem.java 362

8.3 ChangeImpl Implementation inside MailFileSystem.java 362

8.4 AttrImpl Implementation inside MailFileSystem.java 363

8.5 Mail Filesystem: MailFileSystem Implementation as a Whole 364

8.6 Mail Filesystem: MailFileSystem.java Added Inner Class to Support Status 368

8.7 Mail Filesystem: MailFileSystemBeanInfo.java 369

8.8 Mail Filesystem: SelectServerPanel.java 372

8.9 Mail Filesystem: SelectRootFolderPanel.java (Panel Implementation) 374

8.10 Mail Filesystem: SelectRootFolderPanel.java (MailFolderNode Inner Class) 375

8.11 Mail Filesystem: ConnectionWizardIterator.java 377

8.12 Mail Filesystem: Initial layer.xml 379

8.13 Mail Filesystem: Initial Module JAR Manifest 379

8.14 Mail Filesystem: Initial Bundle.properties 379

8.15 Mail Filesystem: new.xml 380

9.1 Mail Filesystem: Module JAR Manifest Including Data Loaders 381

9.2 Mail Filesystem: MailDataLoader.java 382

9.3 Mail Filesystem: MailDataObject.java 383

9.4 Mail Filesystem: MessageBodyEditorSupport.java 383

9.5 Mail Filesystem: MailDataNode.java 384

9.6 Mail Filesystem: MultipartMessageDataLoader.java 386

9.7 Mail Filesystem: MultipartMessageDataObject.java 387

9.8 Mail Filesystem: MultipartMessageDataNode.java 387

9.9 Mail Filesystem: MessageFileSystemsNode.java 388

9.10 Mail Filesystem: MessageFileSystemsChildren.java 390

9.11 Mail Filesystem: GeneralFolderHierarchyChildren.java 390

Trang 13

9.14 Mail Filesystem: Module JAR Manifest with Node Registration 393

9.15 Mail Filesystem: ViewTypeOption.java 394

9.16 Mail Filesystem: view-type-option.xml 395

9.17 Mail Filesystem: MessageFolderHierarchyChildren Changes for Threaded View 395

9.18 Mail Filesystem: Signature of MessageThread.java 396

9.19 Mail Filesystem: ThreadChildren.java 397

9.20 Mail Filesystem: MessagesExplorer.java 401

9.21 Mail Filesystem: mail.xml 402

9.22 Mail Filesystem: explorer.xml 403

9.23 Mail Filesystem: messages.xml 403

9.24 Mail Filesystem: messages-def.xml 404

10.1 Minicomposer: Initial minicomposer.mf 407

10.2 Minicomposer: Initial src/org/netbeans/examples/modules/minicomposer/Bundle.properties 407

10.3 Minicomposer: Initial src/org/netbeans/examples/modules/minicomposer/layer.xml 407

10.4 Minicomposer: build.xml 408

10.5 Minicomposer: Initial src/org/netbeans/examples/modules/minicomposer/mime-resolver.xml 410

10.6 Minicomposer: Initial src/org/netbeans/examples/modules/minicomposer/ScoreDataLoader.java 410

10.7 Minicomposer: Initial src/org/netbeans/examples/modules/minicomposer/ScoreEditorSupport.java 412

10.8 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreDataObject.java with Editor Sup-port 413

10.9 Minicomposer: Public Signature of src/org/netbeans/examples/modules/minicomposer/Score.java 414

10.10 Minicomposer: Public Signature of src/ org/netbeans/examples/modules/minicomposer/LineInFromScore.java 415

10.11 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreExec.java 416

10.12 Minicomposer: src/org/netbeans/examples/modules/minicomposer/DescForTemplate.html 417

11.1 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreCookie.java 419

11.2 Synopsis of EditorCookie 420

11.3 Synopsis of Selected Methods in SourceElement 421

11.4 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreSupport.java (Text # Structure) 422

11.5 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreOpenSupport.java 427

11.6 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScorePanel.java (Creation and Persis-tence) 429

11.7 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreDataNode.java with Parse Support .433

12.1 Minicomposer: src/org/netbeans/examples/modules/minicomposer/SampledAudioCompiler.java 438

12.2 Minicomposer: src/org/netbeans/examples/modules/minicomposer/SampledAudioCompilerGroup.java 439

12.3 Minicomposer: src/org/netbeans/examples/modules/minicomposer/SampledAudioCleaner.java 440

12.4 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreCompilerSupport.java 442

12.5 Minicomposer: mime-resolver.xml with Compiler Support 445

13.1 Minicomposer: src/org/netbeans/examples/modules/minicomposer/InternalPlayer.java 449

13.2 Minicomposer: src/org/netbeans/examples/modules/minicomposer/InternalPlayerBeanInfo.java 451

13.3 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ExternalPlayer.java 452

13.4 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ExternalPlayerBeanInfo.java 453

13.5 Minicomposer: src/org/netbeans/examples/modules/minicomposer/internal-player.xml 455

13.6 Minicomposer: src/org/netbeans/examples/modules/minicomposer/external-player.xml 456

13.7 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreExecSupport.java 457

13.8 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ComposerSettings.java 461

13.9 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ComposerSettingsBeanInfo.java 463

13.10 Minicomposer: src/org/netbeans/examples/modules/minicomposer/option.xml 465

14.1 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ClipLengthProperty.java 468

14.2 Minicomposer: src/org/netbeans/examples/modules/minicomposer/ScoreChildren.java 471

14.3 Minicomposer: src/org/netbeans/examples/modules/minicomposer/NoteNode.java in Basic Form 474

Trang 14

14.5 Minicomposer: src/org/netbeans/examples/modules/minicomposer/NoteProperty.java 481

16.1 Dependency Specifications in Modules 512

16.2 Providing services to a client 513

16.3 Specifying a required service in a client 513

16.4 The module manifest 522

16.5 The package manifest 522

16.6 I18N: Basic src/org/module/SomeClass.java 526

16.7 I18N: Basic src/org/module/Bundle.properties 526

16.8 I18N: Basic src/org/module/Bundle_cs.properties 527

16.9 I18N: Incorrect src/org/module/SomeClass.java 527

16.10 I18N: Incorrect src/org/module/Bundle.properties 527

16.11 I18N: Revised src/org/module/SomeClass.java 527

16.12 I18N: Revised src/org/module/Bundle.properties 528

16.13 I18N: Revised src/org/module/Bundle_cs.properties 528

16.14 JavaHelp: src/org/netbeans/examples/modules/minicomposer/help-set.xml 529

16.15 JavaHelp: src/org/netbeans/examples/modules/minicomposer/help-map.xml 530

16.16 JavaHelp: src/org/netbeans/examples/modules/minicomposer/help-contents.xml 530

16.17 JavaHelp: src/org/netbeans/examples/modules/minicomposer/help-set-ref.xml 531

16.18 JavaHelp: src/org/netbeans/examples/modules/minicomposer/help-main-page.xml 532

16.19 Bundling Javadoc: javadoc-mount.xml 536

16.20 Adding to the User Classpath: lib-mount.xml 538

16.21 Java Templates: SimpleRenderer.java.template 538

16.22 NBMs: Sample NBM File Contents 541

16.23 NBMs: Sample Info/info.xml 541

16.24 Update Center: Sample Update XML 543

16.25 Update Center: updates.settings 545

17.1 Adding a Module: Sample system/Modules/com-yourcorp-modulename.xml 554

17.2 Branding: …/Layer_macmod.xml with a New File 560

17.3 Branding: …/Bundle_macmod.properties with a New File 560

17.4 Branding: org/netbeans/modules/autoupdate/resources/info-UpdateAction_macmod.html 567

Trang 15

What attracts me to NetBeans is the fact that, contrary to the marketing material, it is not an IDE—not an Integrated

Development Environment It is better described as a DDE—a Disintegrated Development Environment What I mean

is that, at its most basic, NetBeans is just a spine It is a framework that development environment components can beplugged into When you run NetBeans, almost everything you see is a plug-in

One of the problems of the development environment world has been that, traditionally, things have not been done thisway Many people have built specialized tools (for example, finite state thread modeling tools), but they have had ahard time making progress with them Individual tools are only a part of the software production process, so those whomake the tools have often ended up attempting to build a supporting environment, which is a daunting and expensivetask

The key to making any framework successful is having a set of interfaces that define it—contracts between the twosides of the interface so that each side knows what is expected of it, and what it should expect of the other side Thisnotion of building frameworks out of sets of interfaces is central to object-oriented programming and one of the mostimportant patterns in the use of Java

This book defines the framework that is NetBeans It is somewhat daunting, but the technology of development ronments is rich in a certain unavoidable complexity Through this book and the NetBeans platform, you will be able tobuild your own tools to handle whatever specialized problem you may have with software development, and have theresult integrate into the whole development process I know you’ll have fun with it I certainly have!

envi-James Gosling

Trang 16

[1] According to the American Heritage™ Dictionary of the English Language, Fourth Edition, API is also an acronym for Asian and Pacific

Is-lander Readers of this book may safely assume we are referring to Application Programming Interface.

Chapter 1 Introduction

Table of Contents

Who Should Read this Book? 249

What’s Different about NetBeans? 250

The Core and the Open APIs 250

TheLicense 251

Open-Source 252

The netbeans.org Web Site 252

NetBeans for Bean Counters 254

Getting and Installing the Open APIs Support Module 255

Life is Change 256

Source code for the examples 256

Who Should Read this Book?

There any number of reasons to develop extensions to NetBeans: Perhaps you are a developer, working on a project that has some unique needs (such as deployment to a particular application server or use of a code analysis tool), and you use NetBeans and would like to have support for that tool integrated into your development environment Or you could have a development tool that you would like to integrate with NetBeans and sell as an extension

Or you could simply be embarking on a project to create a large desktop application, and you can save several person-years by using the NetBeans core without its development-tool-specific functionality to handle the menus, windowing, file access, configuration and browsing aspects of your application

This half of the book is about writing modules to plug into NetBeans to extend its functionality So it is of particular in-terest to people developing or using tools for software development, people developing desktop applications in Java, or anyone who simply uses the NetBeans IDE and would like to change the way something works We assume you have some familiarity with NetBeans as a development tool and its user interface components and with the Java language The design of NetBeans is also a great example of well-crafted object-oriented architecture Odds are good this book will affect the way you think about how to build software

Extensions to NetBeans are developed by writing Java code to the NetBeans Open APIs API stands for Application Programming Interface[1], and is the common industry term for interfaces a program exposes to allow other programs

or components to interact with it

There is extensive documentation of the NetBeans APIs available in Javadoc and prose format on the NetBeans web site This book should act as a complement to the Open APIs reference documentation, not as a replacement Javadoc is

a very good tool for explaining APIs using their package and class structures as its organizing principle, and the Javadoc set for NetBeans contains excellent prose overviews of each API that cover how to use them But people do not necessarily think in the same structure that a class hierarchy has—generally, they start with a problem to solve With this book we intend to provide a task-oriented guide to using these APIs We hope to leave you with a rich under-standing of how NetBeans works and the philosophy guiding that design

Trang 17

What’s Different about NetBeans?

In the form most of the world knows it, NetBeans is an integrated development environment (IDE) written in Java ing written in Java, it should (and generally does) run on a Java 2 JVM, version 1.3 or higher What makes NetBeansdifferent from other development environments is its flexibility While the first incarnation of it was a tool for Java pro-gramming, over three generations of its architecture, it was redesigned to be a generic tools platform to support devel-opment in any language, not just Java The key is its modular design There is a basic, generic application runtime thatdoes not even know it is an IDE, which is implemented in the NetBeans core Extensions to this framework in the form

Be-of modules are what actually make it an IDE The code editor, the Java language support—almost everything you see

in NetBeans is implemented as a pluggable module

This means that not only can NetBeans be used as a tool for Java development; people can use the NetBeans core withonly their own modules installed to build a desktop application that might have nothing to do with software develop-ment A number of companies and individuals have done this, and the result is (at the time of this writing) four com-mercial IDEs which are NetBeans plus some custom modules (Sun’s Forte for Java, Compuware’s OptimalJ, CompaqNetBeans and Zucotto’s Whiteboard) and applications running the gamut from a CAD tool for designing coal mines(ECSI Minex [http://www.ecsi.com.au/]) to a tool for managing a hair salon (SalonTango), to a music composition andnotation tool (Project XEMO [http://www.xemo.org/]) By the time you read this, there will no doubt be many more.For an up-to-date list, see the netbeans.org third party page [http://www.netbeans.org/about/third-party.html]

Since all of the IDE-like behavior of NetBeans is implemented in the form of plug-in modules, you can use the Beans core to handle a lot of the grunt work involved in writing a desktop application Most applications need access tofiles, need to provide menus and toolbars and windows and store settings Having the implementation of these thingshandled for you solidly by the NetBeans core can save a lot of development time and effort NetBeans is to the desktopmuch as an application server is to a server computer—where an application server provides an execution context forarbitrary Enterprise Java Beans, NetBeans provides an execution context for arbitrary modules Both frameworks aredesigned to handle commonly needed tasks so you can concentrate on the actual logic

Net-The Core and the Open APIs

The architecture of NetBeans breaks down into two major sections: The core (also referred to as the application time) and the Open APIs The core plus the Open APIs makes up the NetBeans Platform These are represented in the

run-org.netbeans.core.*andorg.openide.*Java packages, respectively, in the source code for NetBeans nary libraries of these packages are part of your installation of NetBeans in the files$NB_HOME/lib/core.jarand

Bi-$NB_HOME/lib/openide.jar The core implements many interfaces defined in the Open APIs and is NetBeans’runtime engine The Open APIs are the toolset available to module authors who want to write modules to implementfunctionality that will run inside of NetBeans A module is a jar(Java ARchive or JAR) file which contains the

module’s Java classes and a manifest file which describes the module, and how to install and uninstall it, to NetBeans’runtime

As for any application, for an IDE such an architecture has a number of advantages First and foremost is the ability tosupport multiple languages Another significant advantage is the ability to wrap the functionality of other developmenttools and present it within the IDE The simplest example of this kind of wrapping is the way external compilers andJava virtual machines can be used for compilation and execution by defining services which launch an external processand parse and present the output of that process (e.g compiler error messages) A more complex example would be theintegration of a pre-existing UML tool to allow seamless interaction with it through NetBeans’ user interface

A number of the elements of NetBeans, such as the Filesystems, Nodes and Explorer APIs, can also be used as

stan-dalone libraries for client- and server-side Java applications outside of NetBeans In a sense, NetBeans is a set of

li-braries [2]

Trang 18

[2] As this book is being written and NetBeans 3.4 is in development, one of the thrusts of that work is to decompose the core into smaller, dent libraries implementing specific APIs This work will further enable applications to use and distribute only that functionality which they need.

indepen-A caveat to this type of design is that no module should call functionality that does not appear in the Open indepen-APIs: for ample, getting an object with an interface declared in the Open APIs and then casting to a core implementation class toaccess some method that isn’t defined in the APIs The contract of an API is to provide access to functionality that willcontinue to work even if the underlying implementation is replaced This means that there is no guarantee that anythingnot declared in the Open APIs documentation will be present in future versions of the IDE, and any code using the coreimplementation classes directly is liable to be break in some future version of NetBeans If there is something you need

ex-to do that is inconvenient or not possible with the APIs, ask on the NetBeans mailing lists[http://www.netbeans.org/about/community/lists.html] if there is a different approach you should take, or if there is not,file an enhancement request in the bug tracking tool [http://www.netbeans.org/issues/query.cgi] on the netbeans.orgweb site

The License

Licensing of software and source code determines what other people can and cannot do with that software The sourcecode to NetBeans is available under a license called the Sun Public License, which is very non-restrictive Basicallywhat this allows you to do is:

License compatibility

There are a lot of religious arguments about software licenses, and this book is not going to take a position with regard

to them There are cases where software licenses are “encumbered”—a license places certain obligations on the author

of any code using that license, the users of code written under that license, and in some cases, anyone who distributescode under more than one license as a single product There are situations in which the licenses of two products, if dis-tributed together, place contradictory demands on either the author or the user These are termed incompatible licenses.The GNU General Public License (GPL) is one such case—it requires that people distributing software under other li-censes along with GPL software apply the the GNU license to all software that is packaged with it (requiring them togive away the source code) There is a possibility of something called “dual licensing” which allows users and vendors

to choose which license applies where, but this also lands in completely uncharted legal waters

Because the GPL (requiring all source code to be “free”) and the license NetBeans is under (which allows you to giveaway what you want and sell what you want) are not compatible, it is the requirement of Sun Microsystems’ lawyersthat incompatibly licensed software not be hosted on netbeans.org Since Sun foots the bill for the site, this legal advice

is taken seriously

If you decide to contribute a module to netbeans.org, the way to do this is simply to use the same license[http://www.netbeans.org/about/os/license.html] as the rest of the NetBeans sources, as detailed in the section called

“The License”

Please bear in mind that the authors of this book are not lawyers, and none of the licensing-related text in this book

should be construed as legal advice If you are writing software and have questions as to how to license it, consult ified legal counsel

qual-• Use NetBeans to create commercial or non-commercial software

• Build modules that integrate with NetBeans and sell them or give them away

• Redistribute NetBeans either for free or for sale, with your own branding, custom configuration, with additionalmodules you supply, and removing any modules you don’t want in your distribution

• Use parts of NetBeans code (e.g., the Filesystems library, or the core) in your own applications, commercial or

Trang 19

The Sun Public License (SPL) is a minor variant of the Mozilla Public License (MPL), the license Netscape created

when it released the sources to its web browser The only significant differences are that the word Netscape is replaced

by Sun Microsystems and the license covers open-sourcing the documentation as well, which Netscape did not

explic-itly do For the full details (including a diff with the MPL) see http://www.netbeans.org/about/os/license.html[http://www.netbeans.org/about/os/license.html]

Open-Source

NetBeans is an open-source project hosted at http://www.netbeans.org/ [http://www.netbeans.org/] What this means isthat the source code for the entire IDE is available for download A principle of open-source is open communication,and design discussions happen on the public mailing lists at netbeans.org The site is divided into various subprojectsites (e.g http://editor.netbeans.org/ [http://editor.netbeans.org/]) for the various modules that are part of NetBeans De-cisions are reached by consensus on the mailing lists (see the section called “The mechanics of consensus” for an ex-planation of how this works in practice); there is a governance board consisting of two members chosen by the commu-nity on the mailing lists, and one appointed by Sun Microsystems (which donated the code that started the project, em-ploys many of the developers of NetBeans, and financially supports the site’s infrastructure) In the event of an in-tractable dispute, the board exists to make decisions In practice, issues of such magnitude are extremely rare

It being an open-source project, you can also get involved in the ongoing development of NetBeans Code tions, patches and bug fixes are always welcome To learn more about getting involved in the NetBeans project, see thecontributions index [http://www.netbeans.org/devhome/community/contribute.html]

contribu-If you write a module for NetBeans that you do not intend to sell, but which would be generally useful to the nity at large, you have the option of contributing that module to netbeans.org Please do! Assuming a compatible li-cense (see License compatibility), the sources can be hosted in CVS, mailing lists set up for discussing the ongoingmaintenance of that code and bug categories for your module created If you want to do this, send a proposal to the

commu-<nbdev@netbeans.org>mailing list about your module, and assuming the consensus is that your module would

be a good addition to the NetBeans project, follow the contribution instructions on the web site See the section called

“The Lifecycle of Module Development” for details

Note that contributing a module involves an ongoing commitment to maintain it— it is never a good idea to contribute

a module as a way of abandoning it

The netbeans.org Web Site

The main pages of the NetBeans web site can be found at http://www.netbeans.org/ [http://www.netbeans.org/] and clude overviews of NetBeans, news from the various subprojects on the site, documentation, bug tracking and indexes

in-to interesting documents from subprojects, such as new feature proposals, how-in-to’s and FAQs

The site is hosted using an open-source infrastructure called SourceCast, and is hosted by a company called CollabNet,under contract to Sun Microsystems As mentioned, NetBeans is modular—there are a lot of subprojects that are part ofNetBeans, and if they were all hosted on the top-level web site, the number of documents would quickly become un-manageable Instead, a module or set of modules has its own web pages on a virtual host—a virtual web site with a dif-ferent name, e.g., http://editor.netbeans.org/ [http://editor.netbeans.org/] for the pages relating to the code editor Eachmodule project may have its own mailing lists for development discussion, user questions and such Not all do—it is atthe discretion of the maintainers of that particular project whether their project needs its own mailing lists Mostprojects are small enough that discussion should simply happen on the top-level user and development mailing lists.There is a convention for posting messages of interest only to developers of a single module or topic of interest to a mi-nority of members of a mailing list: Put the topic in square brackets, e.g.[performance] Caught exceptions

Trang 20

on startup.

There are also several “meta-projects” which are not really modules in their own right, but exist as jumping-off pointsfor related modules which have their own virtual hosts An example of this is das.netbeans.org[http://das.netbeans.org/]; DAS stands for “Distributed Application Support— the project is mainly a homepage for get-ting to modules such as CORBA and RMI support These meta-projects serve to group related modules and keep theinitial list of projects that a visitor to the site is confronted with from being intimidatingly large

Additionally, there are a number of sub-projects which are not specifically coding-related, such as the qa.netbeans.org[http://qa.netbeans.org/] quality assurance sub-site, which has graphs of the bug counts of recent builds over time, andother useful resources Another interesting site of this type is ui.netbeans.org [http://ui.netbeans.org/], maintained bySun’s team of human interface engineers who work to ensure that the user interface to NetBeans is usable and consis-tent, and do work such as icon and interaction design

ac-Bug tracking

Bugs are tracked using Issuezilla, an enhanced version of the Mozilla project’s bug tracking tool Bugzilla Issuezillalacks some bells and whistles, and has a somewhat intimidating query interface, but is generally usable Eventually,CollabNet plans to replace it with a new system, but the timetable for this is still undetermined at the time of this writ-ing Items in Issuezilla are categorized as defects, enhancement requests or tasks

There is a simple query interface available at http://www.netbeans.org/devhome/issues.html[http://www.netbeans.org/devhome/issues.html] Anyone can anonymously query the bug database; to enter new items

in Issuezilla, you will need to register and get a login ID

Ways to participate

Open-source is not just about writing code! There are a huge number of ways to participate in an open-source nity—the simplest is to download a copy of the software and join a mailing list Open-source is about people buildingsoftware more efficiently by everyone benefiting from each other’s expertise Filing enhancement requests and bug re-ports, and asking and answering questions on mailing lists are as important forms of participation as writing code Inparallel with reading this book, we encourage you to subscribe to the <nbdev@netbeans.org>,

commu-<dev@openide.netbeans.org>or<nbusers@netbeans.org>mailing lists and get a sense for yourself ofwhat the NetBeans community is like See the NetBeans Mailing Lists[http://www.netbeans.org/devhome/community/mail-top.html] page to sign up

The netbeans.org FAQs and mailing lists

The mailing lists on netbeans.org are particularly useful supplements to the contents of this book Many subprojectshave their own development mailing lists for discussion of development on that particular project (e.g

<dev@editor.netbeans.org>)

Trang 21

Another useful resource to supplement this book is the <dev@openide.netbeans.org> mailing list Theopenide.netbeans.org [http://openide.netbeans.org/] project is where the ongoing evolution of the Open APIs happens,and if you have questions about how to do something or the usage of a particular part of the Open APIs that you cannotfind the answer to, the APIs documentation or this book, that is the place to ask As with any mailing list of this type,please check the Frequently Asked Question (FAQ) pages at http://www.netbeans.org/devhome/docs/index.html[http://www.netbeans.org/devhome/docs/index.html]! You may well find the answer to your question there.

You can also read and post to the netbeans.org mailing lists via a newsreader, by connecting tonews://news.netbeans.org [news://news.netbeans.org] Note that posts from unregistered email addresses are moder-ated—they need to be approved by someone, so there may be a delay before your first post appears if you post via anewsreader or using an email address in the From: field of your email other than the one you registered with An in-creasing amount of “spam” mail is sent to the netbeans.org mailing lists daily—moderators make sure this unwantedemail does not end up cluttering the mailboxes of everyone on the mailing lists, hence the need for this protectionmechanism

Being on Topic

Mailing lists exist to cover specific areas of NetBeans design and use, and it’s helpful to know which list is for what.The value of a mailing list to its participants is proportional to the amount the conversation stays on topic Here is abreakdown of the major top-level netbeans.org mailing lists:

• <nbusers@netbeans.org>—The main user community mailing list, for questions about using NetBeans, cussion of problems, etc

dis-• <nbdev@netbeans.org>—Development of NetBeans, both modules (those that don’t have their own oper lists) and the core

devel-• <dev@openide.netbeans.org>—Usage and ongoing evolution of the Open APIs If you have a questionabout something in the APIs that you can’t find an answer to, this is the place

• <nbdiscuss@netbeans.org>—Discussion of non-code aspects of the NetBeans project (the web site, nance, etc.)

gover-• <nbannounce@netbeans.org>—A fully moderated (all posts must be approved by a moderator) list for Beans project announcements

Net-• <nbjobs@netbeans.org>—A fully moderated list for companies that want to hire people with NetBeans

ex-pertise to post job listings on, and for people with NetBeans exex-pertise to post resumes Note that this is not a

gen-eral jobs list! If a resume or a job listing has nothing to do with NetBeans, it will not be approved to the list.Another useful resource is the NetBeans weekly newsletter, which is run by volunteers and mailed every Monday to the

<nbannounce@netbeans.org> mailing list It contains summaries of what’s happened with NetBeans for thepast week, any new contributions and links to web archives of interesting conversations from the public mailing lists.For a listing of the top-level mailing lists, and a form to allow you to subscribe to them, go tohttp://www.netbeans.org/devhome/community/lists.html [http://www.netbeans.org/devhome/community/lists.html] Tosubscribe to individual project mailing lists, follow the links from the home pages of the projects you are interested in

As with any set of community mailing lists, it pays to lurk a little while before posting, to get a feel for the communityand a sense of what subjects are appropriate to each mailing list

NetBeans for Bean Counters

Trang 22

At the time of this writing (May 2002), the NetBeans open-source project has been running for two years Here aresome interesting statistics about it:

• The oldest code in the codebase is from 1997, from NetBeans 2.0

• The codebase is currently around 800,000 lines of code

• There have been 386,300 downloads of NetBeans

• There have been over a million downloads of Sun Microsystems’ distribution of NetBeans, Forte™ for Java

• The average number of messages on all the top-level mailing lists combined is around 2000 messages per-month

• The combined subscribership count of all top-level mailing lists is about 2000

Getting and Installing the Open APIs Support Module

Not only are there tools to make general Java coding easier within NetBeans—there is also a module that provides asubstantial amount of help with building extensions to the IDE This is the Open APIs Support module It includes:

• Templates for various kinds of objects commonly subclassed in writing extensions, with helpful comments and amples

ex-• The NetBeans Open APIs Javadoc and prose reference documentation, installed in the IDE’s Javadoc repository, sothe documentation can be viewed and searched from within the IDE

• Execution services for commonly used interface components—so instead of having to install a component you’recreating into the IDE, you can simply execute the component class

• The Bean Browser, which is rather like the traditional explorer tree, but allows you to browse objects within the ternal hierarchy of objects in the IDE which are not normally exposed by the user interface

in-• Support for dynamically reloading modules for testing purposes—it would be awful to have to restart the IDE totest each revision to one’s code

• Structural editing of XML layers (a configuration file most modules use) and graphical access to components andattributes of modules under development in the Explorer tree

You will need the Open APIs Support module to do many of the examples in this book To get the module:

Getting the Open APIs Support module using the Update Center

Trang 23

[3] If you are behind a SOCKS firewall, you will need to pass the proxy information to the JVM the IDE is running in You need to do this when you start the IDE, e.g.runide.sh -J-DsocksProxyPort=1080 -J-DsocksProxyHost=socksproxy.foo.com Note that even if you are behind a SOCKS firewall, you should still be able to use a simple HTTP proxy if one is available—so this is seldom neces- sary If you will need to use a SOCKS proxy every time you run NetBeans, create or edit the file called ide.cfg in$NB_HOME/binto con- tain the above line switches.

For more information see the module’s web page [http://apisupport.netbeans.org/]

Life is Change

No piece of software is ever “finished,” and this is certainly true of NetBeans We began writing the book at the ning of the NetBeans 3.2 release cycle; as this paragraph is being written, 3.3.2 is released, 3.4 is almost ready, and 4.0looms on the horizon There are ways to do things in NetBeans today that simplify things compared with the previousrelease, and there are ways of doing things that were recommended for 3.2 that are now deprecated (but except if noted

begin-in the upgrade guide bundled with the Open APIs documentation, still function) This will be true of future releases aswell Where possible in this book, we project what changes are expected with 3.4 and further This book primarily cov-ers NetBeans 3.3.x, though major changes in NetBeans 3.4 are noted where appropriate

This shouldn’t be cause for alarm—great effort is put into making NetBeans backward compatible What it does mean

is that since technical books, particularly about software, are quickly obsolete, it is worth checking the upgrade guidesfor module authors for versions subsequent to 3.3, and the published errata for this book For details on the pendingchanges known at this time, and the general direction in which the NetBeans APIs are evolving, see Appendix C

Source code for the examples

As noted in the section called “Contents of the Accompanying Sources”, both sources and compiled module.nbmfilesfor the examples in this book can be found at somewhere [somewhere]

Trang 24

Chapter 2 History of NetBeans

Table of Contents

HumbleBeginnings 257First Successes, First Costs 258Sun Meets NetBeans 259Open-Source, Fire-Drill Style 260NetBeansToday 260

The story behind NetBeans is an interesting one—as with any piece of software, story or work of art, it did not springfully formed from the forehead of anyone, but is tied up with the dreams, sweat and hard work of a number of people

If you are anxious to get started coding for NetBeans, you can skip this chapter—but we encourage you to come backand learn the human story behind the software you will read about in this book

Humble Beginnings

In the fall of 1996, two Czech students were walking down a stairway at Charles University in Prague, one of themnamed Jan (Ian) Formánek, when they encountered a group of fellow students in an argument They were arguing aboutthe subject of their student project—it is a common practice in the Czech Republic for a group of computer science stu-dents to do a year- to year-and-a-half-long project that gives them the experience of teamwork and creating somethingworthwhile This school had a stock list of projects, such as building and programming a robot But these studentsweren’t satisfied with any of them They brought this up to their professor—they wanted to design their own project.But what would it be? That was the subject of the argument

When the dust cleared, they had settled on the ambitious task of building a visual C++ development tool along the lines

of Borland Delphi for the X Window System, and named the project Xelfi Over the next few months they set about signing an architecture, and trying to solve the issues of writing code portable enough that it would be usable on a widevariety of systems

de-Six months into the project, the group was faced with a crisis: They needed a stable, mature, free component library for

X, and after experimenting with many different component libraries, they could find none that would do the trick One

of the students, Jaroslav (Yarda) Tulach, a mathematics major, had discovered Java while working on a side project.Yarda suggested they shift the project to build a visual IDE for Java “Good joke” was the response of the group After

a month, they were still at a loss to find a component library when Ian brought the Java idea up again This time, perate, they agreed

des-There was no reflection API in Java des-There was no easy way to have an IDE manipulate Java components at time Bear in mind that we’re talking about Java 1.0.2 So this group of students took on the ambitious task of writingtheir own visual component library, based on AWT, and building an IDE for it In March of 1997, they named that li-brary OpenJCOM, defended the Xelfi project, and, successful, graduated

design-But some of the members of the project wanted to continue working on it Not only was Xelfi the first IDE for Java, itwas the first IDE written in Java The project was fun, they were freshly out of school, and it might have commercialpotential The group formed a company under Ian’s name called Xelfi Technologies They arranged a deal with a bankfor credit card processing (not an easy thing to do in the Czech Republic of 1997), and began selling Xelfi as shareware

on the web for $20 per license, at http://www.xelfi.cz/, which was hosted on a web server owned by Yarda’s cousin’s

Trang 25

firm To their astonishment, the software made quite a splash—featured on the Gamelan web site, it attracted enormousnumbers of downloads from all over the world The name of one of the downloaders was Roman Stan#k, a Czech en-trepreneur He sent them an email asking to meet and discuss business options.

It was the summer of 1997, the internet bubble that would burst in 2001 had just begun to inflate, and Roman had cided he needed a new project He stumbled across Xelfi on the internet He had begun his career in mainframe pro-gramming, later directed Sybase’s eastern European operations, and subsequently had started a successful PowerSoftdistributor which he had just sold to PowerSoft Xelfi was interesting, new, and it had been a tremendous surprise todiscover its authors were right across town, in Prague Since Ian and Yarda were competing for leadership of the Xelfiproject, they compromised on meeting with Roman together

de-It was a warm June evening when Ian and Yarda, fresh out of college and flush with the success of their new enterprise,clambered up the steps of the Dejvická metro station and met Roman in the lobby of the Hotel Diplomat They emergedwith an agreement, and a surprising one: They would scrap Xelfi—by this time, the reflection API had been added toJava by Sun There was a now both a standard component architecture for Java and a way for an IDE to communicatewith it at design-time that could be used directly by an IDE Xelfi would need to be rewritten from the ground up orrisk irrelevance They would form a new company, an American-style internet startup The purpose of that companywould be to create an IDE and an internet-enabled component framework resembling the Java Beans specification.Yarda coined the name NetBeans, and the company had its name The founders were Roman, Ian, Yarda and HelenaStolka, brought in by Roman to handle marketing

The shape of NetBeans today is very much a product of the tension between its two founders, Ian and Yarda—Ian,quiet, reserved and piercingly intelligent, prioritizing usability and professionalism, and Yarda, outgoing, brilliant andjoyously outrageous, the abstract mathematics maven and architectural purist valuing a scalable, beautiful underlyingarchitecture over aesthetics It is hard to imagine a more perfect combination, or a more difficult one! What you seewhen you run NetBeans is, along with the contribution of the many talented people who have worked on the code, theproduct of that creative tension

First Successes, First Costs

In the fall of 1998, NetBeans released its first product, NetBeans Developer 2.0 By this time there were other JavaIDEs on the market, but NetBeans attracted a loyal following, favorable press, and particularly a good deal of interestfrom the people in Sun Microsystems’ JavaSoft division Sun had its own Java IDE, Java Workshop, but the projecthad been plagued with shifting goals and design problems and was less than a wild success

The plan the founders had was still to build a network-enabled framework along the lines of the Java Beans tion once the first version of the IDE was released when, as with Xelfi’s component library, the specification for Enter-prise Java Beans was released and began to get broad industry and media attention The JDK 1.2 and Swing had alsobeen released, and the development environment would need to address these technologies as well An interim releasecalled Developer X2 was planned and shipped early in 1999, supporting Swing with its newjavax.swingpackag-ing, as planning for 3.0 began

specifica-The recurring theme in the history of NetBeans is one of adaptation—the Java reflection API forcing the abandonment

of OpenJCOM, and, with Developer 3.0, scotching the plans for their own “net beans” and adopting Enterprise JavaBeans (the beta of NetBeans Developer 3.0 in the summer of 1999 was the first IDE on the market to support EJBs).Take any engineer and show them a specification and they will probably tell you how they could write a better one—it

is to the real credit of the developers of NetBeans that they had the discipline to take the long view and use the able standards rather than reinvent the wheel

avail-But there was another crisis brewing—the architecture of the IDE itself Clearly the direction they needed to go was for

it to become as generic as possible, so that new developments in technology would not continually obsolete the existingdesign Yarda and others had floated the notion of an extremely abstract, modular design But this looked far too daunt-

Trang 26

ing and time-consuming for 2.0 As planning for 3.0 began, two things were clear: The developers could not know whatnew technologies they would need to integrate into the IDE, and as the team developed NetBeans using NetBeans,there were many technologies, such as version control, that would be nice to integrate with the IDE A generic architec-ture such as NetBeans now has was the safest bet for building an IDE that could stay relevant in an uncertain future.Further, if they published the APIs, they could attract vendors to write extensions and produce their own modules thatwould enhance NetBeans Developer Not only that, but there was talk of even making the basic framework of the IDEopen-source, and making the modules that added value the thing that was sold To do this meant a lot of re-engineering,but it would prove worth it Roman had worked with a development tool many years before which had followed thismodel, and liked the idea as well The concept of a “tools platform” was born.

As Ian puts it, “Xelfi had poor architecture and poor functionality—the best thing we did was to throw it out With 2.0,

we had good functionality but the architecture was still poor—but we had spent those three years running into lems, solving them and learning to do architecture With 3.0 we threw out about half of the code from 2.0, and finally

prob-we had both.”

Sun Meets NetBeans

But another thing was happening in the summer of 1999, in Menlo Park, California Sun had recognized that its owntool, Java Workshop, had neither succeeded in the marketplace, nor kept up with the evolution of the Java language Aneleven year Sun veteran engineer, Evan Adams, had been brought on board to kill the Java Workshop project Yet itwas clear that Sun needed to make sure there were good Java tools available that served the Java language, not a partic-ular vendor’s agenda Sun operates rather obsessively on the principle that, while in the short term, owning a propri-etary framework can bring in fast cash, for the future of the business, open standards are what get you longevity Suncreated the Java language, and since tools are a principle way to spread new technologies and maintain market leader-ship, both Java and development tools are critical to Sun A number of companies were considered for this acquisition,but the one the engineers kept coming back to was NetBeans

At this point, NetBeans was on its second set of offices—the third floor of an airplane parts factory in the grubbyneighborhood of Palmovka, and had grown to thirty employees While the neighborhood was not so beautiful, the Net-Beans office was a fun place to work—Karel Zatloukal, the system administrator for NetBeans, turned down a betterjob offer to work there when he learned they had a ping-pong table! There was an easy camaraderie, and employeescould often be found together after hours at the pub around the corner, Jaguška, with its unique and legendary service

(patron orders cola Server brings soda water Patron: “But I ordered cola!” Server: “Yes, but I brought you soda.”

Server turns and leaves) But not only this—in a country laboring out from under the “we pretend to work; they pretend

to pay us” legacy of communism, you could find the lights on and the office full at 8PM These were not just leagues, but friends, working on a project they both loved and believed in

col-Rumors flew about the office when Roman called to say that he was staying for an extra week after Sun’s JavaOne ference for mysterious meetings Something was happening, but few knew what It was on a bright morning in earlyAugust when Roman called an unexpected meeting about the 3.0 beta in the ping-pong room “The beta probably won’thappen But we are being acquired by Sun Microsystems.”

con-If this was not success, there is no defining success! To have the maker of Java itself validate your work by throwingout its competing product and buying yours! Yet acquisitions are a complex, difficult and sometimes painful business,and there was much work to be done, and as yet nobody knew exactly what all of this would mean

In October of 1999, Sun did officially acquire NetBeans—and a month later another tools company in Oakland, fornia, called Forté The beta of NetBeans Developer 3.0 would be renamed “Forte for Java,” and the Forté team inOakland would write modules for enterprise technologies such as EJBs to plug into it The integration of these compa-nies would take some time, and so the beta program was continued while things were sorted out

Trang 27

Cali-Open-Source, Fire-Drill Style

But in the spring of 2000, another event would further change the lives of the NetBeans team Open-source had beendiscussed as an option on and off for some time—it has its proponents and opponents within Sun Microsystems AtLinuxWorld that spring, Pat Sueltz, head of software at Sun, decided to announce that, by the time of JavaOne, only 90days away, Sun would open-source the NetBeans codebase The commercial technology support modules, such as EJBand JSP support would remain closed, but the rest of the IDE would be given away But this was going to be a fire drill!Not only were there 90 days to build a web site, move to a new bug tracking and version control system, but the launchdate coincided with the day Sun was moving the NetBeans team into a new office building, near the Hotel Diplomatwhere NetBeans-the-company had been born

Evan Adams, the engineer who had been brought in to kill Java Workshop, had meanwhile transferred to Prague to sist in bringing the team into the Sun fold, and he was chosen to put together a small team to do the necessary work tobuild the site and get it up and running on time That team included the NetBeans webmaster, Jack Catchpoole, and theauthors The first decision was that the open-source project should be called NetBeans

as-A lot of work goes into open sourcing software—there is a due diligence process that must be done to make sure thatyou actually own all of the code that is being open-sourced, and migrating between version control and bug trackingsystems can be nightmarish It can be especially nightmarish when done on a tight schedule including a massive pack-age rename, while normal development attempts to continue in parallel!

And it involves a change in development style—to reap the benefits of open-source, you really do have to have yourdesign discussions on public mailing lists, and walk the talk It was a paradigm shift—it took some discipline, when anengineer had an idea and wanted to discuss it, for their colleagues to say “Good You have an idea Send a proposal tothe mailing list and we’ll discuss it there” when they could just as easily go over to a whiteboard But to look at the ac-tivity on the NetBeans mailing lists, and the success that the NetBeans open-source project has had, clearly it wasworth it

Through heroic efforts on the part of the entire team in the Palmovka office, and with a great deal of help from Net, the company contracted to host the site and provide the server-side infrastructure, we successfully launched net-beans.org in early June of 2000

Collab-NetBeans Today

The team that built NetBeans, including Ian and Yarda, are still in Prague, working for Sun on NetBeans—while a fewmembers of the original team have moved on, almost everybody who built this tool can be found on the NetBeans mail-ing lists, working on a project they love, and which for some may be their life’s work The difference now is the manyothers involved in the project, joining the work that happens on netbeans.org and making their unique contribution tothe project What could be better than to both create something wonderful and be able to share it with the world? Theteam that created NetBeans deserves tremendous credit for creating something that has made such an impact—but itwould be meaningless without those who use and contribute to that work, from all over the world While Sun may paythe bills for the NetBeans project, it has a life all its own

Trang 28

Chapter 3 Understanding the NetBeans APIs

Table of Contents

Design Philosophy of NetBeans 261

Abstracting the Abstractions—the Open APIs 262Modularity 262Hierarchy, Files and Nodes 263Everything is a File—Virtually 263Mapping Files to Java Objects 264The System Filesystem 265ModuleLayers 265Layers in the System Filesystem 266Exploring the System Filesystem 267Data Objects—Wrappers for Persistent Data 270NetBeans and JavaBeans 270Nodes—the Application as Hierarchy 270Presenting Nodes to the User—Explorer 271User-LevelCustomization 273

Nodes in Action—Customizing the IDE without Writing Code 275Modules—Overview 278

How Modules Add Functionality 278How Modules Install Virtual Filesystem Layers 279What Modules Can Do 279DisablingModules 280

An Illustration—NetBeans with No Modules at All 280Interacting with the IDE through Internal Execution 281

Setting the Status Bar Text 282Setting the Current Workspace 283

Design Philosophy of NetBeans

You would think that, writing an IDE, the first priority would be an editor—this is a thing that edits files, right? Andthen you write code for compilation, execution, etc and you’ve got an IDE This is a fine design for a small applica-tion But what happens when you want to, say, integrate source code management with the tool? You find you have torewrite a lot of your file access code What about integrating access to databases? You’ll need some way to make con-nections, browse databases, etc And interestingly, you’ll find a lot of the user-interface code you’re writing for that(select an object representing the database, get some information from it, present it), looks an awful lot like the codeyou’re writing for browsing files…which looks like the code for managing user settings, and so forth Your codebase isgrowing rapidly (and getting less maintainable in the process), and a lot of it is code to do very similar things

The team that created NetBeans went through this, as NetBeans 2.0 evolved, and the current architecture from the sign of 2.0 The good news is that if you are building an application on top of the NetBeans core, you get to benefitfrom their experience, and start writing your application with all the problems they encountered (lots!) already solvedfor you

de-NetBeans solves problems like this through very heavy use of abstractions For example, when you interact with a file,you will be using aFileObject, not an instance ofjava.io.File When you deal with menu items and toolbar

Trang 29

[4] Itself an extension to the Swing actions API

buttons, you will be developing subclasses oforg.openide.util.actions.SystemAction[4] , not directlyinteracting with menus and toolbars (though you can create custom components to use if you need them) Our presenta-tion problem above is solved through an abstraction called nodes, which will be explained in more detail later In gen-eral, the NetBeans platform provides high-level abstractions to handle the common cases found in development, whileallowing the flexibility to do something more low-level if the need arises

There will be times when you may wonder why things are done the way they are One of the goals of this part of thebook is to get you comfortable with the abstractions exposed by the Open APIs and how to use them—to get you think-ing in terms of these abstractions, and ideally, using the patterns you encounter in NetBeans to create abstractions thatsolve problems of your own

Abstracting the Abstractions—the Open APIs

The Open APIs are the set of interfaces, defined in the packageorg.openideand its subpackages, and the tions (such as for manifest files and XML layers) specified in the Open APIs Javadoc documentation The Open APIsdefine how modules interface with NetBeans The Javadoc (and the prose documentation that accompanies it) is thecanonical documentation of the Open APIs The NetBeans APIs can be broken down into a number of sections based

specifica-on the roles they play, such as:

Filesystems—Communication with persistent data storage

Datasystems—Recognition and interpretation of different types of data

Actions—User-invokable functionality

Nodes—Useful hierarchical relationships between data or objects and some aspects of how they are presented to the

user

Explorer—Presentation of hierarchical data structures

Services/Lookup—Locating objects or services provided by modules, which can be used by other modules or

in-voked by the user Services are often used for performing complex operations on groups of objects, such as lation, execution or searching

compi-• Window System—manipulating and configuring windows and visual components of the user interface

Modularity

Modularity is one of the primary defining design characteristics of NetBeans—the notion that functionality should bediscrete and be able to be added and removed painlessly There is a Modules API, which defines what a module is andhow to install and uninstall modules

Modules can also offer their own APIs so that other modules can use functionality they implement—for example, theXML modules offer basic support for XML documents that can be used by other modules designed to work with spe-cific flavors of XML For cases like this, there is a way to declare inter-module dependencies The NetBeans runtimewill not allow a module to be installed if it requires another module that is not present; it will not allow a module to bedisabled without also disabling those modules dependent on it

Standards

One of the most striking aspects of the design and codebase of NetBeans is its use of standards Wherever a standard

for doing something existed, the developers of NetBeans opted to use it, rather than reinvent the wheel For example,

Trang 30

module manifest files are based on the Java Versioning Specification, Nodes are conceptually based on the JavaBeansBeanContext specification, and so on Wherever there was an existing standard or a near match, it was used.

What this adherence to standards achieves is extensibility As other pieces of code that work with the same standardsare created, it is much less difficult to get them to interoperate with NetBeans It requires greater discipline to adhere tostandards than to reinvent the wheel, but it gets you maintainability and interoperability, as standards are, by definition,documented, and if something is a standard, others are using it as well

Hierarchy, Files and Nodes

In any large, extensible application, you need a way for components of the system to create objects and for other parts

of the system to notice and work with them Additionally, you need a way to present those objects to a user Think ofthe example at the beginning of this chapter of when your database access UI looks a lot like your file management UIwhich looks a lot like other parts of your UI Most data formats are structured, and have subcomponents, and it’s useful

to be able to both manipulate and present those subcomponents as contained entities belonging to a parent entity Ageneric system is needed which can nonetheless provide data-type-specific functionality

For the first problem, creating and working with arbitrary objects, there is a convenient and understandable paradigmthat arises from operating systems: Files Applications running in an operating system create files on disk and thenwork with them The operating system provides the low-level services of creating and accessing files, and is not inter-ested in user-created files’ content Modules in NetBeans are fairly analogous to applications in an operating system,and files are the core metaphor used to manage persistent objects created by modules NetBeans has a concept of afilesystem which in its most basic sense means a storage area or namespace into which files can be written and fromwhich they can be read It also has semantics by which a “file” may be a factory for Java objects

For the second problem, presentation and containment, NetBeans provides a content-agnostic abstraction, the node,which is used to handle hierarchical representation of data and presentation of that data in arbitrary ways through a userinterface ANodeis not a container for data, so much as a pointer to data Under the hood, bridging filesystems andnodes are data objects, which identify types of data and potentially aggregate multiple related files into a single entity

Everything is a File—Virtually

To understand filesystems in the NetBeans paradigm, you will need to stretch your concept of what a filesystem is a tle bit A filesystem in NetBeans is a place where you can hierarchically store files and read files But NetBeans doesnot require that a filesystem absolutely be files on disk somewhere—only that it behave as if it were This can be ac-complished by implementing a set of interfaces defined in the Filesystems API A filesystem need only satisfy the con-tract of conforming to those interfaces; how and where the data is physically stored is irrelevant and transparent to codethat acts on the files

lit-A filesystem is effectively a hierarchical namespace for named entities that contain data or contain entities that containdata There is a Service Provider Interface (SPI) for extending NetBeans with alternate types of file storage As a con-crete example (which will be important later in this chapter), NetBeans defines and internally uses XML filesystemswhich are, for all intents and purposes, analogous to physical files on disk Additionally, there are extensions to supportFTP, CVS and other types of storage, available in separate modules that plug into NetBeans

File Attributes

Most people are familiar with the notion of files having attributes , such as whether they are read-write, etc NetBeansborrows a concept from IBM’s OS/2 in allowing files to have arbitrary additional attributes, which can be added to orremoved from In the IDE, this mechanism is used to specify things such as if a particular compilation or execution ser-vice has been specified for a given file These attributes are stored, for local files, in.nbattrsfiles in the same direc-tory as the files in question Attributes are stored using XML and Java serialization, so potentially any Java object can

be associated with a file attribute

Trang 31

Once you have virtualized the concept of a filesystem, there are some other useful things you can do If, to be a tem, one need only to satisfy the contract defined above, why not also have a virtual filesystem which owns a collection

filesys-of sub-filesystems and presents all filesys-of them in the same virtual namespace? NetBeans provides a concrete tion of this in the classMultiFileSystem, part of the Filesystems API This class allows you to construct a singlenamespace which merges a set of discrete sub-filesystems called layers and acts as if the contents of all of them lived inthe same namespace (as seen in Figure 3.1) If two different layers contain a folder called/MyFolder/with differentcontents, listing the contents of theMultiFileSystem’s/MyFolder/simply gets you the contents of both Fordealing with name collisions (e.g two layers contain different files with the same name and path), MultiFileSys-temhas a stacking order of layers In the case of a conflict, whichever filesystem is on the top of the stack is the onewhose file is returned Changes written to aMultiFileSystemare written to one or another writable layer Thereare also semantics for one filesystem to mask a file that exists in another layer, so it appears not to exist even thoughone of the merged filesystems below contains it Furthermore, it is possible to insert and remove layers at runtime

implementa-Figure 3.1 MultiFileSystem merging constituent filesystems

Mapping Files to Java Objects

NetBeans is a Java application; simply throwing around lots of files is not terribly useful Java object instances, on theother hand, are So NetBeans defines semantics for mapping files to Java object instances You can create a file with aname such ascom-mycom-MyClass.instance The Datasystems API contains a facility (implemented in a classcalledInstanceDataObject) to dereference a file with such a name and return an instance of the named class.Using this infrastructure, files can be factories for Java objects This infrastructure serves two primary purposes in Net-Beans: First, it allows for modules to register objects with the system (for example, adding beans to the ComponentPalette or adding menu items to a menu) Second, it allows objects to be registered without the JVM actually loadingthe class in question unless it is actually needed, thus saving memory

On top of this infrastructure is a facility called Lookup Lookup adds a layer of indirection which allows module code

to find objects registered via files in special folders (see the section called “The System Filesystem”) without dealingdirectly with filesystems

We mentioned above the concept of an XML filesystem, where the contents of the filesystem are actually represented

in an XML document In a NetBeans XML filesystem, the XML to add a Java class to a filesystem looks like Example3.1

Example 3.1 Adding a instance to the System Filesystem

<filesystem>

<folder name="Menu">

<folder name="View">

<file name="org-netbeans-examples-quickpanel-ShowQuickPanelAction.instance"/>

</folder>

Trang 32

</filesystem>

The effect of the above example is that when the system creates the main menu, it creates an instance of

org.netbeans.examples.quickpanel.ShowQuickPanelAction, which supplies the icon and displayname for the action on the menu, and whose actionPerformed()method will be called if the user selects themenu item

The System Filesystem

Not only does NetBeans use the concept of virtual filesystems for managing user files, it also uses a special virtualfilesystem which contains configuration information for NetBeans itself This is called the system filesystem Using theconvention of.instancefiles and other similar mechanisms to represent Java objects, NetBeans stores a wide vari-ety of information in the system filesystem For example, the system filesystem contains a folder called/Menuwhichcontains subfolders with names such asFileandEdit Those subfolders in turn contain.instancefiles for Javaclasses which implement the actions that appear in the File and Edit menus Modules are free to create their own fold-ers in the system filesystem to store data interesting to them, or add objects to folders that have defined meaningswithin NetBeans One of the reasons to use the system filesystem is that it allows objects to be declared, but theirclasses not actually loaded by the JVM until something needs to use them, thus saving memory The system filesystem

is the general registry for publicly accessible data and objects

One important aspect of a NetBeans virtual filesystem is that it can fire events to notify the rest of the system whensomething in it changes NetBeans listens for changes in the system filesystem, and if, for example, something creates anew.instancefile in one of the menu folders, that new item will appear on the menu

Module Layers

The primary way modules install their functionality into the runtime environment is via files—specifically via virtualfiles defined in the module’s XML filesystem layer (or module layer) This is a small XML document in the module’sJAR, conforming to the NetBeans filesystems DTD It is declared in the module’s JAR manifest Since NetBeans’ in-frastructure allows files to actually map to Java class instances, what a module generally installs is class instances, us-ing the.instancefile convention described above The files are put into folders in the system filesystem that havedefined meanings to the system or to a module The XML layer defines a hierarchy of files and folders which may ormay not overlap with existing folders in the system filesystem When a module is loaded, this small XML filesystem ismerged with the system filesystem, shown in Figure 3.2

Figure 3.2 Module adding XML layer to the system filesystem

Ngày đăng: 12/08/2014, 21:20

TỪ KHÓA LIÊN QUAN