blob: 1cb9e1972f5f77ba0624f084fef79387ee77dc9d [file] [log] [blame]
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
= NetBeans Platform Feed Reader Tutorial
:jbake-type: platform_tutorial
:jbake-tags: tutorials
:jbake-status: published
:syntax: true
:source-highlighter: pygments
:toc: left
:toc-title:
:icons: font
:experimental:
:description: NetBeans Platform Feed Reader Tutorial - Apache NetBeans
:keywords: Apache NetBeans Platform, Platform Tutorials, NetBeans Platform Feed Reader Tutorial
Welcome to the NetBeans Platform Feed Reader tutorial. The Feed Reader that you create in this tutorial is a simple RSS/Atom feed browser, modeled after the Sage plug-in for Mozilla Firefox. It presents a tree of feeds with subnodes representing individual feed entries that you can open in a browser.
To illustrate the end result, here you see the Feed Reader that you will create in this tutorial, displaying a feed entry from the link:https://netbeans.org/rss-091.xml[NetBeans Highlights feed]:
image::images/feedreader_69-feedreader.png[]
NOTE: This document uses the NetBeans IDE 6.9 Release. If you are using an earlier version, see link:68/nbm-feedreader.html[the previous version of this document].
== Prerequisite Knowledge
This is not a beginner's tutorial. You are assumed not only to be familiar with Java and with Swing, but with the basic concepts and processes of the NetBeans Platform. At the very least, you should be aware of the following two documents and, ideally, you will have worked through them and understood the topics they address:
* link:http://refcardz.dzone.com/refcardz/essential-netbeans-platform[Essential NetBeans Platform RefCard]. Anyone getting started with the NetBeans Platform must have this DZone RefCard, which explains the benefits, scope, and features of the NetBeans Platform. It outlines the most important APIs and provides many tips and tricks.
* link:nbm-quick-start.html[NetBeans Platform Quick Start]. This short tutorial guides you through a complete process for building a rich-client application on top of the NetBeans Platform. The major development stages and tools are covered, and a modular application is the result of the tutorial. This tutorial also introduces crucial classes used in the tutorial below, in particular the classes link:http://bits.netbeans.org/dev/javadoc/org-openide-util-lookup/org/openide/util/Lookup.html[Lookup], link:http://bits.netbeans.org/dev/javadoc/org-openide-util-lookup/org/openide/util/LookupListener.html[LookupListener], and link:http://bits.netbeans.org/dev/javadoc/org-openide-util-lookup/org/openide/util/lookup/InstanceContent.html[InstanceContent].
== Setting Up the Application
In NetBeans IDE, building an application on top of the NetBeans Platform starts with generating a number of files which will serve as the foundation of your application. For example, the IDE provides several project wizards that set up all the basic files needed by modules and applications built on the NetBeans Platform.
* *NetBeans Platform Application.* A project that groups a set of module projects and library wrapper module projects that have dependencies on each other, and lets you deploy them together as a unit. Automatically included are a subset of the modules that make up the NetBeans Platform.
* *Module Suite.* Same as above, except that the pre-included modules are more than only those relating to the NetBeans Platform—in this case, all the modules that make up NetBeans IDE are included as well.
* *Library Wrapper Module.* A project that puts a library JAR file on its classpath and exports some or all of the JAR file's packages from the module as public packages.
* *Module.* A project for implementing the functionality, business logic, and user interface of a module or application built on the NetBeans Platform.
=== Creating the Application Skeleton
[start=1]
1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select NetBeans Modules. Under Projects, select NetBeans Platform Application. You should see the following:
image::images/paintapp_paintapp-proj-wiz.png[]
Click Next.
[start=2]
1. In the Name and Location panel, type ``feedreader-suite`` in Project Name. Change the Project Location to any directory on your computer. Click Finish.
The IDE creates the ``feedreader-suite`` project, which looks as follows in the Projects window:
image::images/feedreader_65-suite-project.png[]
The project will contain the module project and library wrapper module projects that you will create in the following subsections.
=== Wrapping the Libraries
You could bundle the entire Feed Reader application into a single module. However, the application needs the Rome, Rome Fetcher, and JDom libraries:
* *Rome.* Reads RSS and Atom feeds, using a very simple API.
* *Rome Fetcher.* Allows the retrieval of feeds via HTTP.
* *JDom.* Is an XML parsing API. The only reason the Feed Reader will need it is because the Rome library uses it.
Later, if you want to extend the Feed Reader application with more modules that may use these libraries, it would be better for them to depend on just the library modules, rather than the entire Feed Reader. Also, library modules can be "autoloading", which means that NetBeans will only load them when needed. Until that happens, it won't take up any memory at runtime.
[start=1]
1. Right-click the Modules node in the project in the Projects window, as shown below, and click Add New Library:
image::images/feedreader_65-add-lib0.png[]
When you do so, you should see the following:
image::images/feedreader_65-lib-wiz.png[]
[start=2]
1. In the Select Library panel, shown above, browse to the folder where you downloaded JDom, and then select ``jdom.jar`` and ``LICENSE.txt.`` Click Next.
[start=3]
1.
In the Name and Location panel, accept all the defaults. You should see the following:
image::images/feedreader_65-lib-wiz3.png[]
NOTE: The library wrapper module project will be stored within the application project. You could also store it somewhere else, but for versioning purposes it is a good idea to put it within the application project. Therefore, the ``feedreader-suite`` application project is selected in the Add to Module Suite drop-down.
Click Next.
[start=4]
1. In the Basic Module Configuration panel, type ``org.jdom`` as the code name base and leave all the other defaults unchanged. You should see the following:
image::images/feedreader_65-lib-wiz4.png[]
Click Finish.
The new library wrapper module project opens in the IDE and displays in the Projects window. You should now see the following in the Projects window:
image::images/feedreader_65-lib-wiz2.png[]
[start=5]
1. Return to step 1 of this section and create a library wrapper module project for Rome. Use code name base "org.rome" and accept all the other defaults.
[start=6]
1. Return to step 1 of this section and create a library wrapper module project for Rome Fetcher. Use code name base "org.fetcher" and accept all the other defaults.
You now have an application skeleton, with three library wrapper module projects, providing many useful Java classes that you will be able to make use of throughout this tutorial.
=== Creating the Module Project
In this section, we create a project for the functionality that our application will provide. The project will make use of the classes made available by the library wrapper modules that we created in the previous section.
[start=1]
1. Right-click the Modules node in the application project in the Projects window, as shown below, and click Add New:
image::images/feedreader_65-module-project.png[]
When you do so, you should see the following:
image::images/feedreader_65-module-wiz.png[]
[start=2]
1. In the Name and Location panel, shown above, type ``FeedReader`` in Project Name. Accept all the other defaults. Click Next.
[start=3]
1. In the Basic Module Configuration panel, type ``org.myorg.feedreader`` in Code Name Base.
[start=4]
1. Select "Generate XML Layer". Leave the locations of both the localizing bundle and the XML layer file so that they will be stored in a package with the name ``org/myorg/feedreader`` . You should now see the following:
image::images/feedreader_69-module-wiz-1.png[]
Click Finish.
The IDE creates the FeedReader project. The project contains all of the module's sources and project metadata, such as the project's Ant build script. The project opens in the IDE. You can view its logical structure in the Projects window (Ctrl-1) and its file structure in the Files window (Ctrl-2). The Projects window should now show the following:
image::images/feedreader_69-module.png[]
You have now created the source structure of your new application. In the next section, we will begin adding some code.
== Creating the Feed Reader Window
In this section you use the Window wizard to generate files that create a custom windowing component and an action to invoke it. The wizard also registers the action as a menu item in the ``layer.xml`` configuration file and adds entries for serializing the windowing component. Right after finishing this section, you are shown how to try out the files that the Window wizard generates for you.
[start=1]
1. Right-click the ``FeedReader`` project node and choose New > Other. Under Categories, select Module Development. Under File Types, select Window, as shown below:
image::images/feedreader_69-windowcomp-wiz.png[]
Click Next.
[start=2]
1. In the Basic Settings panel, select ``explorer`` in the drop-down list and click Open on Application Start, as shown below:
image::images/feedreader_69-windowcomp-wiz2.png[]
Click Next.
[start=3]
1. In the Name and Location panel, type Feed as the Class Name Prefix and browse to the location where you saved ``rss16.gif (
image::images/feedreader_rss16.gif[]).`` The GIF file will be shown in the menu item that invokes the action. You should now see the following:
image::images/feedreader_65-windowcomp-wiz3.png[]
Click Finish.
The following is now shown in the Projects window:
image::images/feedreader_69-windowcomp.png[]
The IDE has created the following new files:
* ``FeedTopComponent.java.`` Defines the Feed Window.
* ``FeedTopComponentSettings.xml.`` Specifies all the interfaces of the ``org.myorg.feedreader`` rich-client application. Enables easy lookup of instances, without the need to instantiate each. Avoids the need to load classes or create objects and therefore improves performance. Registered in the ``Windows2/Components`` folder of the ``layer.xml`` file.
* ``FeedTopComponentWstcref.xml.`` Specifies a reference to the component. Enables the component to belong to more than one mode. Registered in the ``Windows2/Modes`` folder of the ``layer.xml`` file.
The IDE has modified the following existing files:
* ``project.xml.`` Two module dependencies have been added, ``Utilities API`` (click link:http://bits.netbeans.org/dev/javadoc/org-openide-util/overview-summary.html[here ] for Javadoc) and ``Window System API`` (click link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/overview-summary.html[here] for Javadoc).
* ``Bundle.properties.``
Three key-value pairs have been added:
* ``CTL_FeedAction.`` Localizes the label of the menu item, defined in the ``layer.xml`` file.
* ``CTL_FeedTopComponent.`` Localizes the label of ``FeedTopComponent.java`` .
* ``HINT_FeedTopComponent.`` Localizes the tooltip of ``FeedTopComponent.java`` .
Finally, three folders have been added to the ``layer.xml`` file:
* ``<Actions>``
Registers the link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/TopComponent.html#openAction(org.openide.windows.TopComponent,%20java.lang.String,%20java.lang.String,%20boolean)[openAction] provided by the TopComponent class as an Action in the Window folder. The openAction requires three parameters: the TopComponent that it should open, a display name, and an icon.
* ``<Menu>``
Registers the Action defined above as a menu item in the Window menu.
* ``<Windows2> `` Registers the ``FeedTopComponentSettings.xml`` file, which is used for looking up the windowing component.
Registers the component reference ``FeedTopComponentWstcref.xml`` file in the "explorer" area.
At this point, the ``layer.xml`` file should have this content:
[source,xml]
----
<folder name="Actions">
<folder name="Window">
<file name="org-myorg-feedreader-FeedAction.instance">
<attr name="component" methodvalue="org.myorg.feedreader.FeedTopComponent.findInstance"/>
<attr name="displayName" bundlevalue="org.myorg.feedreader.Bundle#CTL_FeedAction"/>
<attr name="iconBase" stringvalue="org/myorg/feedreader/rss16.gif"/>
<attr name="instanceCreate" methodvalue="org.openide.windows.TopComponent.openAction"/>
</file>
</folder>
</folder>
<folder name="Menu">
<folder name="Window">
<file name="FeedAction.shadow">
<attr name="originalFile" stringvalue="Actions/Window/org-myorg-feedreader-FeedAction.instance"/>
</file>
</folder>
</folder>
<folder name="Windows2">
<folder name="Components">
<file name="FeedTopComponent.settings" url="FeedTopComponentSettings.xml"/>
</folder>
<folder name="Modes">
<folder name="explorer">
<file name="FeedTopComponent.wstcref" url="FeedTopComponentWstcref.xml"/>
</folder>
</folder>
</folder>
----
== Trying Out the Application
Without having typed a single line of code, you can already take your application for a spin. Trying it out means deploying the modules to the NetBeans Platform and then checking to see that the empty Feed Window displays correctly.
[start=1]
1. In the Projects window, right-click the ``feedreader-suite`` project.
[start=2]
1. Choose Run.
The application starts up. You see a splash screen. Then the application opens and displays the new Feed Window, as an explorer window, shown below:
image::images/feedreader_65-feedreader-1.png[]
NOTE: What you now have is an application consisting of the following modules:
* The modules provided by the NetBeans Platform, for bootstrapping the application, lifecycle management, and other infrastructural concerns.
* The three library wrapper modules that you created in this tutorial.
* The FeedReader functionality module that you created in this tutorial, for providing the Feed window.
In the application's Window menu, you should see the new menu item, which you can use for opening the Feed window, if it is closed.
As you can see, without having done any coding, we have a complete application. It doesn't do much yet, but the entire infrastructure exists and works as one would expect. Next, we begin using some of the NetBeans APIs, to add code to our application.
== Adding Code to the Application
Now that you have laid the basis for your application, it's time to begin adding your own code. Before doing so, you need to specify the application's dependencies. Dependencies are modules that provide the NetBeans APIs that you will extend or implement. Then, you will use the New File wizard and the Source Editor to create and code the classes that make up the Feed Reader application.
=== Specifying the Application's Dependencies
You need to subclass several classes that belong to the NetBeans APIs. The classes belong to modules that need to be declared as dependencies of your Feed Reader application. Use the Project Properties dialog box for this purpose, as explained in the steps below.
[start=1]
1. In the Projects window, right-click the ``FeedReader`` project and choose Properties. In the Project Properties dialog box, click Libraries. Notice that some APIs have already been declared as Module Dependencies, thanks to the Window wizard you used earlier.
[start=2]
1. Click Add Dependency. You will need the following APIs. Some have been added by the Window wizard. Add the others yourself:
[source,java]
----
Actions APIs
Datasystems API
Dialogs API
Explorer and Property Sheet API
File System API
Lookup
Nodes API
rome
rome-fetcher
Settings API
UI Utilities API
Utilities API
Window System API
----
You should now see the following:
image::images/feedreader_69-proj-props-2.png[]
Click OK to exit the Project Properties dialog box.
[start=3]
1. Expand the ``FeedReader`` project's Libraries node and notice the list of modules that are now available to this project:
image::images/feedreader_69-add-lib5.png[]
=== Setting Dependencies Between Library Wrapper Modules
Now that we have set dependencies on the NetBeans API modules that we will use, let's also set dependencies between our library wrapper modules. For example, the Rome JAR makes use of classes from the JDom JAR. Now that these are wrapped in separate library wrapper modules, we need to specify the relationship between the JARs via the library wrapper module's Project Properties dialog box.
[start=1]
1. First, lets make Rome dependent on JDom. Right-click the Rome library wrapper module project in the Projects window and choose Properties. In the Project Properties dialog box, click Libraries and then click Add Dependency. Add ``jdom`` . You should now see the following:
image::images/feedreader_65-props-jdom.png[]
Click OK to exit the Project Properties dialog box.
[start=2]
1. Finally, since Rome Fetcher depends on both Rome and JDom, you need to make Rome Fetcher dependent on Rome, as shown below:
image::images/feedreader_65-props-rome.png[]
Because Rome already depends on JDom, you do not need to make Rome Fetcher dependent on JDom.
=== Creating the RssFeeds Folder
You will use the IDE's user interface to add a folder to the ``layer.xml`` file. The folder will contain our RSS feed objects. Later, you will add code to ``FeedTopComponent.java`` , which was created for you by the Window wizard, to view the content of this folder.
[start=1]
1. In the Projects window, expand the ``FeedReader`` project node and then expand the XML Layer node. You should see the following nodes:
* ``<this layer>.`` Exposes the folders provided by the current module. For example, as you can see below, the FeedReader module provides folders named Actions, Menu, and Windows2, as discussed earlier in this tutorial:
image::images/feedreader_69-feedfolder-1.png[]
* ``<this layer in context>. `` Exposes all the folders available to the entire application. We will look at this node later in this tutorial.
[start=2]
1. Right-click the ``<this layer>`` node and choose New > Folder.
[start=3]
1. Type ``RssFeeds`` in the New Folder dialog box. Click OK. You now have a new folder, as shown below:
image::images/feedreader_69-feedfolder-3.png[]
[start=4]
1. Double-click the node for the ``layer.xml`` file so that it opens in the Source Editor. Notice that this entry has been added: ``<folder name="RssFeeds"/>``
=== Creating the Feed Object
Next you create a simple POJO that encapsulates a URL and its associated Rome feed.
[start=1]
1. Right-click the ``FeedReader`` project node, choose New > Java Class.
[start=2]
1. Name the class ``Feed`` and select ``org.myorg.feedreader`` in the Package drop-down. Click Finish.
[start=3]
1. In the Source Editor, replace the default ``Feed`` class with the following:
[source,java]
----
public class Feed implements Serializable {
private static final long serialVersionUID = 1L;
private static final FeedFetcher FEED_FETCHER =
new HttpURLFeedFetcher(HashMapFeedInfoCache.getInstance());
private transient SyndFeed syndFeed;
private final URL url;
private String name;
public Feed(URL url) {
this.url = url;
name = url.toExternalForm();
}
public URL getURL() {
return url;
}
public SyndFeed getSyndFeed() throws IOException {
if (syndFeed == null) {
try {
syndFeed = FEED_FETCHER.retrieveFeed(url);
String title = syndFeed.getTitle();
if (title != null) {
name = title;
}
} catch (Exception ex) {
throw (IOException) new IOException(ex.toString()).initCause(ex);
}
}
return syndFeed;
}
@Override
public String toString() {
return name;
}
}
----
A lot of code is underlined, because you have not declared their packages. You do this in the next steps.
Take the following steps to reformat the file and declare its dependencies:
[start=1]
1. Press Alt-Shift-F to format the code.
[start=2]
1.
Press Ctrl-Shift-I and make sure the following import statements are selected:
image::images/feedreader_65-fix-imports-1.png[]
Click OK, and the IDE adds the following import statements to the class:
[source,java]
----
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
----
All the red underlining should now have disappeared. If not, do not continue with this tutorial until you have solved the problem.
=== Extending the Feed Window
In this section, we use a NetBeans Swing component called `` link:http://bits.netbeans.org/dev/javadoc/org-openide-explorer/org/openide/explorer/view/BeanTreeView.html[BeanTreeView]`` to display a hierarchy of feeds in our ``TopComponent`` .
[start=1]
1. Double-click ``FeedTopComponent.java`` and then click the Source button, so that the ``TopComponent`` opens in the Source Editor.
[start=2]
1. Type ``implements link:http://bits.netbeans.org/dev/javadoc/org-openide-explorer/org/openide/explorer/ExplorerManager.Provider.html[ExplorerManager.Provider]`` at the end of the class declaration.
[start=3]
1. Press Alt-Enter in the line and click on the suggestion. The IDE adds an import statement for the required package `` link:http://bits.netbeans.org/dev/javadoc/org-openide-explorer/org/openide/explorer/ExplorerManager.html[org.openide.explorer.ExplorerManager]`` .
[start=4]
1. Press Alt-Enter again and click on the suggestion. The IDE implements the abstract method ``getExplorerManager()`` .
[start=5]
1. Type ``return manager;`` in the body of the new ``getExplorerManager()`` method. Press Alt-Enter in the line and let the IDE create a field called ``manager`` for you. Replace the default definition with this one:
[source,java]
----
private final ExplorerManager manager = new ExplorerManager();
----
[start=6]
1. Right below the field declaration in the previous step, declare this one:
[source,java]
----
private final BeanTreeView view = new BeanTreeView();
----
[start=7]
1. Finally, add the following code to the end of the constructor:
[source,java]
----
setLayout(new BorderLayout());
add(view, BorderLayout.CENTER);
manager.setRootContext(new RootNode());
ActionMap map = getActionMap();
map.put("delete", ExplorerUtils.actionDelete(manager, true));
associateLookup(ExplorerUtils.createLookup(manager, map));
----
Now a lot of code is underlined, because you have not declared their associated packages. You do this in the next steps.
Take the following steps to reformat the file and declare its dependencies:
[start=1]
1. Press Alt-Shift-F to format the code.
[start=2]
1. Press Ctrl-Shift-I and the IDE adds several import statements below the package statement. The complete list of import statements should be as follows:
[source,java]
----
import java.awt.BorderLayout;
import java.util.logging.Logger;
import javax.swing.ActionMap;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.explorer.view.BeanTreeView;
----
[start=3]
1. Note that the line ``manager.setRootContext(new RootNode());`` is still underlined in red, because you have not created ``RootNode.java`` yet. This you will do in the next subsection. All other red underlining should now have disappeared. If not, do not continue with this tutorial until you have solved the problem.
=== Creating the Root Node
The top level node of our Feed Reader is provided by the RootNode class. The class extends `` link:http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/nodes/AbstractNode.html[AbstractNode]`` , which is the generic convenience class for creating your own Nodes. It creates its child Nodes by using the 'RssFeeds' folder that you created in the "Creating the RssFeeds Folder" section earlier in this tutorial. In addition to child Nodes, the RootNode has a display name and an Action for creating new feeds.
Take the following steps to create the RootNode class:
[start=1]
1. Create ``RootNode.java`` in the ``org.myorg.feedreader`` package.
[start=2]
1. Replace the default class with the following:
[source,java]
----
public class RootNode extends link:http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/nodes/AbstractNode.html[AbstractNode] {
public RootNode() {
super(Children.create(new FeedChildFactory(), false));
setDisplayName(NbBundle.getMessage(RootNode.class, "FN_title"));
}
@Override
public Action[] getActions(boolean popup) {
DataFolder rssFeedsFolder = DataFolder.findFolder(FileUtil.getConfigFile("RssFeeds"));
return new Action[]{new AddFeedAction(rssFeedsFolder)};
}
private static class FeedChildFactory extends ChildFactory<Feed> implements LookupListener {
private Result<Feed> result;
FeedChildFactory() {
result = Lookups.forPath("RssFeeds").lookupResult(Feed.class);
result.addLookupListener(this);
}
@Override
public void resultChanged(LookupEvent le) {
refresh(true);
}
@Override
protected boolean createKeys(List<Feed> list) {
list.addAll(result.allInstances());
return true;
}
@Override
protected Node createNodeForKey(Feed key) {
OneFeedNode ofn = null;
try {
ofn = new OneFeedNode(key);
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return ofn;
}
}
}
----
Several red underline markings remain in the class, because you have not yet created the OneFeedNode class and the AddFeedAction class.
=== Creating the Add Feed Action
In this section, we create the menu item that adds new feeds. As you can see in the previous section, the Add Feed Action is bound to the context-menu of the Root Node.
To create this class, take the following steps:
[start=1]
1. Create ``AddFeedAction.java`` in the ``org.myorg.feedreader`` package.
[start=2]
1.
Replace the default class with the following:
[source,java]
----
class AddFeedAction extends AbstractAction {
private DataFolder folder;
public AddFeedAction(DataFolder df) {
folder = df;
putValue(Action.NAME, NbBundle.getMessage(RootNode.class, "FN_addbutton"));
}
@Override
public void actionPerformed(ActionEvent ae) {
link:https://bits.netbeans.org/dev/javadoc/org-openide-dialogs/org/openide/NotifyDescriptor.html[NotifyDescriptor].InputLine nd = new NotifyDescriptor.InputLine(
NbBundle.getMessage(RootNode.class, "FN_askurl_msg"),
NbBundle.getMessage(RootNode.class, "FN_askurl_title"),
NotifyDescriptor.OK_CANCEL_OPTION,
NotifyDescriptor.PLAIN_MESSAGE);
Object result = link:http://bits.netbeans.org/dev/javadoc/org-openide-dialogs/org/openide/DialogDisplayer.html[DialogDisplayer].getDefault().notify(nd);
if (result.equals(NotifyDescriptor.OK_OPTION)) {
String urlString = nd.getInputText();
URL url;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
String message = NbBundle.getMessage(RootNode.class, "FN_askurl_err", urlString);
Exceptions.attachLocalizedMessage(e, message);
Exceptions.printStackTrace(e);
return;
}
try {
checkConnection(url);
} catch (IOException e) {
String message = NbBundle.getMessage(RootNode.class, "FN_cannotConnect_err", urlString);
Exceptions.attachLocalizedMessage(e, message);
Exceptions.printStackTrace(e);
return;
}
Feed f = new Feed(url);
FileObject fld = folder.getPrimaryFile();
String baseName = null;
try {
baseName = f.getSyndFeed().getTitle();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
try {
FileObject writeTo = fld.createData(baseName, "ser");
FileLock lock = writeTo.lock();
try {
ObjectOutputStream str = new ObjectOutputStream(writeTo.getOutputStream(lock));
try {
str.writeObject(f);
} finally {
str.close();
}
} finally {
lock.releaseLock();
}
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
}
private static void checkConnection(final URL url) throws IOException {
InputStream is = url.openStream();
is.close();
}
}
----
=== Creating the Feed Node
Here we are concerned with the container for the article nodes, as shown below for the 'NetBeans Highlights' node:
image::images/feedreader_60-actions2.png[]
As can be seen, each of these nodes has a display name, retrieved from the feed, an icon, and a Delete menu item.
Take the following steps to create this class:
[start=1]
1. Create ``OneFeedNode.java`` in the ``org.myorg.feedreader`` package.
[start=2]
1. Replace the default class with the following:
[source,java]
----
public class OneFeedNode extends link:http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/nodes/AbstractNode.html[AbstractNode] {
OneFeedNode(Feed feed) throws IOException, IntrospectionException {
super(Children.create(new EntryChildFactory(feed.getSyndFeed()), false),
Lookups.singleton(feed));
}
@Override
public String getDisplayName() {
String displayName = null;
Feed feed = getLookup().lookup(Feed.class);
try {
displayName = feed.getSyndFeed().getTitle();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return displayName;
}
@Override
public Image getIcon(int type) {
return ImageUtilities.loadImage("org/myorg/feedreader/rss16.gif");
}
@Override
public Image getOpenedIcon(int type) {
return getIcon(0);
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() throws IOException {
Feed feed = getLookup().lookup(Feed.class);
String id = feed.getSyndFeed().getTitle();
FileObject folder = FileUtil.getConfigFile("RssFeeds");
FileObject[] kids = folder.getChildren();
for (FileObject fileObject : kids) {
if (fileObject.getName().equals(id)){
fileObject.delete();
}
}
}
@Override
public Action[] getActions(boolean context) {
Action[] actions = null;
try {
actions = new Action[]{(Action) DataObject.find(
FileUtil.getConfigFile("Actions/Edit/org-openide-actions-DeleteAction.instance"))
.getLookup().lookup(InstanceCookie.class).instanceCreate()};
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (ClassNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
return actions;
}
private static class EntryChildFactory extends ChildFactory<SyndEntry> {
private final SyndFeed feed;
public EntryChildFactory(SyndFeed feed) {
this.feed = feed;
}
@Override
protected boolean createKeys(List<SyndEntry> list) {
list.addAll(feed.getEntries());
return true;
}
@Override
protected Node createNodeForKey(SyndEntry key) {
OneEntryNode oen = null;
try {
oen = new OneEntryNode(key);
} catch (final IntrospectionException ex) {
Exceptions.printStackTrace(ex);
}
return oen;
}
}
}
----
Several red underline markings remain in the class, because we have not created our ``FeedChildren`` class yet.
=== Creating the Entry Node
Finally, we deal with the lowest level nodes, those that represent articles provided by the feed.
To create this class, take the following steps:
[start=1]
1. Create ``OneEntryNode.java`` in the ``org.myorg.feedreader`` package.
[start=2]
1. Replace the default class with the following:
[source,java]
----
class OneEntryNode extends link:http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/nodes/BeanNode.html[BeanNode] {
private SyndEntry entry;
public OneEntryNode(SyndEntry entry) throws IntrospectionException {
super(entry, Children.LEAF, Lookups.singleton(new OpenEntryCapability(entry)));
this.entry = entry;
}
/** Using HtmlDisplayName ensures any HTML in RSS entry titles are
* properly handled, escaped, entities resolved, etc. */
@Override
public String getHtmlDisplayName() {
return entry.getTitle();
}
/** Making a tooltip out of the entry's description */
@Override
public String getShortDescription() {
return entry.getDescription().getValue();
}
@Override
public Action[] getActions(boolean context) {
Action[] actions = null;
try {
actions = new Action[]{(Action) DataObject.find(
FileUtil.getConfigFile("Actions/Edit/org-openide-actions-OpenAction.instance"))
.getLookup().lookup(InstanceCookie.class).instanceCreate()};
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (ClassNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
return actions;
}
/** Specifying what should happen when the user double-clicks the node */
@Override
public Action getPreferredAction() {
return getActions(false)[0];
}
/** Specifying what should happen when the user invokes the Open action */
private static class OpenEntryCapability implements link:http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/cookies/OpenCookie.html[OpenCookie] {
private final SyndEntry entry;
OpenEntryCapability(SyndEntry entry) {
this.entry = entry;
}
@Override
public void open() {
try {
URLDisplayer.getDefault().showURL(new URL(entry.getUri()));
} catch (MalformedURLException mue) {
Exceptions.printStackTrace(mue);
}
}
}
}
----
Above, you use the NetBeans URLDisplayer class to open an entry in the Swing browser. See the completed sample (referred to in the Troubleshooting section below) for code that lets you create your own TopComponent, containing a JEditorPane for displaying your entries.
=== Localizing the RssNode Class
[start=1]
1. Open the ``FeedReader`` module's ``Bundle.properties`` file.
[start=2]
1. Add the following key-value pairs:
[source,java]
----
FN_title=RSS/Atom Feeds
FN_addbutton=Add
FN_askurl_title=New Feed
FN_askurl_msg=Enter the URL of an RSS/Atom Feed
FN_askurl_err=Invalid URL: {0}|
FN_askfolder_msg=Enter the folder name
FN_askfolder_title=New Folder
----
Here is an explanation of the new key-value pairs, which localize strings defined in ``RssNode.java`` :
* * FN_title.* Localizes the label of the highest node in the Feed Window.
Localization of user interface for adding a feed:
* * FN_addbutton.* Localizes the label of the Add menu item that appears in the highest node's pop-up.
* * FN_askurl_title.* Localizes the title of the New Feed dialog box.
* * FN_askurl_msg.* Localizes the message that appears in the New Feed dialog box.
* * FN_askurl_err.* Localizes the error string that is displayed if the URL is invalid.
== Branding the Application
Now that you are at the end of the development cycle, while you are wrapping up the application, you are concerned with the following questions:
* What should be the title displayed in the application's titlebar?
* What should the user see when starting up my application? A progress bar? A splash screen? Both?
* When my application starts up, what should be displayed in the title bar?
* Do I need all the menus and toolbar buttons that the NetBeans Platform provides by default?
These questions relate to branding, the activity of personalizing an application built on top of the NetBeans Platform. The IDE provides a panel in the Project Properties dialog box of application projects to help you with branding.
[start=1]
1. Right-click the ``feedreader-suite`` project node (not the ``FeedReader`` project node) and choose Branding. The Branding Editor opens.
[start=2]
1. In the Basic panel, type ``Feed Reader Application`` in Application Title. The value in the application title field sets the text displayed in the application's title bar.
[start=3]
1. Click Browse to browse to the ``rss16.gif`` icon (
image::images/feedreader_rss16.gif[]). The icon will be displayed in the Help > About dialog box.
You should now see the following:
image::images/feedreader_69-branding-1.png[]
[start=4]
1. In the Splash Screen panel, click Browse to browse to ``splash.gif`` . Optionally, change the color and text size of the progress bar. Or, if you do not want a progress bar, unselect Enabled.
You should now see the following:
image::images/feedreader_69-branding-2.png[]
[start=5]
1. In the Window System panel, you can limit the behavior of the windows in your application:
image::images/feedreader_69-branding-3.png[]
Click OK.
[start=6]
1. Right-click the application's "Modules" node and create a new module called "Branding". In the Module Project wizard, make sure to specify that a ``layer.xml`` file should be created, and then, once the module is created, add these entries to its ``layer.xml`` file:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "https://netbeans.org/dtds/filesystem-1_1.dtd">
<!--
This is a `branding' layer.
In this case, it's just hiding menu items and toolbars we don't want.
-->
<filesystem>
<!-- hide unused toolbars -->
<folder name="Toolbars">
<folder name="File_hidden"/>
<folder name="Edit_hidden"/>
</folder>
<!-- hide unused menu items and menus -->
<folder name="Menu">
<folder name="File">
<file name="org-openide-actions-SaveAction.instance_hidden"/>
<file name="org-openide-actions-SaveAllAction.instance_hidden"/>
<file name="org-netbeans-core-actions-RefreshAllFilesystemsAction.instance_hidden"/>
<file name="org-openide-actions-PageSetupAction.instance_hidden"/>
<file name="org-openide-actions-PrintAction.instance_hidden"/>
</folder>
<folder name="Edit_hidden"/>
<folder name="Tools_hidden"/>
</folder>
</filesystem>
----
Run the application and notice that your title bar, splash screen, menus, and toolbar have all been customized.
== Distributing the Application
The IDE uses an Ant build script to create a distribution of your application. The build script was created for you when you created the project.
[start=1]
1. In the Projects window, right-click the ``FeedReader Application`` project node and choose Build ZIP Distribution. The Output window (Ctrl-4) shows you where the ZIP distribution is created.
[start=2]
1. In your filesystem, find the ``feedreader.zip`` distribution in the ``dist`` folder in your project directory. Unzip it. Launch the application, which you will find in the ``bin`` folder. During start up, the splash screen is displayed. When the application has started up, go to the Help > About dialog box and notice the icon and splash screen that you specified in the <<branding,Branding the Application>> section.
When it is up and running, the Feed Reader application displays the RSS/Atom Feeds window, containing a node called RSS/Atom Feeds.
Congratulations! You have completed the NetBeans Platform Feed Reader tutorial.
== Troubleshooting
If you encounter problems during this tutorial, get the completed sample here, in the New Project wizard (Ctrl-Shift-N):
image::images/feedreader_69-sample.png[]
NOTE: The completed sample provided by the New Project wizard, above, is slightly different to the code used in this tutorial. Though the end result is the same to the user of the application, the source code in the completed sample is different mainly in that its Nodes extend the FilterNode class, rather than the AbstractNode class used throughout this tutorial.
link:http://netbeans.apache.org/community/mailing-lists.html[Send Us Your Feedback]