DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Tools Topics

article thumbnail
War Fighter on the NetBeans Platform
Agile Client is a NetBeans Platform application developed by Northrop Grumman in partnership with the Defense Information System Agency (DISA). It brings the war fighter a 3-D common operational picture (COP) workstation designed for greater efficiency and mission effectiveness. This efficiency is empowered by its ability to be installed and upgraded on demand. Its mission effectiveness is permitted by the ability to tailor the user’s application with only the capabilities and data they need for their specific mission. The interview below is with Charlie Black, who runs the team using the NetBeans Platform at Northrop Grumman. Hi Charlie, who are you and what do you do? My name is Charlie Black and I have worked for Northrop Grumman since 1998. Over that time I have been working as a software engineer on a Global Command and Control System (GCCS) program supporting data fusion, dissemination and display technologies. I am currently running a team that uses the NetBeans Platform for a product called Agile Client, which is now part of GCCS. Team: Greg Gibsen, Charlie Black, Brice Bingman and James Maloney What are the technical specifics of Agile Client? The Agile Client uses several commercial off the shelf (COTS) products that make up its core feature set: It uses the NetBeans Platform, which provides the services common to almost all large desktop applications: window management, menus, settings and storage, an update manager, and file access. For map and visual rendering, Agile Client uses NASA’s World Wind product, enabling the retrieval of geospatial data via open standards that are embraced by the international community. For providing data services, Agile Client uses Gemstone GemFire, which provides ultra low-latency distributed caching with high availability and no data loss. Here's a screenshot of Agile Client in action: Agile Client is also integrated with GCCS COP Collaboration. This allows one or more war fighters to work simultaneously on a single map. They can collaboratively create GCCS Overlays, share files and communicate by instant messaging and Voice over IP. This is all done with the Extensible Messaging and Presence Protocol (XMPP), which is a set of open XML technologies for presence and real-time communication. What are the two or three things that you are happiest about, relating to this application? Since the NetBeans Platform is based on standard Java UI technologies, we are able to integrate existing Java windows directly, without any issues. This has accelerated our development substantially. Using Sun UI guidelines and reusable components in any new development, we have actually made an application that is embraced by our customers as looking modern. Underneath this application is the NetBeans Platform. Why? The main reason for going with a rich client platform such as the NetBeans Platform was the module system. It will help with our deployment of a large scale application on an enterprise level. I can envision a future where there will be hundreds of modules deployed in the application. Then, using the update center, we can keep those applications up to date. How did you find out about it? When? Why did you start using it? We have known about NetBeans for a long time. However it was used mainly as a developer tool. It wasn’t until NetBeans 6.0 that we started using it as our platform for basing new work on. What are the main things you gained from the NetBeans Platform? Using the NetBeans Platform, we decreased our time to develop our application by using existing window components. Also, the automatic updates are integral to our final application. In the past, it would have taken months or even years to get a patch to our end users. That said, the most significant gain has been the community! Which APIs have you used? Which ones are your favorites and why? We actually use several API sets, with just about every one enabled. The Windows API is incredible, as that is what the end user sees that allows them to tailor their display. With the customization of toolbars, the end-user can make their own ad-hoc workflow. The other API that we have been impressed with is the Nodes API, providing a view to our layers on the 3D globe. What could be improved about the NetBeans Platform? In our community OSGi is a big item, so if NetBeans could formally handle them for module deployment that would be a monumental win. Imagine a module of business intelligence that can be deployed in Glassfish and in the NetBeans Platform. I realize that some work has already been done in this area, but to see it on an official roadmap would be remarkable. After that, the Properties window could use something to make it more appealing. We are thinking of dropping our own Properties window in favor of the NetBeans implementation. Overall, we have been really happy with the NetBeans Platform and the features it provides. Do you have some tips and tricks for a complete newbie, who is getting started with the NetBeans Platform? When new team members join, I customarily distribute to them a book on the NetBeans Platform. For further aid, I point them to the NetBeans Developer Wiki. There is an amazing amount of information available, detailing not only what the NetBeans Platform can do for you, but what can you do with the NetBeans Platform as well. If more assistance is needed, I recommend just asking the community. Someone can usually help in answering any level of questions. How have customers responded to this application and what are your plans for its future? Our customers are very pleased with the application and they are moving forward with plans to base future work on the Agile Client. Internally, we have made Agile Client with the goal of releasing portions back to the community. However, before that can be done, we have to figure out what that means from our customer’s standpoint.
March 31, 2009
by Geertjan Wielenga
· 37,563 Views
article thumbnail
Wicket Tutorial Series: Setting Up the Project
Each day this week will feature a new article with an in-depth look at the creation process behind setting up a Java project and implementing the frontend with Apache Wicket. Wicket is a Java web application framework which allows “Designers” (people good with Dreamweaver) and “Developers” (people good with Java and Databases) to collaborate on a project with minimal chances of stepping on each other’s toes or wearing each other’s hats. The beauty of Wicket is that it uses plain xhtml pages as it’s templating markup. This means that html pages can be loaded into Dreamweaver (or whatever tool the Designer is comfortable with) and they will look very close to the same as they would when rendered on the deployment web server. Workflow The basic workflow involved in creating and maintaining html rendered by Wicket is as follows: The Designer creates the html for the website and fleshes it out with “mock” sections. For instance in the application we intend to create during our Five Days of Wicket will be a pastebin application called “Mystic Paste”. In our application we’ll have an “Add Code to Mystic Paste” page, mock data might include some user created content in the textarea of the page. All css/images, etc… are setup such that if they were to be put on a webserver, everything would work. The Developer needs to flesh out the dynamic areas of the webpage, that is, he needs to instruct Wicket where it will need to show information from the server. The developer does this by decorating the designer’s html page with special Wicket tags and attributes. Because these tags and attributes are just considered part of another namespace separate from xhtml’s, editors like Dreamweaver and browsers will simply ignore them - It is important to note: The developer will still keep the “mocked” sections of the page intact, this is so the page renders and looks fleshed out on its own. The mocked sections will be replaced by real data when rendered by Wicket. The Developer hands the file back to the Designer. The Designer is free to make further edits, so long as he/she does not remove or manipulate the Wicket tags and attributes present in the file. If the Designer does need to remove any Wicket tags or attributes, they need to consult the Developer as such an action will “break” the webpage when Wicket renders it. Example Wicket Page Here is an example of a Wicket page. This example was taken from Manning Publishing’s book “Wicket in Action”: ... Gouda Gouda is a Dutch... $1.99 add to cart Emmental Emmental is a Swiss che... $2.99 add to cart ... This looks almost 100% like a normal webpage would look, the only difference is the addition of the “wicket:XXX” attributes and tags sprinkled through the document. The parts of the document using the special Wicket namespace modifiers will be replaced/removed in the final markup when Wicket renders the page to the user’s browser. Notice the “” element? This is where your designer can put a “mocked” version of what that area of the page should look like. You as a developer can take that mocked html and divide it out into a template that is dynamically driven from the backend. Here is how the final page looks if you were to simply load the page into a web browser (or Dreamweaver) from your hard drive: Preparing for Setup Deviating a bit from the Standard Wicket Convention One of the first things a developer notices when starting out with Wicket is the convention where Wicket likes having its html template files live at the same level and in the same packages as it’s Java source files. Sure you can jump through hoops to get Wicket to load the html template files from elsewhere but a nice compromise is to simply keep your html template files within the same package directory structure but in a source folder separate from the Java classes. Why? Well quite simply to keep your designers (Dreamweaver folks!) from having to grab Java source files along with the html files they are working on. It will just confuse them and clutter their directories. You can of course stick with the typical “Java source files along side html” convention if you wish, but I find it much cleaner to separate them during design time, and have Maven combine them only at build time into the target war (which it will gladly do automagically). Project Folder Structure . |-- pom.xml |-- src | `-- main | |-- filters | |-- java | | `-- com | | `-- mysticcoders | | `-- mysticpaste | | |-- model | | |-- persistence | | | |-- exception | | | |-- hibernate | | |-- services | | `-- web | | |-- ajax | | |-- pages | | |-- panels | | `-- servlet | |-- resources | | |-- com | | | `-- mysticcoders | | | `-- mysticpaste | | | |-- spring | | | `-- web | | | |-- ajax | | | |-- pages | | | `-- panels | | `-- log4j.properties | |-- sql | `-- webapp | |-- WEB-INF | |-- images | |-- js | `-- css src/main: maven builds source and resources from this directory to the main deployable target (i.e. our war file) filters: we keep a set of “filters” files that maven can use to interpolate variables at build time. What does this mean? It means that inside your configuration files, the files you use to setup database connections or file paths, you can insert variable place holders like ${db.host}. When maven does a build, it looks up the correct filter file to use and looks for the key=value part corresponding to “db.host” and inserts it into the configuration file for you. This ensures that you are able to configure your application per environment you deploy to (i.e. DEV, QA, PROD, etc…) by having different filter files with the same keys but different values. For more information see Maven’s documentation on filtering resource. java/*: this folder will contain all of the application’s source code. Everything from the database access code, wicket code and services code for the mysticpaste application (see below). model: all “domain” classes, that is, classes that represent the objects in the application. For mysticpaste you’ll see classes like “PasteItem” which represents an item pasted to the mysticpaste. persistence: at this level of the persistence package a list of interfaces will be kept. The interfaces comprise the basic access layer the services layer will use to save, retrieve and update items to/from the paste bin. exception: the peristence layer needs to tell the services layer when things have gone wrong. It does this via delcaring and throwing exceptions. hibernate: such is our case, our persistence interfaces will be implemented via the ORM known as Hibernate. This package will store all of the custom hibernate implementations and hibernate specific classes services: The services layer will be stored here. Both the generic interfaces and their implementation classes. The persistence layer will be injected via spring. web: this folder is where our Wicket classes will reside and it’s split into several category packages which are as follows: ajax: mysticpaste uses Ajax to render portions of its UI. The wicket classes which render the xml/html to be injected dynamically into the page are stored here. pages: standard Wicket page classes which are used throughout the application are stored here panels: reusable panel classes are stored here. Panels may be included within Wicket pages for sake of templating servlet: any run of the mill servlet code we need is stored here. A good example might be an ImageUploadServlet resources/*: the resources folder will hold our non-java based files. Noteably html files and spring confguration files spring: Holds any spring configuration files needed to wire the services and persistence layer web: this folder and all subfolders mirror the packages under src/main/java/…/web and hold the .html files that the Wicket page/panel classes use as their templates. As described above, a “standard” wicket application simply stores the .html files along side their Wicket classes under src/main/java/…/web, however we want to keep these files separate from the Java source so as to keep the directory our designers checkout from version control contianing only the files they need to work on. sql: any sql scripts we need to keep handy for building the mysticpaste database. webapp: this folder will keep the files which live at the base directory of our war file WEB-INF: where you keep your web.xml file images: any image resource, .gif/.png/.jpg files your webapp will reference js: javascript files your webapp will reference css: style sheets your webapp uses src/test/*: All files which reside under this folder are test classes and resources needed to support the tests. Maven will build everything under src/main/java and add it to the class path of the JUnit or TestNG classes you create. java: JUnit or TestNG test classes which will be run during a build resources: resource files which are needed to support the tests Getting Started Since we are using Maven as our build tool we can take advantage of the fact that the fine folks at the Wicket project have created a specialized “archetype“ which creates a skeleton web application complete with a folder structure which mimics roughly what we have outlined above and Maven pom.xml file used to build a war. The Wicket contributors have even gone one step further and have created a little web page which will, based off a few drop down options, generate the maven command you need to execute in order to create the boiler plate Wicket project. You can find this web page over on the Apache Wicket site under the “Quick Start” link. Copying the above Maven command creates a Skeleton Wicket Project To be precise, the command I used was: mvn archetype:create -DarchetypeGroupId=org.apache.wicket -DarchetypeArtifactId=wicket-archetype-quickstart -DarchetypeVersion=1.3.5 -DgroupId=com.mysticcoders -DartifactId=mysticpaste And I ended up with the following folder structure: . `-- mysticpaste |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mysticcoders | | |-- HomePage.html | | |-- HomePage.java | | `-- WicketApplication.java | |-- resources | | `-- log4j.properties | `-- webapp | `-- WEB-INF | `-- web.xml `-- test `-- java `-- com `-- mysticcoders |-- Start.java `-- TestHomePage.java Now obviously we’ll have to rearrange a few things, for instance I want my base package to be com.mysticcoders.mysticpaste, but that’s easy enough to do once we are in an IDE. For now, let’s test this example webapp out and see if it works. To do that switch into the mysticpaste directory (the directory that has pom.xml in it) and type the following: mvn jetty:run This will start up a Jetty webapp container running on port 8080 (if you have something running there already, use the -Djetty.port= option). Startup a webbrowser and navigate to http://localhost:8080/mysticpaste/ You should see: Your IDE Sooner or later you’re going to want to crack open your IDE and start hacking away. Maven makes this extremely easy by allowing you to create IDE specific project files based off of the Maven pom.xml file. Eclipse mvn eclipse:eclipse For eclipse you’ll also have to set the M2_REPO classpath variable for the workspace your project resides under. Do this by entering the following command: mvn -Declipse.workspace= eclipse:add-maven-repo IntelliJ IDEA mvn idea:idea -OR- in IDEA 7+ simply open the pom.xml file Netbeans Netbeans supports maven out of the box, just “Open Project” and choose the mysticpaste directory that contains the pom.xml file When generating the project files through Maven, the project is setup such that classpath entries point to your local Maven repository (i.e. ~/.m2/repository, or C:Documents and Settingsyourusername.M2repository on Windows). It also sets up src/main/java, src/main/resources as “source folders”. You may add other folders to the source folder list as per your IDE if needed, the only thing you have to remember is if you ever use mvn eclipse:clean followed by mvn eclipse:eclipse again, those other source folders will have to be readded through your IDE. Instead, you should add the source/resource folders directly to your pom.xml, this way they will be maintained. Spring The Mystic Paste application will use Spring, and really you should too. Unless you have been hiding under a rock or work in a corporate environment so lame as to which technologies newer than 2002 are forbidden you should learn to accept Spring as a defacto standard. Dependency injection for the win! We add the following to our pom.xml: org.apache.wicket wicket-spring-annot org.springframework spring org.springframework spring-test org.springframework spring-tx wicket-spring-annot: allows us to wire our Wicket application via handy dependency injection annotations (i.e. @SpringBean, see Wicket documentation for more detail) spring: is just the core spring libraries spring-test: is a set of Spring integration classes for Unit testing spring-tx: is the Spring Transaction Management api for declarative transactions web.xml additions for Spring In order for Spring to manage our Wicket application we need to setup the Wicket filter with a Spring-aware application factory. This allows us to wire our Wicket Application class in our applicationContext.xml file, which is really handy if you have a services and configuration settings you want to inject into the Wicket Application object so the rest of your application can access them. To do this, we change the original Wicket filter like so: wicket.mysticpaste org.apache.wicket.protocol.http.WicketFilter applicationFactoryClassName org.apache.wicket.spring.SpringWebApplicationFactory As well, we want our Spring context to be available to our webapp if ever there is a need for one of our pages to access the Spring managed beans directly: contextConfigLocation classpath:com/mysticcoders/mysticpaste/spring/applicationContext.xml org.springframework.web.context.ContextLoaderListener Hibernate Hibernate is our ORM of choice, it will allow us to persist and retrieve our model objects to and from the underlying database, whatever that database may be. We add the following to our pom.xml: org.hibernate hibernate-annotations c3p0 c3p0 commons-dbcp commons-dbcp javax.transaction jta 1.0.1B hibernate-annotations: used so we can annotate our model classes with mapping information, instead of having to create a separate mysticpaste.hbm.xml file. c3p0: provides a connection pooling library Hibernate can use commons-dbcp: another connection pooling library, we’ll add it as well and decide whether to use it or c3p0 later jta: this is the Java Transaction API which is needed by Hibernate (Hibernate provides an implementation of the API) web.xml additions for Hibernate To have a Hibernate Session open and ready for our webapplication during a Request Cycle we need to setup a Hibernate filter like so (otherwise, good luck getting lazy loading working!): open.hibernate.session.in.view org.springframework.orm.hibernate3.support.OpenSessionInViewFilter open.hibernate.session.in.view /* As the comment states above, make sure this filter-mapping exists *before* your wicket.mysticpaste filter or else it just plain won’t work. Database For the Mystic Paste we decided to use the freely available PostgreSQL. Adding support for PostgreSQL is very easy, unlike with some of the commercial DBMSes where you have to download and install their JDBC driver into your repository. To add support for Postgres, we simply add the following to our pom.xml: postgresql postgresql Servlets Regardless of which webapplication framework you choose there are just some times when a plain jane Servlet comes in really handy. If you have a need for Servlets and the Servlet must have access to the Wicket session add the following to your web.xml: wicket.session org.apache.wicket.protocol.http.servlet.WicketSessionFilter filterName wicket.mysticpaste And then, after your other filter-mappings add the following (assuming you mount your servlet-mappings under /servlet/): wicket.session /servlet/* Maven Filters and Profiles In order to build our Mystic Paste project for various environments (DEV/QA/PROD) we need to implement both Maven profiles and filters. Filters Filters allow you to place variables inside your configuration files and have those variables filled in durring build time. This is very handy for setting environment specific things such as database connection information. Enabling filters is quite easy, we open up the pom.xml file and find the section for and set the value for the element to true as follows: true src/main/resources . . . But for filtering to work, we need to specify a filters file. It’s not enough to specify only one filter file because we need to specify different filters per environment and we’ll do that by using Maven Profiles. Profiles To setup a profile, create a new set of elements following the section in your pom.xml file. Like so: DEV DEV DEV QA QA PROD PROD and just above your tag underneith your tag you would add the following elements: mysticpaste src/main/filters/filters-${env}.properties true src/main/resources src/main/filters will contain the following files. |-- pom.xml |-- src | `-- main | |-- filters | | `-- filters-DEV.properties | | `-- filters-QA.properties | | `-- filters-PROD.properties filters-DEV.properties jdbc.url=jdbc:postgresql://localhost:5432/mysticpaste jdbc.user=mysticpaste jdbc.password=password image.upload.path=/tmp/pasetbin/userimages image.upload.size.limit=4096K filters-PROD.properties jdbc.url=jdbc:postgresql://192.168.2.10:5432/mysticpaste jdbc.user=mysticpaste jdbc.password=CrYp71c image.upload.path=/mysticpaste/userimages image.upload.size.limit=4096K Now within any file under src/main/resources that has variables of the form ${variable.name} will have those variables replaced with the values specified in the proper filters file located under src/main/filters. For instance here is an example of a Spring applicationContext.xml file which will be interpolated with proper variables values at build time: applicationContext.xml To determine which filters file will be used depends on the profile chosen when building. For example, to build to production using the filters-PROD.properties we would execute the following: mvn clean deploy -P PROD The profile you use with the -P switch must match one of the values of the element for a profile. Conclusion Although it’s quite easy to get started with the Maven QuickStart project it is sometimes a bit frustrating putting some of the additonal pieces together. Building to several environments, setting up depenencies not included in the QuickStart project and strucuturing your project in an effort to make life easy for yourself as a developer and for your designer. I hope our Day 1 tutorial leaves you with a good sense of how a Wicket project is setup, now we can move onto coding the app! In the next four days we will be covering: Writing the Tests Designing the backend Designing the Wicket components Putting it all together Mystic Coders, LLC has been coding web magic since 2000. Mystic is a full-service Development Agency specializing in Enterprise development with Java. They are usually involved in developing enterprise-grade software for companies large and small, and have experience working in diverse industries, including b2b, b2c, and government-based projects. Mystic has done work with large companies such as LeapFrog, Nestlé, Harrah's Entertainment and the Los Angeles Conventions & Visitor's Bureau, among others. Andrew Lombardi, CTO of Mystic, is available for speaking engagements. For more about Mystic, check us out at http://www.mysticcoders.com
March 10, 2009
by Craig Tataryn
· 30,162 Views
article thumbnail
Using IntelliJ IDEA for NetBeans Platform Development
On jetbrains.com there's a rather impressive article entitled Using IntelliJ IDEA for Eclipse RCP development. Let's take a look at what the NetBeans Platform equivalent would look like. We'll start with one of the standard NetBeans Platform sample applications distributed with NetBeans IDE, the Paint Application. The application consists of an application module that provides a canvas for painting, with some 3rd party libraries wrapped into supporting modules. In other words, a very realistic example representing a real life scenario. We're going to (1) open that application into IntelliJ and then (2) deploy it from IntelliJ, with this result: In the picture above, take a look at the application structure, as well as the running application itself. That's what we're going to be creating in the steps that follow. I.e., we will make full use of the NetBeans Platform, while using IntelliJ to do so. Create the Application. Open NetBeans IDE and create the Paint Application, which you can find in the New Project dialog. Import the Application into IntelliJ. Open IntelliJ and choose File | New Project | Create project from scratch. Click Next. In "Project files location", set the "PaintApp" root folder. Type "PaintApp" in "Name". Click Next and keep clicking Next until you can click Finish. I.e., don't change any of the defaults. Now the application is open in IntelliJ. Add the NetBeans Platform to the Classpath. Right-click the main "PaintApp" node and choose "Module Settings". In Dependencies, create a new project library that contains all the JARs that you can find in the NetBeans installation directory's 'platform9' folder. Make sure to look in the 'core', 'lib', and 'modules' folders. You should end up with a very long list of JARs. Also make sure to add 'ColorChooser.jar' (which is in 'release/modules/ext' within the Color Chooser module) in the same way. Create a Runtime Configuration. In the toolbar, click 'Edit Configurations'. Create a new configuration, named 'NetBeans' (for example, but name it whatever you like). Set 'org.netbeans.Main' as the 'Main class' (you should be able to browse to it in 'boot.jar'). in 'VM parameters', pass in some VM options for setting the user directory of the application (which would normally be set via etc/netbeans.conf when NetBeans IDE starts up, which it won't do in our case), as well as the home directory. The user directory can be anywhere, while the home directory must be the cluster that is created by the build process: -Dnetbeans.user="/home/geertjan/idea/paint-userdir" -Dnetbeans.home="/home/geertjan/idea/PaintApp/build/cluster" The above implies that the cluster exists, which implies that a build has been performed. That's why I do the build from NetBeans IDE. That creates the cluster and then the above VM option works. Instead of VM options, you can also use other approaches to ensure that the application knows where the installation and the user directory are, as discussed here in the comments. Turn Folders into Source Folders. Go back to the Module Settings and then use the Sources tab to set 'branding' and 'build' as sources. (After you do this, the folders will turn blue.) The 'Paint/src' should already be marked as sources. Now run the application, using the runtime configuration you defined earlier and you should see your application deployed. Now do the same to the FeedReader Application, which is also distributed with NetBeans IDE, and you should end up with a successful result, following the principles outline above. Finally, what's the benefit of all this? Well, for far too long IntelliJ users have been excluded from the wonderfulness of the NetBeans Platform. Now, following these instructions, you can at least get started. You'd use NetBeans IDE for generating the project structure and API stubs, as well as for the Matisse GUI Builder's support for the TopComponent class (and other UI classes), after which you'd do your coding in the IntelliJ Java editor. (And the IntelliJ XML editor has better support for the NetBeans Platform layer.xml file than NetBeans IDE does.) Or you'd have different developers working in different IDEs, sharing the same codebase in the way outlined above. An interesting discovery is that a NetBeans Platform application deploys much more quickly from IntelliJ than it does from NetBeans IDE.
March 4, 2009
by Geertjan Wielenga
· 30,348 Views
article thumbnail
NetBeans Lookups Explained!
Lookups are one of the most important parts of the NetBeans Platform. They're used almost everywhere and most of the time when you ask something on a mailing list the answer is "Use Lookups!". Many times when the use of Lookups is explained it's in a very specific context, e.g. selection management or ServiceLoaders. That makes Lookups look complicated and hard to understand, while actually they are very simple and extremely powerful. That's why I guess it's time to write an article that explains what lookups actually are and how they work. In the subsequent parts I'll explain how they can be used to solve some common problems. Lookup as a Data Structure So first let's have a look at Lookup as a data structure. A Lookup is a map with Class Objects as keys and a Set of instances of the key Class object as values. An additional feature of a Lookup is that you can listen for changes of what's in there. It's as simple as that! If you want to ask a lookup for it's contents, you can do so like this: Lookup lookup = //get a lookup somewhere... Collection strings =lookup.lookupAll(String.class); If you want to listen for changes, you add your Listener to Lookup.Result an inner class that represents a query result. This way you add a Listener that listens for addition or removal of objects of a certain class: Lookup.Result strings = lookup.lookupResult(String.class); strings.allItems(); strings.addLookupListener(new LookupListener(){ @override public void resultChanged(LookupEvent e){ // do something } ); This is how you usually use an existing lookup. If you want to create one, there are some implementations to help you. The most basic one is Lookups.Singleton, a Lookup that only contains one object: Lookup simple = Lookups.singleton("Hello World!"); There's also an implementation for creating a lookup with more than one entry, still with fixed content: Lookups moreElements = Lookups.fixed( "Hello", "World", new Integer(5) ); If you want to use a Lookup to dynamically put in stuff you'll need to choose an implementation that supports that. The most flexible one is using an InstanceContent Object to add and remove stuff: InstanceContent content = new InstanceContent(); Lookup dynamicLookup = new AbstractLookup(content); content.add("Hello"); content.add(5); Listeners registered for the matching class will be informed when something changes. If you would like to query more than one Lookup at a time you can use a ProxyLookup. This for example, combines two of the Lookups created above into one: ProxyLookup proxy = new ProxyLookup(dynamicLookup, moreElements); Lookup.Provider If your Object has a Lookup to store a bunch of stuff, you can make it accessible to others by implementing Lookup.Provider an interface with only one method: public Lookup getLookup(); Again, extremely simple. Someone interested in what's in your Objects Lookup can ask for it and register a listener. In NetBeans TopComponents implement this interface, so you can ask any TopComponent for it's Lookup. The easiest way to get hold of most of the TopComponents is via their ID: TopComponent tc = WindowManager.getDefault().findTopComponent("AnInterestingTopComponent"); Lookup tcLookup = tc.getlookup(); As most TopComponents put into their Lookup whatever is selected, for example the entries in a list, you can add a Listener to track the Selection in a TopComponent. If your for example interested in the selected Nodes you can do it like this: Lookup.result noderesult = tcLookup.lookupResult(Node.class); result.allInstances(); noderesult.addLookuplistener(myLookupListener); That's especially handy when you want to provide a Master-Detail-View. If you want to provide your own Lookup in your TopComponent you do it like this: associateLookup(mylookup); Global Selection Sometimes you might be interested not only in what is selected in one specific TopComponent, but in whatever TopComponent currently has the focus. That's easy as well because NetBeans provides a Lookup that proxies the Lookup of the TopComponent that currently has the focus. To use this you simply need to do this: Lookup global = Utilities.actionsGlobalContext(); You can use this like any other Lookup and register your listeners, no magic involved. Nodes Nodes also implement Lookup.Provider so you can ask them for their Lookup as well. Something useful to store inside a Node's Lookup is the DataObject it may represent. If you're using Nodes you probably do so in combination with the Explorer API to display them. If you do that you'll usually create a lookup for your TopComponent with the help of the ExplorerManager: associateLookup(ExplorerUtils.createLookup ( explorermanager, this.getActionMap() ) ); The resulting Lookup also proxies the content of the selected Nodes Lookup. This way everything someone might be interested in shows up in your TopComponent's Lookup. Service Loader and other uses As you've seen Lookups are actually a very simple yet powerful concept. Some articles here on NetBeans Zone also cover the use of Lookups for loading services in a NetBeans RCP application, which is also an important use. To do that NetBeans provides a default Lookup that looks in certain places for service registrations, e.g. in the META-INF/services folder of a modules jar file and in the modules layer.xml. If you're interested in getting an instance of a Service implementation you can do it like this: Collection services= Lookup.getDefault.lookupAll(ServiceInterface.class); If you register your service in the layer.xml you can get a lookup for a certain Folder like this: Lookup lkp = Lookups.forPath("ServiceProviders"); I guess that's all you need to know to get started with Lookups, so have fun trying it out, it's really simple.
February 12, 2009
by Toni Epple
· 72,148 Views · 7 Likes
article thumbnail
NetBeans Output Window Font Too Small? Now It's Easy to Change!
Ctrl=, Ctrl-- or Ctrl-mousewheel In a fit of pique this evening, I added a much requested feature to the NetBeans output window: Actions for Larger Font and Smaller Font on the popup menu - or you can just Ctrl-mousewheel to rapidly change the font size. Font changes affect all open output windows, and persist across sessions. It just seemed silly to have this issue sitting open for so long. Now we'll see if anyone gets upset with me, since I haven't actually been the owner of the output window code in years. :-)
February 6, 2009
by Tim Boudreau
· 23,374 Views
article thumbnail
Tip: Importing Images into NetBeans
In the 6.5 release I noticed I can import images in two ways: Drag image from outside NetBeans into a project (e.g., a package) in Projects window. Copy an image outside NetBeans (so it is now on clipboard), then paste it onto a package and then it is added. Small tip, but Very useful to me now I know it.
January 30, 2009
by Harris Goldstone
· 49,806 Views · 1 Like
article thumbnail
Hello EclipseLink on the NetBeans Platform
Let's use EclipseLink to set up some very basic database interaction in a NetBeans Platform application. Though it will be the ultimate 'Hello World' scenario, it should show how to get started with database interactivity on the NetBeans Platform, while also yet again showing the benefit of the NetBeans Platform's modular architecture. Of course, feel free to adapt these instructions to your needs, for example, instead of EclipseLink, use TopLink, or Hibernate, or whatever. You should also be surprised by how easy it is, once you know how. We'll simply access a database and display what we find there: Our application will look as follows: Notice that we will have 4 separate modules, which will enable us to easily provide alternative database providers, as well as alternative persistence providers, because the UI module uses generic code that could make use of any alternative backing modules. Let's get started. Create a Java Library and Generate Entity Classes from the Database. Firstly, create a Java Library project. Then use the Entity Classes from Database wizard to generate entity classes from your database. In the wizard, select EclipseLink in the step where you use the wizard to generate a persistence unit. Look at the generated code and notice that, among other things, you have a persistence.xml file in a folder called META-INF, thanks to the wizard. In my case, I chose a Sample database that comes with the IDE, and then I specified I want an entity class for the Customer table, which resulted in the IDE also creating an entity class for the related DiscountCode table: Build the Java Library and you will have a JAR file in the above application's "dist" folder. As you will read in the next step, that JAR file needs to be added as a library wrapper module to the application you will start creating in the next step. Create a NetBeans Platform Application. In the New Project dialog, specify that you want to create a new NetBeans Platform Application. Once you've created it, right-click the Modules node in the Projects window and choose Add New Library. Then select the JAR you created in the previous step. You now have your first custom module in the new application. Create Supporting Library Wrappers. Do the same as you did when creating the library wrapper for the entity class JAR, but this time for the EclipseLink JARs (which are in your GlassFish distro, make sure to include the persistence JAR that you find there too and, if you don't know which ones to include, go back to the Java Library shown in the previous screenshot and then expand the Libraries folder, which will show you which libraries you need). Next, create yet another library wrapper module... for the DerbyClient JAR. Create the UI Module. The final module you will need will provide the UI. So, create a new module (not a Library Wrapper Module, but just a plain NetBeans Module) and add a Window Component via the New Window Component wizard. Set Dependencies. You now have lots of classes all neatly separated into distinct modules. In order to be able to use code from one module in another module, you'll need to set dependencies, i.e., very explicit contracts (as opposed to accidental reuse of code in one place from another place, resulting in unmaintainable chaos). First, the entity classes module needs to have dependencies on the DerbyClient module, as well as on the EclipseLink module. Then, the UI module needs a dependency on the EclipseLink module as well as the entity classes module. (You could split things further so that the EclipseLink module is not a dependency of the UI module, by putting the persistence JAR in one module, with the other EclipseLink JARs separated in a different module.) Now, finally, let's do some coding. Not much needed, though. Add a JTextArea to the TopComponent in the UI module. Then add this to the end of the TopComponent constructor: EntityManager entityManager = Persistence.createEntityManagerFactory("EntityLibPU").createEntityManager(); Query query = entityManager.createQuery("SELECT c FROM Customer c"); List resultList = query.getResultList(); for (Customer c : resultList) { jTextArea1.append(c.getName() + " (" +c.getCity() + ")" + "\n"); } Above, you can see I am referring to a persistence unit named "EntityLibPU", which is the name set in the persistence.xml file. In addition, I am referring to one of the entity classes, called Customer, which is in the entity classes module. Adapt these bits to your needs. Deploy the Application. Start your database server and then run the application. You should see this: Congrats, you've just managed to set up JPA via EclipseLink in a modular NetBeans Platform application... and you only typed 6 lines of code.
January 17, 2009
by Geertjan Wielenga
· 34,335 Views
article thumbnail
Which Java Version Is Used To Run Our NetBeans Installation?
Ever wondered which Java version is used to run your NetBeans instance? I have a lot of JDK's installed and everytime I install a new one it ones to be the default JDK for my computer. To know which JDK is used for running NetBeans we go to Help | About and the dialog box shows which Java version is used: To explicitly tell NetBeans which JDK to use we can use the command-line argument --jdkhome when we start NetBeans. Or we can set the property netbeans_jdkhome in the file netbeans-install-dir/etc/netbeans.conf.
December 23, 2008
by Hubert Klein Ikkink
· 16,947 Views
article thumbnail
Check Directory/dir/file Size In Linux
#check partition sizes df -h #check directory size du -s -h /var/log/ #check every directory and file sizes under a dir. du -s -h /var/log/* #check individual size size du -s -h /var/log/lastlog
December 9, 2008
by Snippets Manager
· 17,037 Views
article thumbnail
How Do NetBeans Extension Points Work?
One of the main benefits of the NetBeans Platform is its module system. Regardless of which module system is best (my guess is there will soon be a version of NetBeans that can also run as OSGi bundles), it’s important to have a system that enables you to create a modular architecture for your application. A module system is an invitation to create a clean and maintainable architecture with defined dependencies and nice APIs with clearly defined and easy-to-use extension points. If you follow these principles, others can extend your application easily. Maybe the easiest way to provide extension points in NetBeans is via the layer.xml file (also known as the "layer file"). In a NetBeans module (also known as a "plugin"), the layer file is its central configuration file. NetBeans IDE uses the layer file to provide extension points for APIs. Objects can be created declaratively in the layer file and you can use the NetBeans Lookup API to listen for changes. You will use this approach whenever you create new Actions (which are invoked via menu items, toolbar buttons, and/or shortcut keys) or TopComponents (which provide "views" or "windows"), for example. This quick tutorial shows how you can provide your own extension points via the layer file. The source code of the sample is found here in the NetBeans Plugin Portal. Prerequisites NetBeans (I’m using 6.1, but this will also work with older/newer versions). Create a new module suite: Choose File > New Project (Ctrl-Shift-N). Under Categories, select NetBeans Modules. Under projects, select "NetBeans Platform Application" or ("Module Suite Project" in older versions) and click Next. In the Name and Location panel, type "layerextensionpoints" in Project Name. Change the Project Location to any directory on your computer, to store the application. Click Finish. Now create four modules inside the suite, called "extensionpointinterface", "messagereader", "messageprovider1" and "messageprovider2": Choose File > New Project (Ctrl-Shift-N) again. Under Categories, select NetBeans Modules. Under Projects, select Module and click Next. In the Name and Location panel, type the name in Project Name (i.e., one of the four names listed at the start of this step). The default in the wizard should be to create the module underneath the directory where you just created the suite, which is fine. Click Next. In the Basic Module Configuration panel, replace the Code Name Base with de.eppleton.. Make sure to let the IDE create a layer file, by filling out the XML Layer field with de/eppleton//layer.xml. Click Finish. Here is what you should now see: Create a Service Provider Interface We will use the module "extensionpointinterface" to define an interface that will be used by the two extension point providers as well as by the "messagereader" module, which uses the two extension points. Inside that module create interface "MessageProviderInterface" with the single method getMessage() that returns a String: public interface MessageProviderInterface { public String getMessage(); } To make this part of the public API right click the project node, select API Versioning and select the check box of de.eppleton.extensionpointinterface. Now this package is accessible to other modules. Create Service Provider Implementations Now we need some modules that implement the MessageProviderInterface. We will use the modules "messageprovider1" and "messageprovider2" to do that. To implement the interface they both need a dependency on module "extensionpointinterface". For each of them do the following: Right click the project node, click Properties and, in the Project Properties dialog, select the "Libraries" category. Click "Add Dependency". Select "extensionpointinterface", and click "OK" twice. Now that we have access to the interface in our two message providers, we can implement it. Again, for both modules, do the following: Select "New" > "Java Class". In the Wizard type "MessageProvider1" or "MessageProvider2" in the Class Name field, respectively, and select the main package in each case, for stroring the new class. Implement the interface. Each of them should provide a different String. In other words, we will provide "Hello " in MessageProvider1 and then we will provide "World!" in MessageProvider2: import de.eppleton.extensionpointinterface.MessageProviderInterface; public class MessageProvider1 implements MessageProviderInterface { public String getMessage() { return "Hello "; } } import de.eppleton.extensionpointinterface.MessageProviderInterface; public class MessageProvider2 implements MessageProviderInterface { public String getMessage() { return "World!"; } } } In order to make our MessageProviders available as services, add these entries in the layer of the two modules. Between the the layer file's tags, add the following, i.e., in the first module add the first set of tags and add the second set of tags in the second module: and This will create an instance of our MessageProviders using the standard constructor. The trick is that those instances will be accessible from outside the modules, via the NetBeans System FileSystem. Now that you have created your services, the next step shows how you can access them, without even needing to set a module dependency for them. Find and Use the Service Providers We will use the module "messagereader" to display the messages provided by our two MessageProviders. To do so we will create a TopComponent, within the "messagereader" module: In the Project Properties dialog for "messagereader", set a dependency on "extensionpointinterface", exactly as shown earlier. Right-click on the "messagereader" project node and choose "New" > "Window Component". Choose "Output", which will determine where the new window will be displayed. Make it show on startup by ticking the checkbox. Click Next. Enter "MessageReader" for the class name prefix and click "Finish". The TopComponent class will open in Design View. Drop a JScrollPane from the palette in the window and make it fill the whole area. Add a JTextArea to it, making it fit the whole area too. In the source view (i.e., click "Source" at the top of the Design view) add this to the end of the constructor: Lookup lkp = Lookups.forPath("MessageProviders"); for (MessageProviderInterface mi : lkp.lookupAll(MessageProviderInterface.class)) { jTextArea1.append(mi.getMessage()); } The code above will lookup the folder you created via the layer file (Lookups.forPath("MessageProviders")), search for classes implementing the interface (lookupAll(MessageProviderInterface.class)) and call the interface method on all instances. Let’s try it out! Run the Module Suite. You will see the window either displaying "Hello World!" or "World!Hello ". As we can see in this very simple example, the order in which the ServiceProviders are called can be important for the result. So in the next step I will show you a trick to guarantee the correct order. Sort the Service Providers The NetBeans Platform provides a way to sort layer entries. This mechanism is used, for example, to provide the order of actions in menus and toolbars. Since 6.0, this is done via the position attribute in the layer file. So this won’t work in older versions: In the layer file of the two modules, insert the "position" attributes that you see below, i.e., the first set of tags below belongs to "messageprovider1", while the second belongs to "messageprovider2": and Now the messages will always be displayed in the correct order: "Hello world!". Simply swap these values to reverse the order of the messages. When you do something like this, make sure that you choose your values large enough to add services in between the initial ones, so that there’s room for your application to grow! Now try and see what happens when you set the same value for both attributes! Summary The intention of this article is to illustrate how simple it is to implement loose coupling in a NetBeans Platform application. Note that the module that uses the services (i.e., "messagereader") has no dependencies on the modules that provide the services ("messageprovider1" and "messageprovider2"). And not only does the NetBeans Platform provide a very simple mechanism to provide and lookup services, but it also provides an easy way to declaratively order them. Appendix: Alternative Registration Mechanism, Using "META-INF/services" In the previous sections, I showed how to register the Service Providers via the layer file. As stated correctly in the comment to this article, by Casper Bang, there's an alternative way to register the service providers. Using the META-INF/services folder is the standard approach that is supported by Java since version 1.3. This additional sections below show how it works. Register the Services There are only some small changes needed to change the registration mechanism: In module messageprovider1 create a folder via the context menu of "Source Packages" > "New" > "Other" > "Folder". Enter "META_INF/services" as Folder Name; the folder will show up like a normal package. Create a file via the context menu of this new package "META-INF.services" > "New" > "Other" > "Empty file", name the file "de.eppleton.extensionpointinterface.MessageProviderInterface". Edit the file and enter "de.eppleton.messageprovider1.MessageProvider1" Copy and paste the "META_INF" folder to the "Source packages" folder of module messageprovider2 and change the content of file "de.eppleton.extensionpointinterface.MessageProviderInterface" to "de.eppleton.messageprovider2.MessageProvider2" There are different ways to lookup the services. You can either use the default lookup to do so, or you can use the ServiceLoader mechanism introduced in Java 1.6. Let's begin with the method using the default lookup. Using Lookup to retrieve ServiceProviders The global lookup will automatically provide these services for you, so only a little change is needed. In the module "messagereader", edit "MessagereaderTopComponent", and replace this line: Lookup lkp = Lookups.forPath("MessageProviders"); with this line: Lookup lkp = Lookup.getDefault(); Afterwards, you can build and run the application as before. You may notice that the order of the services has changed. As before you can fix this by adding an additional position attribute when you define the ServiceProvider. Edit both "de.eppleton.extensionpointinterface.MessageProviderInterface" files in modules messageprovider1 and messageprovider2. Add the lines "#position=10" and "#position=20" respectively. Run the application and play with the values to change the order as before. Using ServiceLoader to Locate the ServiceProviders If you're using JDK 1.6 or later, you can edit "MessagereaderTopComponent" and replace the code we've added before with the following: ServiceLoader serviceLoader = ServiceLoader.load(MessageProviderInterface.class); for (MessageProviderInterface mi : serviceLoader) { jTextArea1.append(mi.getMessage()); } Note that the position attribute is now ignored, since it's not a part of the standard JDK but an extension added by the NetBeans Platform.
August 25, 2008
by Toni Epple
· 28,210 Views
article thumbnail
Generate Constructor, Getters and Setters in NetBeans PHP IDE
Petr Pisl is the lead engineer of the PHP work scheduled for NetBeans IDE 6.5. Here he shares an update on some of the latest work that's been done in this area. -- Geertjan Wielenga, NetBeans Zone leader This morning I have committed a feature to the NetBeans PHP support that will be part of NetBeans IDE 6.5, which offers generating of constructor, getters and setters in a PHP class. To invoke the functionality, the caret position has to be inside a PHP class and you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered. Let's explain on a simple example. I have very simple PHP class, where I have only two properties - $name and $age. At first I want to add constructor. After pressing ALT+Insert (CTLRL+I on Mac), the constructor generator is offered - Constructor... item in the Generate menu. After invoking this item, the Generate Constructor dialog is displayed. There I can choose parameters of the constructor. It is possible to chose any property, then the constructor is generated without any parameter and empty. If I check / uncheck the User class, then all properties are selected / unselected. For my demonstration I have chose $name property. After pressing OK button, the constructor with one parameter is generated. Now I want to generate getter for the $name. After invoking Generate menu, you can notice that the Constructor... item is not offer anymore, because the class already has a constructor. I choose Getter... item and Generate Getters dialog is displayed. In the dialog you can choose, for which properties you want to generate getters. Again you can check / uncheck the class node, which selects / unselects all properties. As the next step I want to generate getter and setter for $age property. After choosing Getter and Setter... item in Generate menu, the dialog offers only $age property, because only this property has neither getter nor setter. When I invoke Generate menu after creating getter and setter for $age property, only setter generator is offered, because there is not defined only setter for $name property. The generate functionality is designed that you can work just with the keyboard and you don't have to use mouse. From: http://blogs.sun.com/netbeansphp
July 30, 2008
by Petr Pisl
· 107,940 Views
article thumbnail
IntelliJ Keymap for NetBeans IDE
Have been using IntelliJ for about 5 years now. It is still the Roll Royce of all IDEs, and of that there is no doubt. But having said that, you should once in a while jump the ship, and try out something different and it is with this intention that I am currently trying out NetBeans IDE 6.1. I was a NetBeans IDE user starting from its “Forte for Java” days to about 2003, and did also develop some plugins on it. So it feels great to be back home. Well not quite. Though NetBeans IDE has now added almost every trick in the bag, it is still challenging even for a veteran, to pick up from where they left off. To ease this pain of transition, here is the link to an IntelliJ Key Map, which when applied to NetBeans IDE, will make it feel more like IntelliJ to you. If you find yourself pressing CTRL+ALT+L, CTRL+ALT+O and CTRL+F12, this keymap will be a real time saver. From: IntelliJ Keymap for NetBeans
July 14, 2008
by Swapnonil Mukherjee
· 10,862 Views
article thumbnail
Python Development in NetBeans IDE
The nbPython project aims to provide support for Python development to NetBeans IDE. Below follow the step-by-step instructions for getting started! The bits are available (milestone releases) for download now as NetBeans modules (nbms). Let us get started: Download/lnstall the M3 NBMs from here. Fire up NetBeans IDE. Go to Tools -> Plugins -> Downloaded Tab. Click on "Add Plugins" and select all the NBM files in the unzipped directory. Now, you will see all the chosen modules along with their descriptions. You should see something like this: Press the "Install" button. Using NetBeans IDE 6.1, I get a dependency error: Then, I downloaded a latest build NetBeans IDE Build 200806220002 from here and repeated the above steps. This time there was no dependency problem. You will get a "Validation Warning". Press "Continue": The installation will continue and will be over without any further user interaction required. Creating a New Python Project Go to File-> New Project-> Python-> Python Project. Choose a Project Name- say "HelloNbPython". Click on Finish. A new project gets created and is visible in the Project Explorer window. No default file is created. Right Click on the project name, and select New-> Empty Python File. Enter a name, say- HelloWorld. A Python script will be generated for you which will simply print "Hello World". The project tree is now as follows: HelloNbPython/ pyproject/ project.properties src/ HelloWorld.py Runing a Python Script Right Click on HelloWorld.py in the project explorer and click "Run Python Script". First time I did this, I got the following exception message: java.io.IOException: Cannot run program "/home/amit/netbeans-dev-200806220002/nbpython/jython-2.5/bin/jython" (in directory "/home/amit/NetBeansProjects/HelloNbPython"): java.io.IOException: error=13, Permission denied So I checked the file permission of the 'jython' executable: $ ls -l jython -rw-r--r-- 1 amit amit 5101 2008-06-22 15:05 jython As you can see there is no executable permission for 'jython' as indicated by the absence of the 'x' flag So, I made the 'jython' executable by: chmod +x jython Run the script again and you should get "Hello World" in the output window.
June 22, 2008
by Amit Saha
· 33,158 Views
article thumbnail
Easy Unwrapping with IntelliJ IDEA
In complicated code constructs that contain numerous nested statements, you sometimes need to accurately get rid of the enclosing parts. When you try to manually delete such statements, it is too easy to break the syntax of the whole construct. With the new IntelliJ IDEA’s unwrapping feature, this task becomes just a snap. Consider the following example, where a string variable is being analyzed: [img_assist|nid=3370|title=|desc=|link=none|align=left|width=640|height=299] Let’s remove one of the branches. To do that, place the cursor at the branch containing the statement, and press Ctrl+ Shift+Delete. IntelliJ IDEA shows you which results you can obtain: the part that will remain is displayed on the blue background, while the grey background denotes the pieces of code to be deleted: [img_assist|nid=3371|title=|desc=|link=none|align=left|width=640|height=258] After clicking the Remove ‘else…’ option, we get the promised results: [img_assist|nid=3372|title=|desc=|link=none|align=left|width=640|height=226] As you see, all parentheses are properly balanced, and the syntax is correct. However, Java developers are not the only ones who can enjoy this powerful feature. The same “stripping” can be done in XML or HTML code. Consider a situation when you have to clean up some HTML code and get rid of inline styles, for example, remove bold fonts. What will you do in this case – delete an opening tag, then delete the closing tag, with the real possibility to lose something in process. With IntelliJ IDEA, all you have to do is to place the caret somewhere inside the tags, and press Ctrl+Shift+Delete. The unnecessary tags are removed silently. This facility is even more helpful for XML constructs, which can have deep nesting. You can sequentially remove enclosing tags level by level, until getting to the innermost one you want to preserve. Do I need to mention that such unwrapping can be undone? Enjoy!
June 7, 2008
by Irina Megorskaya
· 10,254 Views · 1 Like
article thumbnail
Obfuscating a NetBeans Java Application Project
Some time ago I found a couple of posts talking about how to obfuscate a NetBeans RCP module (here and here). Getting some parts of the ant targets presented in the previous post, this one presents a simple target that allows to obfuscate a normal Java library. For this, you need to have installed the obfuscator ProGuard. Take into account I am talking about obfuscating a Java library. This implies the obfuscation is lighter than if you obfuscate a closed application, that is, all public methods and interfaces must maintain its name (if not you can call your library methods anymore). Open your build.xml Java application file and paste this target: Special attention to these couple of lines:
April 30, 2008
by Antonio Santiago
· 45,921 Views · 1 Like
article thumbnail
Quick Start: Creating Language Tools In NetBeans IDE
NetBeans IDE is one of the main free Java editors in the market. In fact, it can be used to program in many other computer languages, like C/C++, Ajax, Javascript. NetBeans IDE can be extended by adding modules that add new features. So... you can have a programming editor customized to your needs. This tutorial can be of interest for all those who want to create a module that adds support for a new language inside NetBeans IDE. Original article: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html (the original article has coloring that makes reading easier. If you have some dificulty reading it here, you can go there). The process of creating the first of the modules that compose my X3DV Module Suite was similar to the one described here. We will learn how to make a module that has these features: Syntax highlighting that is specific for the language we will define. Brace completion and auto-indentation. Icons for the new files of that language. To be able to create new files written in our new language. Template for the new files written in that language. Just download the last version of NetBeans IDE (download NetBeans IDE 6.1 Beta). Then, follow all the steps described here. This tutorial is valid for the 6.1 version of NetBeans IDE, which has many improvements that make module building easier. This tutorial takes a fictional language called Foo Language as a sample. I suggest to follow the tutorial as it is, and later, adapt it to your needs. This is not a highly technical tutorial, but a quickstart guide that can be very easy for newcomers. First Steps With Your Module Create a new NetBeans project: Choose NetBeans Modules in Categories and Module in Projects: Fill in your project Name, locate the directory where its project folder will be placed, and mark it as a Standalone Module. Fill the info for your module. You just have to fill the two first text boxes: change the Code Name Base to what is appropriate for your module and choose a Display Name. The project will be created. Now we will add the basic: support files for the new file type. New File Type Support Over the project name, right click and select New/File Type: In the dialog that appears, you must enter some data so the NetbBeans IDE recognizes the new file type. In MIME Type you must enter text/x- usually followed by the main extension of the file type. Why does it say text/x-? As you may note, what you enter is not the true MIME type. For the IDE, all the extensions we create are text files. In Extension(s) you must enter them separated with spaces. In our example, there's only one extensions for Foo Files: .foo In Class Name Prefix, you enter the name of the file type, so all classes generated by the IDE for this module will start with it. In Icon, you must locate in your hard drive a gif icon of 16x16 pixels. In our example, it's this: Although in some tutorials they say that jpg and png images can also be used, I found that sometimes they're not displayed. So I recommend using gif images, as they are less error-prone. The IDE will copy your icon to the project directory. At this point, a bunch of files will be created by NetBeans IDE and opened in the code editor. Close them all, you don't need to edit them. Now our module is ready to recognize and create the new file types. But we want the new files to have a default content. So we will edit the generated template. Locate the file named: Edit it and write the content that you want to be the default when you create a new file. Locate the XML Layer in the module. The XML Layer file is the soul of our module. It controls most of the things that a module can do. Locate these lines: The next step is to create a description of the new supported file type that will be displayed when you want to create it, in the New File Wizard. This description will be stored in a file called "Description.html" (strange... uh?). Add this line after the one highlighted in blue, modifying it to your project url: This line we added describes where the Description of the new file is. Right click over your project and select New/Other. Select Other/HTML file. Name the file "Description", and leave the rest as it is. Replace all the contents of the generated file with this: Creates a foo file that is useful for nothing at all. This is what we will see as a result of these steps once the module is finished and we want to create a Foo file. Create the Language Support Now that we have the new files recognized, we will add syntax coloring and other features to our language module. To be able to support language features, we must do the following: right click over your project and choose "Properties". The properties of your module will be displayed. Click over libraries (on the left) and then the "Add..." button. In the list, search for the entry called "Generic Languages Framework", and add it. Now, right click over your project and select New/Other. In Categories, select "Module Development", and on the right, select "Language Support". Then enter the MIME Type and Extensions as we did in the first section of our tutorial. You will see that the XML Layer has changed and now has more things added. Between them, there's a new file that describes our language. That file is called "language.nbs". As the XML Layer has been modified, the icon of our files may have disappeared, so we need to add something to the XML Layer file to recover it. Close all the opened files. Locate the file called XML Layer, and open it. Locate the line highlighted in blue in this image, that says And replace that entire line with: Editing The Language File The default language.nbs file is filled with contents that may be a good start point for a scripting language. For declarative languages like VRML or X3D, or markup languages like HTML or similar, these contents are not useful. In our example of the Foo Language, we will use a very simple language definition. This way you will understand the basics of defining languages. So delete all the contents of the file language.nbs, and replace them with this: # To change this template, choose Tools | Templates # and open the template in the editor. # definition of tokens TOKEN:header:( "# foo language v1.0" ) TOKEN:line_comment: ( "#"[^ "\n" "\r"]* | "//"[^ "\n" "\r"]* ) TOKEN:keyword:( "foo_function" | "foo_command" ) TOKEN:field:( "foo_value" ) # all that follows is useful for mostly all languages TOKEN:identifier: ( ["a"-"z" "A"-"Z"] ["a"-"z" "A"-"Z" "0"-"9" "_"]* ) TOKEN:number: (["0"-"9"]*) TOKEN:operator: ( ":" | "*" | "?" | "+" | "-" | "[" | "]" | "<" | ">" | "^" | "|" | "{" | "}" | "(" | ")" | "," | "=" | ";" | "." | "$" ) TOKEN:string:( "\"" ( [^ "\"" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\"" ) TOKEN:string:( "\'" ( [^ "\'" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\'" ) TOKEN:whitespace:( [" " "\t" "\n" "\r"]+ ) # colors COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } COLOR:keyword:{ foreground_color:"red"; font_type:"bold"; } COLOR:field:{ foreground_color:"#25A613"; font_type:"bold"; } # parser should ignore whitespaces SKIP:whitespace # brace completion COMPLETE "{:}" COMPLETE "(:)" COMPLETE "\":\"" COMPLETE "\':\'" # brace matching BRACE "{:}" BRACE "(:)" # indentation support INDENT "{:}" INDENT "(:)" Now, create a Foo file, using a plain text editor, and save it with the extension .foo These will be its contents: # foo language v1.0 # comment // another comment foo_function { foo_command ( foo_value 1 0 1 ); } Now let's see the language.nbs file and understand the basic parts. TOKEN:header:( "# foo language v1.0" ) TOKEN:keyword:( "foo_function" | "foo_command" ) The Tokens are the words that are part of your language, and you want them colored. They define types of words that have something in common in your language. You group them into a category, that is a token. The words are between double quotes, and separated by a | sign. COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } This defines the colors used for each token. You can specify more properties for colors, but these are the basic ones. All these properties are very easy to understand by their own names, as you see. The colors can be specified by their names (although it recognizes only a few) or by its number. # brace completion COMPLETE "{:}" What these lines do is that when you type a { sign, the editor automatically will type } after your caret, speeding your work and making it less error-prone. # brace matching BRACE "{:}" # indentation support INDENT "{:}" This sentences make that when you place the caret over a brace, the matching brace will be highlighted, and that lines after those signs will be indented. Final Note Now you know all that is needed to create the basic support for a new file type and language syntax highlighting. You can add anything you like to your module, that you think is important for you and that could make your work easier. There's much more than can be done with NetBeans IDE. I invite just to test it, join its huge community of users, and experience it by yourself. -Jordi R. Cardona- X3D/VRML Worldbuilder Java Programmer X3DV Module Suite Developer. Hiperia3D News © 2008 by Jordi R. Cardona. The images and text of this post were added by the author to dzone. The author has granted dzone.com with exclusivity to use these images and text for the only purpose to spread this article. If you want to promote this tutorial, you can link to the original one at: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html
April 14, 2008
by Jordi R Cardona
· 39,981 Views
article thumbnail
Ant Build File Changes for Java Web Projects in NetBeans IDE 6.1
While working with a Java Web Application in NetBeans, I noticed some slight changes in the Ant build file for my project between NetBeans 6.0 and 6.1. This article explores some of the problems these changes caused to help out anyone with similar issues. I started with a Java Web Application that was created in NetBeans 6.0.1. After adding some JSP files and several Java source files, I committed everything in the project to my CVS repository. For some of my projects, I utilize the Hudson continuous integration build server. Using a standard deployment of Hudson, I configured the project to poll the SCM every 60 minutes, check out the code from CVS (if changes had been committed), and trigger the NetBeans project’s Ant build file (calling several specific targets like compile, dist, and so on. My builds have been functioning correctly for several weeks using this standard setup. I recently opened one of those projects in NetBeans 6.1 Beta and have been thoroughly enjoying the new features (faster startup, better JSP parsing in the Source Editor). After adding some JAR files as libraries and making several configuration changes, I committed the entire project (particularly the build-related files in the nbproject directory). Suddenly, my build for that project started failing. The console output reported by Hudson was : -init-check: BUILD FAILED D:/projects/hudson-server/data/jobs/MyWebProjectl/workspace/nbproject/build-impl.xml:149: The Java EE server classpath is not correctly set up. Your active server type is Tomcat55. Either open the project in the IDE and assign the server or setup the server classpath manually. For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) Total time: 2 seconds finished: FAILURE I undid the configuration changes one by one, but the build failed regardless of what I reset. Apparently the property j2ee.platform.classpath is now required. I did a DIFF on the nbproject/build-impl.xml file and discovered several changes. The -init-check target includes property checks including this new one : The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}.Either open the project in the IDE and assign the server or setup the server classpath manually.For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) I hadn’t really taken notice of this property in the build file before, but it is referenced in a number of other targets such as: -init-macrodef-javac, -init-macrodef-junit, -init-macrodef-java, -init-macrodef-nbjpda, -init-macrodef-debug, compile-jsps, -do-compile-single-jsp, connect-debugger, javadoc-build, -do-compile-test, -do-compile-test-single Not being able to find a definition of the property anywhere in the build file, I looked through the project’s project.properties file among the list of defined properties. The property j2ee.platform.classpath was not defined. Thus, I’m assuming this is passed into the build file dynamically by NetBeans? In general I wouldn’t care, but when running the build file via Ant inside Hudson, the property j2ee.platform.classpath is never passed in. Hudson DOES allow you to pass properties and values to the build file, so I suppose I can specify the value manually, but I would like to keep the number of per project customizations to a minimum to maintain a low level of maintenance. Unless this causes some problem with the project properties in the build system, I would suggest the following fix for anyone who is experiencing a similar issue. Open your project’s project.properties file. Navigate to the section that contains these properties: j2ee.platform=1.4 j2ee.server.type=Tomcat55 Add a new line that specifies a blank j2ee.platform.classpath property such as this: j2ee.platform=1.4 j2ee.platform.classpath= j2ee.server.type=Tomcat55 Now, if the project.properties file is committed to CVS, a Hudson build can be triggered, and the FAIL check in the build-impl.xml file will pass. I ran some quick tests with the project, and everything with the project inside NetBeans still seems to work fine. I would propose to the NetBeans team to have the j2ee.platform.classpath property automatically added to the project.properties file.
March 26, 2008
by Adam Myatt
· 15,513 Views
article thumbnail
Patching from Local History
Using patches is a popular way to share changes between the teammates or supply updates to software products to the customers. With IntelliJ IDEA, creating and applying versioned patches is quite simple and intuitive: you can do it from the main Version Control menu, or from the Changes tool window. However, IntelliJ IDEA suggests an additional way to create and apply your “personal” patches. As we have discussed earlier, numerous changes pass unnoticed by the version control systems, because you just do not check in every change you make to your files while working. You know that IntelliJ IDEA keeps your own “personal version control” – the local history. Besides the possibility to roll back to a certain revision, you can also create a patch on the base of a revision or action, share it with your colleagues, and apply it when necessary. Local history applies to the folders, files, members and fragments of text, but the technique of creating a patch is common in all cases. Let’s see how it’s done. Select a folder in the Project tool window, and choose Local History on its context menu. In the Local History view, right-click the desired revision, and choose Create Patch: [img_assist|nid=1204|title=|desc=|link=none|align=left|width=505|height=357] In the dialog box that opens, specify the name and location of the patch file: [img_assist|nid=1205|title=|desc=|link=none|align=left|width=415|height=136] An interesting possibility is suggested by the Reverse patch checkbox. If you check this option, IntelliJ IDEA will create a patch that rolls back the selected action. For example, it you have created a file, the patch will delete it. Applying your “personal” patch is done as usual, using the Apply Patch command on the main Version Control menu. If a patch file is stored in project, you can invoke this command on the context menu of the patch file in the Project tool window: [img_assist|nid=1206|title=|desc=|link=none|align=left|width=249|height=195]
February 21, 2008
by Irina Megorskaya
· 9,784 Views
article thumbnail
Binding a JTable to Swing Controls in NetBeans IDE
Here is an outline of a scenario that binds Swing controls to columns in a JTable, via the tools that NetBeans IDE provides.
February 20, 2008
by Geertjan Wielenga
· 183,847 Views
article thumbnail
How to Create Visual Applications in Java?
My excellent colleague Java evangelist Chuk Munn Lee wrote me an e-mail in response to my description yesterday of how to create JConsole plugins: "I did not know that the visual library can be used outside of NetBeans. Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?" This is a good question and the answer is illustrative of how interwoven NetBeans IDE is with the NetBeans Platform. Look in your NetBeans installation folder and you'll find a folder called "platform7", with this content: In other words, literally, the content of the folder above is the NetBeans Platform. Many of the JARs that make up the NetBeans Platform can be used outside a NetBeans Platform application. Last October I wrote about this, in a blog entry entitled NetBeans APIs Outside of the NetBeans Platform. Follow the steps in that tutorial and you'll have a standard Java application that makes use of some of the typical JARs from the NetBeans Platform. In other words, several typical scenarios developed on the NetBeans Platform can also be developed outside of it. Another similar scenario is illustrated in the article I wrote yesterday, How to Get Started with JConsole Plugins, where the Visual Library API is used to inject some graph functionality into the JConsole. And so, in response to Chuk's questions "Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?", the answer is: "No, you don't." Download NetBeans IDE, take the two JARs that are highlighted in the screenshot above, put them on your app's classpath, and you're ready to create visual Java applications: Let's get started for real now. To create visual applications, you need some kind of Swing container within which you need a JScrollPane. Then you create your visual "scene" within that JScrollPane. There are several interesting classes that you can extend to make your visual application. Have a look at the Javadoc or take a stroll through the tutorial, though not all of the tutorial is intended for use outside of the NetBeans Platform. Now that you have a Swing container with a JScrollPane, create a new Java class that extends GraphScene. Fill it out as follows: package demo; import java.awt.Image; import java.awt.Point; import java.util.Random; import javax.swing.ImageIcon; import org.netbeans.api.visual.graph.GraphScene; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Widget; import org.netbeans.api.visual.widget.general.IconNodeWidget; import org.openide.util.Utilities; public class DemoGraphScene extends GraphScene { private LayerWidget mainLayer; private Image image; private Random r = new Random(); public DemoGraphScene() { mainLayer = new LayerWidget(this); addChild(mainLayer); image = Utilities.icon2Image( new ImageIcon(getClass().getResource("/demo/chuk.png"))); addNode("Chuk"); } @Override protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); mainLayer.addChild(widget); return widget; } @Override protected Widget attachEdgeWidget(Object arg0) { return null; } @Override protected void attachEdgeSourceAnchor(Object arg0, Object arg1, Object arg2) { } @Override protected void attachEdgeTargetAnchor(Object arg0, Object arg1, Object arg2) { } } Most of the above code is self-explanatory, I believe. You have a LayerWidget which you add to the scene. Then you add an IconWidget, which you add to the layer. One interesting thing to note is how the icon is converted to an image, via a utility method from the NetBeans Utilities API, which you have already put on your classpath, together with the Visual Library API. In other words, there's a bunch of stuff that NetBeans Platform developers use that can also be used in your own smaller Java applications, as is the case here. To wrap up, we need to instantiate the GraphScene class from our JFrame and then set the JScrollPane so that its port view will contain the "scene". Here's how we do that, nice and easy via the JFrame constructor: private DemoGraphScene scene = new DemoGraphScene(); public DemoVisualFrame() { initComponents(); jScrollPane1.setViewportView(scene.createView()); } Next, I added a pic of Chuk to my app's source structure and then ran the application. And here's the result: Next, let's turn Chuk into a movable object. The user should be able to drag and drop him with their mouse. Hmmm. That will mean a lot of coding, right? Wrong. Here's all I needed to add, i.e., just line 6 below: protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); //I only needed to add this line: widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } And now, when I run my app, I can use my mouse to drag Chuk to a different location: A MoveAction can only mean one thing, i.e., it can only mean that you want to move the widget. However, other actions could be implemented in a variety of ways, hence there is no default. You need to provide the content of the action yourself, as in the case of the LabelTextFieldEditor. Here, we begin by defining a class-level LabelTextFieldEditor: private WidgetAction editorAction = ActionFactory.createInplaceEditorAction(new LabelTextFieldEditor()); Next, we define out LabelTextFieldEditor, extending the TextFieldInplaceEditor class: private class LabelTextFieldEditor implements TextFieldInplaceEditor { public boolean isEnabled(Widget widget) { return true; } public String getText(Widget widget) { return ((LabelWidget) widget).getLabel(); } public void setText(Widget widget, String text) { ((LabelWidget) widget).setLabel(text); } } Finally, we add a label to our widget. We also assign the editor action defined above to our widget. Here we go, just line 7 and 8 below: @Override protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); //I added the following two lines: widget.setLabel("Chuk"); widget.getLabelWidget().getActions().addAction(editorAction); widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } That's it. Let's run our app again. You now have a label which you can click and then it is editable: When you press Enter, the label is changed. But what's the point of having just Chuk in our application? Let's add another evangelist, Gregg Sporar: private Image CHUK = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/chuk.png"))); private Image GREGG = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/gregg.png"))); Next, we'll create a hash table, so that we can manipulate them more effectively: private final Hashtable mapping; { mapping = new Hashtable(); mapping.put("Chuk", CHUK); mapping.put("Gregg", GREGG); } Then, we'll add them both, rather than just one: public DemoGraphScene() { mainLayer = new LayerWidget(this); addChild(mainLayer); //Here we create our two evangelists: addNode("Chuk"); addNode("Gregg"); getActions().addAction(editorAction); } We'll need to rewrite our earlier method just a bit, so that it is more generic, because now it will have to handle both Chuk and Gregg: @Override protected Widget attachNodeWidget(Object node) { Image image = (Image) mapping.get(node); if (image != null) { return createNewWidget(node, image); } throw new IllegalArgumentException(node.toString()); } And we move all the code from the previous implementation of the above method to a new one: protected Widget createNewWidget(Object label, Image image) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); widget.setLabel(label.toString()); widget.getLabelWidget().getActions().addAction(editorAction); widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } Run the app again and now you'll have two evangelists in your "scene", instead of just one, with the same properties because they're both the same widget, as you can see from the code above: You might now think about connecting them together, which we can look at in a future article. In general, there's a lot more that can be done, of course, and the documentation on all of this goes into it all. Here's the homepage of the library. I also highly recommend Fabrizio Giudici's Creative use of the NetBeans Visual Library: the Light Table. In summary, you don't even need to like NetBeans IDE to benefit from its graph library. Just download the IDE, get the two JARs specified above, and then add them to your classpath. That's all. And then code in whatever IDE has your preference.
January 29, 2008
by Geertjan Wielenga
· 198,415 Views · 1 Like
  • Previous
  • ...
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×