for-In this chapter you will add support for the DocBook language to Eclipse as follows: ❍ You create a DocBook validator for files with the .docbookextension.. ❍ You specify a DocBook c
Trang 1Figure 12.10 New Launch Configuration
4 You should see your GlassFish server adapter listed now Select GlassFishand click the Next button The GlassFish Runtime wizard opens (see Figure12.12) Note how the wizard UI gets populated with form fields for theruntime properties you defined in the server definition file
5 Specify the location of the GlassFish installation directory Enter the tion or select it using the Browse button Note that a directory browse but-ton has been provided because the type of the property was directory.Click the Finish button The Installed Runtimes preference page now listsGlassFish(see Figure 12.13)
loca-6 You have now added the GlassFish server runtime environment and areready to use it for a new Web project In the Project Explorer view, rightclick and select New 䉴 Dynamic Web Project The New Dynamic WebProjectwizard opens (see Figure 12.14)
Trang 2Figure 12.12 GlassFish Runtime
575
Trang 3Figure 12.13 Installed Runtimes—GlassFish
Figure 12.14 New Dynamic Web Project
Trang 47. EnterTestWebProjectas the project name and select GlassFishas the target runtime Click the Next button The Select Project Facets page is displayed (see Figure 12.15).
Figure 12.15 Select Project Facets
8 Notice how the set of supported facets matches the allowed values that weredefined in plugin.xml Accept the defaults for other properties Click Finish.WTP creates the project Notice that a GlassFish library gets added to the proj-ect as defined by the runtime classpath provider extension (see Figure 12.16)
9 Create a simple JSP named index.jspin the WebContentfolder Add somesimple content to it This completes the project setup
10 You are now ready to run the JSP on GlassFish In the Project Explorer,selectindex.jsp, right click, and invoke the Run As 䉴 Run on Servermenuitem The Run On Server wizard opens (see Figure 12.17)
11 Create a new server configuration for the GlassFish runtime Click Next tocontinue You will see the server properties displayed (see Figure 12.18).These properties were also defined in the server definitions file Enter theproper values
12 Click Next to continue The Add and Remove Projects page is displayed (seeFigure 12.19)
Trang 5Figure 12.16 Dynamic Web Project—TestWebProject
Figure 12.17 Define a New Server
Trang 6Figure 12.18 GlassFish Server
Figure 12.19 Add and Remove Projects
Trang 7Figure 12.20 Run On Server—index.jsp
13 A server configuration includes the list of dynamic Web projects
TestWebProjectwas automatically added for you, so simply click theFinishbutton The wizard creates the server, starts it, publishes theTestWebProjectproject to it using the Ant scripts, and launches theWeb browser using the URL for the JSP (see Figure 12.20) As the serverstarts and publishes, messages are displayed in the Console view
Summary
In this chapter you learned about the server tools and how to extend WTP with anew generic server adapter You developed and tested a generic server adapterfor GlassFish
Trang 8There is more to server tools than what was covered here Generic serversupport is suitable for most purposes However, you should also have a look atthe custom adapters, such as the Tomcat plug-ins, to see how you can have fullcontrol over the server tools capability If you would like to learn how to publishyour server plug-ins as installable features, and provide links to your updatesites, you should look at the Apache Geronimo plug-in.
Trang 10Supporting New File Types
The limits of my language mean the limits of my world.
583
—Ludwig Wittgenstein
At its core, an integrated development environment (IDE) assists a developer inworking with various development artifacts While some of the artifacts, such asserver instances, may be intangible, most artifacts map to one or more fileswhose syntax is defined by programming languages The IDE’s job is to simplifythe task of working with these languages
There are a number of tools an IDE can provide to simplify development oflanguage-specific files A new file wizard handles tasks such as naming and place-ment of the file and can create a skeleton structure of the new file A rich editorsimplifies manual editing of the file with content assistance and syntax highlight-ing Rich editors may also include a design or graphical view that provides analternate visualization of the file A validator, which will typically be integratedwith the editor, checks the file to ensure it is compliant with the language specifica-tion If a file requires compilation or some other form of transformation before itcan be deployed, a facility for building the file should also be included
DocBook is an XML language for authoring documents such as books, articles,and reference pages (see Example 13.1) It can be obtained from the DocBook Web site:
Trang 11of the artifacts, such as server instances, may be intangible, most artifacts map to a file or a variety of files defined by specific languages The IDE's job is to simplify the task of working with specific languages.
</para>
<para>
There are a number of tools an IDE can provide to simplify
development of language-specific files A new file wizard handles tasks such as naming and placement of the file and can create a
skeleton structure of the new file A rich editor simplifies
manual editing of the file with content assistance and syntax
highlighting Rich editors may also include a design or graphical view that provides a different visualization of the file A
validator, which will typically be integrated with the editor,
checks the file to ensure it is compliant with the
language specification If a file requires compilation or some
other form of transformation before it can be deployed, a facility for building the file should also be included.
</para>
</article>
Unlike many other authoring formats, DocBook documents contain no matting or presentation information Instead, a DocBook document containstags (XML elements) that describe its content The removal of presentationinformation from the source document solves the typical problem of inconsistentformatting and provides increased publishing flexibility (the ability to publish adocument in multiple formats) Publishing flexibility is achieved by transformingthe document after it has been authored into a desired format, such as HTML orPDF In this way, DocBook is very much like a programming language in thatyou write the source and then transform it into a consumable form
for-In this chapter you will add support for the DocBook language to Eclipse
as follows:
❍ You create a DocBook validator for files with the docbookextension
Note that DocBook files typically use the xmlextension The docbookfileextension is used in this chapter for illustrative purposes since WTP con-tains a number of tools, including a validator, for XML files
❍ You define a DocBook marker type to allow end users to filter DocBookproblems from the Problems view
❍ You specify a DocBook content type that allows DocBook files to makeuse of all the XML-related tools, including the XML editor
Warning: As of WTP 1.5, the WTP extension points and API shown in this chapter
are not final These extension points and API may change in future versions of WTP
Trang 12Figure 13.1 Defining the DocBook Plug-in Project
Creating the DocBook Extension Plug-in
As always, the first step in contributing DocBook support to Eclipse is to create aplug-in that will hold your DocBook-specific extensions To create the DocBookextension plug-in, do the following:
1 Open the Plug-in Development perspective, create a new plug-in projectusing the New Plug-in Project wizard, and name it:
org.eclipsewtp.docbook
2 The DocBook extensions you will contribute will not make any UI butions or require an activator Deselect the options Generate an activatorand This plug-in will make contributions to the UI (see Figure 13.1)
contri-The DocBook Validator
Modern software development requires the use of many languages Gone are thedays when being an expert in one language was a career option Many languagesexist in the same space and, to effectively do their job, developers are oftenrequired to work with the many corresponding file types For example, there aremore than just a few languages available in the Web space, including ASP, CSS,
Trang 13HTML, Java, JavaScript, Perl, PHP, Ruby, WSDL, XML, XSD, and XSL Whileall of these languages are not required for every Web project, it is typical to useseveral of them DocBook, which can be used to document Web and other appli-cations, is just one more language in the mix.
With so many different languages, it can be difficult, and overwhelming, fordevelopers to understand each one in the depth required to ensure that the filesthey are creating are correct according to the various specifications DocBookcontains a well-structured definition for documents If a document does not com-ply with the DocBook structured definition, then it is not a DocBook document,and the behavior of DocBook tools when used with this document cannot beguaranteed to be correct To solve this problem, you will contribute a DocBookvalidator to the Eclipse IDE This validator will give developers the assurance thattheir DocBook files conform to the specification and remove the burden fromthem to be DocBook experts
In this section you will contribute the DocBook validator to Eclipse using theWTP validation framework The following sections will detail why and how youwill use the validation framework First, the benefits of the framework will be pre-sented, highlighting how the framework simplifies development of the DocBookvalidator After the rationale for using the framework is clear, you will then imple-ment the DocBook validator and contribute it to the validation framework
The WTP Validation Framework
Before creating a DocBook validator for Eclipse, you need to identify how the idator will interact with the Eclipse workbench In other words, what will theDocBook validator do in Eclipse? Following the example set by the Java compiler(the JDT is typically thought to represent the best of Eclipse), the DocBook val-idator should contribute error and warning markers to the Problems view, be runautomatically on save or when the workspace is cleaned, and have a preferencedefined that allows the validator to be disabled Additionally, you may want toinclude an option to manually validate via an action on the context menu.Although the validator can interact directly with the various pieces of theplatform that provide the functionality outlined above, the validation frame-work provides a simplified method to consistently add the DocBook validator toEclipse Specifically, the validation framework will add errors and warningsreported by the validator to the Problems view, add a preference to disable thevalidator, and run the validator on save as part of the build and via the standardcontext menu Validate action The validation framework allows you to focus onyour core competency, which in this case is a deep understanding of DocBook,
val-by handling these various pieces of Eclipse integration It significantly reducesthe learning curve and time required to add a validator to Eclipse
Trang 14Note that as of WTP 1.5, the validation framework does not support Eclipsecontent types The WTP 1.5 support is limited to distinguishing resources based
on file extension
Implementing the DocBook Validator
In this section you implement the DocBook validator by doing the following:
1 For the DocBook validator to make use of the validation framework, youfirst must add a dependency on the validation framework to your plug-in
In your DocBook project, open the plug-in manifest editor, change to thedependencies tab, and add a dependency on
org.eclipse.wst.validation
The validation API depends on the core runtime plug-in for the scheduling
of validation jobs and reporting validation status Specify a second
dependency on the plug-in
org.eclipse.core.runtime
The DocBook validator will make use of Eclipse file resources in order tovalidate them In Eclipse, resources are represented by the IResource andIFileinterfaces Add a dependency on the following plug-in that containsthese interfaces:
org.eclipse.core.resources
2 With the dependencies declared, you can now create the extension thatwill declare the DocBook validator to the validation framework Change
to the Extensions tab and click Add to add a new extension
The validation framework defines this extension point:
org.eclipse.wst.validation.validator
You will use this extension point to register the DocBook validator with theframework Select the extension point from the list and click Finish Theextensions page should now display the new extension point Give the exten-sion point the id docbookValidatorand the name DocBook Validator.
3 Next, right click on the extension point and select New䉴 validator The toandfromproperties on the validator extension are used to migrate anexisting validator to a new class while maintaining the existing markeraffiliation with the validator This means that when an old workspace ismigrated to a newer version of WTP, markers that were created by a validator will not be stranded leaving the user with no way to remove
Trang 15them Because the DocBook validator is a new validator, these propertiesare not applicable.
4 The validator extension point requires three elements in order to specify theDocBook validator: the runelement, the helperelement, and the filterelement
The first element is the runelement, which will be used to specify detailsabout the validator class and how it should be used by the framework.Start by declaring the new validator using the runelement Right click onvalidator and select New 䉴 run You will use the runelement’s classattribute to specify the DocBook validator class to the validation frame-work, but first you will create the DocBook validator class
Save your plug-in manifest and open the New Java Class wizard by selectingFile 䉴 New 䉴 Class Enter the class name DocbookValidatorand the package
Trang 16Figure 13.3 The run Extension
Click Finish The DocbookValidatorclass opens in the Java source editor.You may see some warnings about discouraged access on your newly cre-ated class These warnings are simply stating that you’re not using
API You can ignore these warnings for now (In general, these warningsalert you that you’re in unsupported waters making use of code that hasnot been declared API.) Close the editor for now You’ll deal with theimplementation details after you finish declaring the extension
Now that you’ve created the class and know the fully qualified class name,return to your plug-in manifest editor and enter the following for the runelement’s classattribute:
org.eclipsewtp.docbook.DocbookValidator
There are three other boolean properties on the validator extension thatare relevant for the DocBook validator (see Figure 13.3): enabled, incre- mental, and fullBuild The fourth option, async, is deprecated As the val-idator implements IValidatorJobit will be run asynchronously
Theenabledproperty specifies whether the DocBook validator should beenabled by default You may want to disable a validator by default ifthere will be a significant performance penalty when the validator isenabled The DocBook validator will be lightweight, so set this property
totrue
Theincrementalproperty tells the validation framework whether theDocBook validator should be run as part of the incremental build Theincremental build runs when a resource is changed (typically when it issaved) One of the requirements for the DocBook validator is that itshould validate on save Set this option to true
Trang 17ThefullBuildinforms the validation framework whether or not the
DocBook validator should run as part of a full build A full build is runwhen users select to clean a project or their workspace (see Figure 13.4) Setthis to trueto allow users to clean DocBook files
Figure 13.4 The Project 䉴 Clean Menu
5 The second element required by the validation framework is the helperelement, which will be used to specify the class that handles model loadingfor the validator
Right click on validator and select New 䉴helper
The validation framework provides a list of resources that should be dated by passing a workbench context (also known as a helper) of typeIWorkbenchContextto the validator The validation frameworkrequires that validators declare the implementation class of the
vali-IWorkbenchContextinterface that they will use The validation frameworkincludes a default workbench context that can be used by client valida-tors The default workbench context provides the ability to load an IFilefor each file that is to be validated The DocBook validator will only sup-port files; therefore, the default workbench context will suit its needs.Specify that the DocBook validator will use the default workbench con-text provided by the validation framework by setting the workbench context class as
org.eclipse.wst.validation.internal.operations.WorkbenchContext
6 The third element that the validation framework requires is the filterelement This element is used to specify the resources for which the valida-tor is enabled As specified in the requirements, the DocBook validatorwill run for files with the extension docbook
Trang 18To specify the filter, right click on the validatorelement and select
New䉴 filter The filterelement contains these three properties that youneed to specify: objectClass,nameFilter, and caseSensitive
objectClassspecifies the type of object that will be filtered The DocBookvalidator will validate files, so specify the objectClass
Thefilterelement contains an optional fourth property, action, whichcan be used to specify the specific actions for which the validator shouldrun For example, you can specify that the validator should only run whenthe New action is invoked This will restrict the validator to running only
on file creation The actionproperty is not typically used with validators
as validators are generally defined for resources that will be edited
7 You’ve now completed the DocBook extension declaration Other sion contributions exist for the validator that allow further restrictions to
exten-be placed on the condition for which it is enabled These extensions allowyou to restrict the validator to certain project types or facets For example,
if you were to define an authoring project nature, you may choose torestrict the DocBook validator to only run on projects with this nature.The DocBook validator will be enabled for all projects and facets, becauseaside from the name filter no restrictions have been defined
The manifest editor stores your extension declaration in plugin.xml Take
a look at the extension by clicking on the plugin.xml tab (see
Trang 19Edit DocbookValidator.java(see Example 13.3).
Example 13.3 Listing of DocbookValidator.java
public class DocbookValidator implements IValidatorJob {
public ISchedulingRule getSchedulingRule(IValidationContext helper) { return null;
}
public IStatus validateInJob(IValidationContext helper,
IReporter reporter) throws ValidationException {
final DocbookValidator validator = this;
final IReporter theReporter = reporter;
String[] uris = helper.getURIs();
for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) {
Trang 20String filename = uris[i];
filename = filename.substring(filename.indexOf("/", 1));
Object[] parms = { filename };
final IFile file = (IFile) helper.loadModel("getFile", parms); Document doc = null;
try { DocumentBuilderFactory domFactory = DocumentBuilderFactory newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); domBuilder.setErrorHandler(new org.xml.sax.ErrorHandler() { public void error(SAXParseException e)
throws SAXException { reportMessage(LocalizedMessage.NORMAL_SEVERITY, e.getLocalizedMessage(), e.getLineNumber());
} public void fatalError(SAXParseException e) throws SAXException {
reportMessage(LocalizedMessage.HIGH_SEVERITY, e.getLocalizedMessage(), e.getLineNumber());
} public void warning(SAXParseException e) throws SAXException {
reportMessage(LocalizedMessage.LOW_SEVERITY, e.getLocalizedMessage(), e.getLineNumber());
} private void reportMessage(int severity, String message, int lineno) {
LocalizedMessage lMessage = new LocalizedMessage(
severity, message, file);
lMessage.setLineNo(lineno);
theReporter.addMessage(validator, lMessage);
} });
doc = domBuilder.parse(file.getRawLocation().toFile());
} catch (Exception e) { }
if (doc != null) { Element rootElem = doc.getDocumentElement();
String rootName = rootElem.getNodeName();
if (!"chapter".equals(rootName) && !"set".equals(rootName)
LocalizedMessage.HIGH_SEVERITY,
"DocBook documents must begin with one of the " +
"following elements: appendix, article, bibliography, " +
"book, chapter, glossary, preface or set.", file);
message.setLineNo(1);
reporter.addMessage(this, message);
}
Trang 21} }
return Status.OK_STATUS;
}
public void cleanup(IReporter reporter) {
// There is no cleanup for the DocBook validator to perform.
}
public void validate(IValidationContext helper, IReporter reporter) throws ValidationException {
// This method is for validators that do not run in jobs
// and so is not implemented for the DocBook validator.
}
}
TheDocbookValidatorcontains four methods that we’ll discuss in the following order: getSchedulingRule,validateInJob,validate,and cleanup.The validation framework runs most validators as Eclipse jobs For each job,
a scheduling rule can be specified that the Eclipse jobs framework will use todetermine when the job will be run getSchedulingRuleis used to specify aspecific scheduling rule that the validation framework should use when run-ning the validator job This method is useful if your validator has schedulingrequirements such as only running after another validator has completed.Returning null indicates that the validator will run with the default schedul-ing rule set by the validation framework The DocBook validator does notrequire a special scheduling rule and therefore returns null (For more aboutscheduling rules, see the Eclipse help topic Scheduling rules.)
As stated previously, most validators are run as jobs This allows the dation framework to run multiple validators at the same time, can
vali-significantly reduce the amount of time required for all validators to plete, and allows the validators to run without blocking the Eclipse UI Torun a validator as a job, the validator must implement validateInJobwithits validation logic We’ll discuss the DocBook validation logic after cover-ing the last two methods in the validator
com-The DocBook validator could alternatively be run without using a job Avalidator should not be run as a job if it is not thread safe or has a specificscheduling requirement that cannot be met using Eclipse jobs In this case,thevalidatemethod from the IValidatorinterface must be implementedinstead of the validateInJobmethod The DocBook validator will be run
as a job and has therefore left the validatemethod empty (You may bethinking that this part of the interface is a little clumsy in its current form
We agree This is a candidate for refactoring.)
Trang 22Thecleanupmethod gives a validator a chance to clean up any artifactsproduced during validation As we will discuss next, the DocBook valida-tor logic does not produce any artifacts that require clean up after valida-tion completes, so this method remains empty.
As it stands, the only method that the DocBook validator needs to implement
is the validateInJobmethod, which contains the validation logic
ThevalidateInJobmethod starts by requesting the list of file URIs to bevalidated from the helper Only files applicable for the validator will be
in the list, but it is the responsibility of the validator to iterate over thefiles and validate each one This feature allows validators to implementspecific logic for batch validation such as caching document models toimprove performance
The validator iterates over this list, validating each file The exit criteriafor the loop iterating over the files contains an additional check The exitcriteria contains the expression
!reporter.isCancelled()
This condition checks whether the validator has received a cancel request,such as that issued when a user selects to cancel validation, and terminatesvalidation without validating the remaining files To be a good citizen in theworkbench and as part of the validation framework, a validator should checkperiodically to see if it has been canceled (See the Validator Best Practicessidebar that follows for more about being a good validation citizen.)
The DocBook validation logic is then implemented as a two-step process:
❍ Step 1: DocBook is an XML language The first step is to validate the
document for XML conformance Success in this step means the ment is a well-formed XML document
docu-The DocBook validator uses the standard Java XML parsing (JAXP)interface to parse the DocBook document Using JAXP serves two purposes First, it has a validation option that performs XML confor-mance validation required by this step Second, it parses the DocBookdocument into an easily traversable XML model, which will be used instep 2
A custom error reporter is registered with the parser that allows theDocBook validator to report XML conformance errors using the validation framework A LocalizedMessageobject is used to hold anerror, warning, or information message and is passed to the reporter
to report the message to the workbench LocalizedMessageis used
Trang 23both when reporting errors produced from XML conformance validation and when reporting custom DocBook error messages instep 2.
❍ Step 2: DocBook contains specific rules beyond those defined for
XML conformance These rules are what differentiate a DocBook document from a generic XML document with no specified grammar.The second step is to validate the document according to the
DocBook specific rule set
To keep this example simple and focused on the validation extension,the DocBook validator only checks that the root element is one of theallowed elements The allowed root elements are appendix,article,bibliography,book,chapter,glossary,preface, and set Obviously, acomplete validator will need to check a lot more than the root element.Note that XML languages often define an XML schema or DTD,which can be used to perform most language-specific validation withthe XML validator DocBook does have an XML schema defined Thisexample does not make use of the schema to show the two stages ofvalidation
After all the files have been validated, the validator returns the OK status, signifying that validation has completed
Tip: When implementing the DocBook validator you may see several restricted
access warnings These warnings appear because the validation framework API is stillinternal To make it easier to work, you can disable these warnings by following thesesteps:
1 Right click on the DocBook plug-in project and select Properties䉴 Java
Compiler䉴Errors/Warnings The Errors/Warnings page opens
2 Select Enable project specific settings, expand the Discouraged
reference (access rules) section and change the Deprecated andrestricted API Discouraged reference (access rules) option to Ignore.
9 You’ve declared the minimum that’s required to run the DocBook
validator Now is a good time to take a look at what you’ve accomplishedthus far Launch a runtime workbench In the runtime workbench selectWindow䉴 Preferences䉴Validation The Validation preference page should
Trang 24Figure 13.5 The Validation Preference Page
list the DocBook validator, indicating that the validator is registered withthe validation framework (see Figure 13.5) Close the Validation
12 Edit article.docbook as shown in Example 13.1
13 In the Project Explorer, validate the file Right click on it and select Validate
No errors are displayed in the Problems view
Trang 2514 Invalidate the file by changing the root element to <eclipsearticle>.Validate the file again The Problems view displays an error that the
DocBook validator produced (see Figure 13.6)
Figure 13.6 The DocBook Validator Error Displayed in the Problems View
Validator Best Practices
Given the nature of validators and their interaction with the Eclipse workbench, hereare a few best practices when implementing your own validator:
1 As already mentioned, validators should check their canceled status
and terminate early if they have been canceled A failure to cancelwhen requested can lead to an unresponsive workbench
2 A validator will likely not be run in isolation but rather as par t of
a group of validators and typically as par t of the build Validatorsshould be lightweight and very fast to avoid introducing lags in buildtimes
3 A validator should not lock resources Validators should only check for
correctness of resources and should not try to fix or otherwise
modi-fy resources Doing so can lead to deadlocks in the workbench orperiods when the workbench is unresponsive
Creating a Custom Marker Type
A marker is an annotation on a file that is used to represent information ated with the file, such as bookmarks, breakpoints, and problems The DocBookvalidator reports error, warning, or information messages as markers Thesemarkers are displayed in various places in the Eclipse workbench, most notablythe Problems view, and the left margin of most editors Each marker that iscreated is of a certain defined type The views that display markers give usersthe ability to filter certain markers For example, markers can be filtered
associ-in the Problems view by selectassoci-ing Menu (down arrow)䉴 Configure Filters
Trang 26By default, all validators defined with the validation framework create markers of the type
org.eclipse.wst.validation.problemmarker
These markers can all be filtered from the Problems view by deselectingValidation Message in the Filters dialog While this filter level may be fine for some validators, the DocBook validator should provide finer-grained filtering forusers to improve the user experience This finer-grained filtering can be achieved
by specifying a custom marker type
In this section you will create a custom DocBook marker type To create thecustom marker, do the following:
1 To specify the custom DocBook marker, you need to specify a new sion and add a contribution to the existing DocBook validator extensiondeclaration
exten-On the Extensions page of the manifest editor add the extension pointorg.eclipse.core.resources.markers
Specify the id validationMarkerand the name DocBook Problem
2 The default marker defined by the validation framework specifies tions to the base marker type that are used by the framework For the newDocBook marker to function properly it must extend the default valida-tion marker
addi-In the plug-in manifest editor’s Extensions page, right click on the DocBookmarker extension point and select a new super Specify the type
org.eclipse.wst.validation.problemmarker
3 With the DocBook marker type defined, the validation framework needs
to be told to use this marker type when creating markers for the DocBookvalidator
Right click on the validate extension you created in the previous sectionand select a new markerId Specify the markerIdas the fully qualified id ofthe DocBook marker
org.eclipsewtp.docbook.validationMarker
4 Save the plug-in manifest
5 That’s it You’ve defined a DocBook marker type without writing anycode View your contribution to the plug-in manifest by selecting the plugin.xmltab in the manifest editor (see Example 13.4)
Trang 27Example 13.4 Listing of the DocBook Marker Type Contribution to plugin.xml
<eclipsearti-In the Problems view, select Menu (down arrow) 䉴Configure Filters.The Filters dialog opens Deselect the DocBook Problem(see Figure 13.7),and click OK The Filters dialog closes and the Problems view is displayedwithout the DocBook error message
Figure 13.7 Filtering DocBook Markers from the Problems View
Tip: If you’re having trouble with changes to plug-in manifests showing up in your
runtime workbench, you may need to clear the configuration area when launchingthe runtime workbench You can clear the configuration area on the Configurationtab of the Run dialog
Trang 28Declaring the DocBook Content Type
When adding a new language such as DocBook to Eclipse, it is a good idea todefine the language to Eclipse Defining the language allows Eclipse to handlethe tools and operations that surround the language in a coordinated and uni-fied fashion For example, by defining the DocBook language with Eclipse itwill allow editors, builders, and other tools to be defined specifically for thelanguage
The most effective way to inform Eclipse that you are adding a language is tospecify a content type By specifying a DocBook content type you are tellingEclipse what content it can expect to find in a DocBook file You can specify aDocBook file simply by the file extension, but because a DocBook file is not tied
to the file extension a content type is more flexible
Getting a little more concrete, a content type has an id and a name for whichyou will specify DocBook specific entries You can also specify the file extensions
that are associated with the DocBook content type Notice that we said
sions, not extension Although in your case you will specify a single file
exten-sion, content types are not restricted to a single file extension This flexibility can
be exploited by Eclipse end users by customizing the content types in their space using a preferences page You can also declare one or more base contenttypes for the DocBook content type Base content types represent more genericrepresentations of the content type For example, DocBook is an XML language.You will therefore specify that the DocBook content type has a base content type
work-of XML Specifying a base content type work-of XML will allow the DocBook contenttype to take advantage of all the tools and operations defined for the XML con-tent type, such as the XML editor
In this section you will define the DocBook content type to Eclipse by doingthe following:
1 In the manifest editor, change to the Extensions tab and click Add Add anextension of type
org.eclipse.core.runtime.contentTypes
The platform defines this extension point to specify content types toEclipse
2 Right click on the newly created content type extension and select
New䉴 content-type Specify an id of contentTypeand a name of DocBook Content Type.As discussed previously, you should specify that DocBookhas a base content type of XML, so specify a base type of
org.eclipse.core.runtime.xml
Trang 293 The file-extensionsattribute accepts a list of the file extensions forwhich this content type is applicable This is the default list, and more fileextensions can be added later by other plug-ins or via Eclipse’s preferences.Specifyfile-extensionsasdocbook.
4 It is also good practice to specify the default character set In the case ofXML and DocBook, this is UTF-8 Specify the default-charsetasUTF-8.Save the manifest editor
5 To take a look at your extension contribution to plugin.xml, switch to thesource view of your plug-in manifest by clicking the plugin.xml tab (seeExample 13.5)
Example 13.5 Listing of the DocBook Content Type Contribution to plugin.xml
work-First, the article.docbookicon has been changed to the XML icon TheXML icon is displayed because the XML editor is now the default editorfor DocBook files The XML editor became the default editor for
DocBook files when you specified the XML content type as a base contenttype for the DocBook content type As should be expected, opening the filenow opens the XML editor and populates the outline view (You can alsocustomize the XML editor for DocBook See The Structured Source
Editing (SSE) Framework sidebar.)
Second, the DocBook content type is now listed in the Content Types erences page (see Figure 13.8) This listing allows users to declare other fileextensions that represent DocBook files
pref-7 To show the power this content type grants an end user, you’ll use it to
specify that files with the extension *.dbkare DocBook files
Trang 30Figure 13.8 The Content Types Preference Page Featuring the DocBook Content Type
In the Project Explorer, rename article.docbooktoarticle.dbk Rightclick on article.docbookand select Refactor䉴 Rename Specify the namearticle.dbkand click OK The file’s icon changes to the default text icon,and the XML editor no longer opens for the file
Select Window 䉴 Preferences The Preferences dialog opens Select
General 䉴 Content Types On the Content Types page select Text 䉴 XML 䉴DocBook Content Type Click Add and specify the file type *.dbk Click
OK.*.dbkis associated with the DocBook content type (see Figure 13.9).The DocBook specific tools, including the XML icon and editor, are nowenabled for the *.dbkextension
In the case of the DocBook extension, a simple content type definition has vided some pretty significant benefits The one limitation in this case is with theDocBook validator The validator is not enabled for *.dbkfiles because it is associ-ated with the *.docbookfile extension and not with the DocBook content type
Trang 31pro-Figure 13.9 Associating *.dbk with the DocBook Content Type
The Structured Source Editing (SSE) Framework
When adding DocBook to Eclipse you simply enabled the XML editor to work for theDocBook content type This is a very quick way to get improved functionality forXML-based languages with little effort, but there is a lot more customization that can
be done
The XML editor is part of a larger family of WTP editors known as the structuredsource editors Many of WTP’s editors, including the DTD, HTML, JavaScript, JSP,WSDL, and XML schema editors, are built on SSE SSE provides enhancements on top
of the text-editing framework It is useful when creating editors for highly structuredlanguages like XML, but really shines when used for editors that contain mixed contenttypes such as JSPs and HTML Mixed content types are those languages in which otherlanguages can be embedded For example, in JSP and HTML not only does the editorneed to handle Java and HTML, it also needs to handle CSS and JavaScript
SSE will assist you when you’re ready to take the DocBook tooling to the next level
by creating a custom DocBook source editor complete with content assistance andsource validation—a project for another time
Trang 32In this chapter you added support for the DocBook language to Eclipse Youcontributed a DocBook validator to the validation framework You also con-tributed a custom DocBook marker and defined the DocBook content type,which allowed DocBook files to make use of the WTP XML tools such as theXML editor and outline view
In the next chapter we’ll focus on extending the WTP tooling for anotherlanguage, WSDL
Trang 34Creating WSDL Extensions
Our native language is like a second skin, so much a part of us we resist the idea
that it is constantly changing, constantly being renewed.
—Casey MillerMany languages are not static They evolve and grow over time For example,natural languages, such as English, continue to evolve and grow as new con-structs, such as words, terms, and sentence structure, are added to the language
or take on new meaning Although all are written in English, Shakespeare’s work
is noticeably different from that of John Grisham or Margaret Atwood
Just as natural languages may evolve, so too may computer languages In theXML family of languages, the content of each element may be defined by agrammar, typically specified by a DTD or XML Schema (XSD) If the grammarlimits the content to a fixed set of elements and attributes, the language is said to
have a closed content model For example, XSD itself has a closed content
model To add new content to XSD, you must put in it annotationelements
In contrast, an XML language that allows new elements and attributes to be
added is said to have an open content model Web Service Description Language
(WSDL) has an open content model Elements and attributes may be added tothe language at almost any level [WSDL11] (see Example 14.1)
Example 14.1 WSDL 1.1 Open Content Model
<wsdl:definitions name="nmtoken"? targetNamespace="uri"?>
<import namespace="uri" location="uri"/>*
Trang 36WSDL was created with an open content model to avoid placing restrictions
on the technologies that may be used with Web services, most notably Web servicebindings New specifications for elements and attributes that describe additionaltechnologies can be added to the language as the need arises The WSDL 1.1 speci-fication defines two such extensions: a binding for SOAP (see Example 14.2) andone for HTTP (Okay, so really there is a third binding type defined for MIME, but
it must be used in conjunction with SOAP or HTTP and as such is not a alone binding.)
stand-Example 14.2 SOAP Binding in WSDL 1.1
<wsdl:port name="ServiceSOAP" binding="tns:BindingSOAP">
<soap:address location="h http://www.example.org/"/>
In this chapter, let’s suppose you’ve been given the task of customizing WTP’sWSDL tools for your organization by adding support for the SOAP namespaceand enforcing your organization’s naming conventions for Web services
Note that since SOAP 1.1 binding extensions are already defined in WTP,you will define SOAP bindings for the following artificial WTP SOAP namespace:
Trang 37Now that you’ve explored the WSDL editor, in this chapter you will:
❍ Contribute binding extension elements for the WTP SOAP namespace tothe WSDL editor
❍ Contribute a validator for the WTP SOAP namespace to the WSDL validator
❍ Contribute custom validation rules to enforce your organization’s Webservice naming conventions
Example 14.3 Listing of Echo.wsdl
The W3C WSDL 1.1 Binding for SOAP 1.2
If you are ambitious, you might want to apply the following instructions to develop
a realistic SOAP 1.2 binding as specified by the recent W3C Member Submission,
WSDL 1.1 Binding Extension for SOAP 1.2 [WSDL11SOAP12], which defines the
namespace
http://schemas.xmlsoap.org/wsdl/soap12/
Such an extension would be a welcome contribution to WTP You should send a note
to the WTP developers list first to see if anyone else is already working on this TheWTP developers’ mailing address is
<wtp-dev@eclipse.org>