Friday Nov 30, 2012

Even More Steroids for JEditorPane

Got some help from Ralph today and now the JEditorPane is as I want it, e.g., code folds are now supported once you click in the JEditorPane, though there are still some side effects, since this is not how anyone anticipated NetBeans editor APIs being used. But, so far, the side effects (e.g., now the hyperlinks work, but they open a new JavaScript file when you click on one of them, instead of jumping within the JEditorPane itself) are not so terrible.

Error checking is also done now, which wasn't there before, i.e., red underlines and error annotations in the right margin. And maybe it's my imagination, but the editor feels a lot snappier, e.g., in code completion, than before.

I've checked in the changes, they're all in this file:

http://java.net/projects/nb-api-samples/sources/api-samples/content/versions/7.3/misc/CMSBackOffice2/CMSBackOffice2-editor/src/main/java/com/mycompany/cmsbackoffice2editor/GeneralTab.java

Thursday Nov 29, 2012

JEditorPane on Steroids with Nashorn

Continuing from Embedded Nashorn in JEditorPane, here is the same JEditorPane on steroids with Nashorn, in the context of some kind of CMS backend system:

Above, you see heavy reusage of NetBeans IDE editor infrastructure. Parts of it are with thanks to Steven Yi, who has done some great research in this area. Code completion, right-click popup menu, line numbering, editor toolbar, find/replace features, block selection, comment/uncomment features, etc, etc, etc, all the rich editor features from NetBeans IDE are there, within a plain old JEditorPane. And everything is externally extensible, e.g., new actions can be registered by external modules into the right-click popup menu or the editor toolbar or the sidebar, etc.

For example, here's code completion (Ctrl-Space):

It even has the cool new feature where if you select a closing brace and the opening brace isn't in the visible area, a rectangular popup appears at the top of the editor, to show how the current piece of code begins:

The only thing I am missing is code folding! I wish that would work too, still figuring it out.

What's also cool is that this is a Maven project. The sources:

http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.3/misc/CMSBackOffice2

Wednesday Nov 28, 2012

Rewritten NetBeans Platform Feed Reader Tutorial

The next tutorial that has been thoroughly restructured and rewritten is:

NetBeans Platform Feed Reader Tutorial

Originally written by Rich Unger, it was one of the very first NetBeans Platform tutorials that ever existed. In this particular rewrite, the entire structure of the tutorial has changed, in an attempt to make the flow more "bite size", rather than a big lump. Also, thanks to recent NetBeans Platform changes, there are no Bundle files anymore, all Strings are declared via @Messages annotations.

Theoretically, the browser in the application could be a JavaFX WebView, though the browser part of the application isn't a central theme of the tutorial, hence only a reference is made to the JavaFX alternative. Here's what it looks like:

Comments to the NetBeans Platform Feed Reader Tutorial are, as always, very welcome. 

Tuesday Nov 27, 2012

Embedded Nashorn in JEditorPane

Here's a prototype for some kind of backoffice content management system. Several interesting goodies are included, such as an embedded JavaScript editor, as can be seen in the screenshot:

Key items of interest in the above are as follows:

  • Embedded JavaScript editor (i.e., the latest and greatest Nashorn technology, look it up, if you're not aware of what that is.) The way that's done is to include the relevant JavaScript modules in your NetBeans Platform application. Make very sure to include "Lexer to NetBeans Bridge", which does a bunch of critical stuff under the hood. The JEditorPane is defined as follows, along the lines that I blogged about recently thanks to Steven Yi:
    javaScriptPane.setContentType("text/javascript");
    EditorKit kit = CloneableEditorSupport.getEditorKit("text/javascript");
    javaScriptPane.setEditorKit(kit);
    javaScriptPane.getDocument().putProperty("mimeType", "text/javascript");

    Note that "javaScriptPane" above is simply a JEditorPane.

  • Timon Veenstra's excellent solution for integrating Nodes with MultiViewElements, which is described here by Timon, and nowhere else in the world. The tab you see above is within a pluggable container, so anyone else could create a new module and register their own MultiViewElement such that it will be incorporated into the editor.

  • A small trick to ensure that only one window opens per news item:
    @NbBundle.Messages("OpenNews=Open")
    private class OpenNewsAction extends AbstractAction {
    
        public OpenNewsAction() {
            super(Bundle.OpenNews());
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            News news = getLookup().lookup(News.class);
            Mode editorMode = WindowManager.getDefault().findMode("editor");
            for (TopComponent tc : WindowManager.getDefault().getOpenedTopComponents(editorMode)) {
                if (tc.getDisplayName().equals(news.getTitle())) {
                    tc.requestActive();
                    return;
                }
            }
            TopComponent tc = MultiViews.createMultiView("application/x-newsnode", NewsNode.this);
            tc.open();
            tc.requestActive();
        }
    
    }

The rest of what you see above is all standard NetBeans Platform stuff. The sources of everything you see above is here:

http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.3/misc/CMSBackOffice

Monday Nov 26, 2012

org.openide.awt.ColorComboBox

It's the time of year when a lot of NetBeans Platform tutorials are being reassessed, reviewed, revised, and rewritten. Today I'm looking at the NetBeans Platform Paint Application Tutorial and updating it for NetBeans Platform 7.3.

Suddenly I remembered seeing something in a recent API Changes document about a new class, ColorComboBox. That means I can make the tutorial a lot simpler, since Tim Boudreau's external ColorChooser.jar is now superfluous. Here's what the ColorComboBox looks like:

It works perfectly. Of course, the nice thing about using that JAR was that it showed the user how to incorporate external JARs, but I'll make sure to make a note of that in the tutorial, along the lines of "If you don't like the NetBeans Platform color combobox, and would like to replace it with your own, such as Tim's ColorChooser.jar or a JavaFX color chooser, take the following steps."

In short, if you're using NetBeans APIs, write this on your ceiling above your bed: http://bits.netbeans.org/dev/javadoc/apichanges.html, check that page regularly (mark it in your calendar to do first thing every Monday morning) and you'll be aware of the latest changes as they happen.

Friday Nov 23, 2012

YouTube: JavaFX and NetBeans Platform Integration

Spend 7 minutes of your life and see the benefits of JavaFX and the benefits of the NetBeans Platform, all at the same time in the context of a single application:

Thursday Nov 22, 2012

Oracle DB, Oracle ADF, GlassFish, JDeveloper, NetBeans IDE

Today I started some experiments with Oracle guru Steven Davelaar, who lives about 20 minutes away from my place in Amsterdam by underground. Very convenient. He showed me a bunch of things in JDeveloper, while I showed him a bunch of things in NetBeans IDE.

He managed to deploy an ADF application to GlassFish in JDeveloper. And, so far, I failed to do the same thing in NetBeans IDE. Quite a few (around 100) JARs are needed, aside from the question of correctly setting up or importing an ADF application, and we're still figuring out which and who and when and where. And how. And if. And why.

Nonetheless, I did manage to get Oracle DB set up in NetBeans IDE, after downloading it from here:

http://www.oracle.com/technetwork/products/express-edition/downloads/index.html

Here's what it looks like when registered in NetBeans IDE, i.e., notice that I have a cool sample database available:

 

Data from the above database I managed to display very easily via the various NetBeans code generators in a PrimeFaces application, exactly as has been done many times in demonstrations and tutorials everywhere, i.e., generate JPA entities, then create an EJB, then inject the EJB into a PrimeFaces data table:

The next step is to somehow do the same with ADF in NetBeans IDE.

I had some trouble with passwords for Oracle DB, the command line (with Steven's help) proved helpful:

Wish us luck as we continue our ADF-inspired journey. This blog entry by Shay is also relevant:

Deploying Oracle ADF Essentials Applications to Glassfish

Wednesday Nov 21, 2012

Draggable & Resizable Editors

Thanks to a cool tip from Steven Yi (here in the comments to a blog entry), I was able to make a totally pointless but fun set of draggable and resizable editors:

What you see above are two JEditorPanes within JPanels. The JPanels are within ComponentWidgets provided by the NetBeans Visual Library, which is also where the special border comes from. The ComponentWidgets are within a Visual Library Scene, which is within a JScrollPane in a TopComponent.

Each editor has this, which means the NetBeans Java Editor is bound to the JEditorPane:

jEditorPane1.setContentType("text/x-java");
EditorKit kit = CloneableEditorSupport.getEditorKit("text/x-java");
jEditorPane1.setEditorKit(kit);
jEditorPane1.getDocument().putProperty("mimeType", "text/x-java");

A similar thing is done in the other JEditorPane, i.e., it is bound to the XML Editor. While the XML Editor also has code completion, in addition to syntax coloring, as can be seen above, this is not the case for the JEditorPane bound to the Java Editor, since the JEditorPane doesn't have a Java classpath, which is needed for Java code completion to work.

Tuesday Nov 20, 2012

Hydraulic Modeling Software

Fudaa-Crue is hydraulic modeling software, developed by Genesis on the NetBeans Platform.

More screenshots here:

https://fudaa-project.atlassian.net/wiki/display/CRUE/Copies+d%27ecran

YouTube movie, with French texts:

Another video about the application's usage of the Visual Library is under preparation. A more extensive article, including an interview with the team behind this software, will be published soon.

Monday Nov 19, 2012

Free & Open Source XML Editor Built on Maven

Here you can download the sources of an XML Editor that uses libraries from NetBeans IDE 7.3 Beta 2 as its basis, while using Maven as its build system:

http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.3/misc/XMLEditorInMavenNBRCP

And here's what it looks like to the user:

Note: The Favorites window has been rebranded as "File Browser" and Nimbus is used for the look and feel, thanks to a .conf file that is registered in the POM of the application project. 

The cool part is that I didn't type one line of code to get the above result and that only those pieces that an XML Editor actually needs are included in the application, though it could be pruned even further.

Sunday Nov 18, 2012

Hibernate, PostgreSQL, Ubuntu, NetBeans IDE (Part 3)

To complete the picture, let's use the traditional (that is, old) Hibernate mechanism, i.e., via XML files, rather than via the annotations shown yesterday. It's definitely trickier, with many more places where typos can occur, but that's why it's the old mechanism. I do not recommend this approach. I recommend the approach shown yesterday. The other players in this scenario include PostgreSQL, as outlined in the previous blog entries in this series.

Here's the structure of the module, replacing the code shown yesterday:

Here's the Employee class, notice that it has no annotations:

import java.io.Serializable;
import java.util.Date;

public class Employees implements Serializable {
    
    private int employeeId;
    private String firstName;
    private String lastName;
    private Date dateOfBirth;
    private String phoneNumber;
    private String junk;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getJunk() {
        return junk;
    }

    public void setJunk(String junk) {
        this.junk = junk;
    }

}

And here's the Hibernate configuration file:

<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/smithdb</property>
        <property name="hibernate.connection.username">smith</property>
        <property name="hibernate.connection.password">smith</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="hibernate.default_schema">public"</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="org/db/viewer/employees.hbm.xml"/>
    </session-factory>
</hibernate-configuration> 

Next, the Hibernate mapping file:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="org.db.viewer.Employees" 
           table="employees" 
           schema="public" 
           catalog="smithdb">

        <id name="employeeId" column="employee_id" type="int">
            <generator class="increment"/>
        </id>

        <property name="firstName" column="first_name" type="string" />
        <property name="lastName" column="last_name" type="string" />
        <property name="dateOfBirth" column="date_of_birth" type="date" />
        <property name="phoneNumber" column="phone_number" type="string" />
        <property name="junk" column="junk" type="string" />
        
    </class>
    
</hibernate-mapping>

Then, the "HibernateUtil" file, for providing centralized access to the Hibernate "SessionFactory":

import java.net.URL;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            String res = "org/db/viewer/employees.cfg.xml";
            URL myURL = Thread.currentThread().getContextClassLoader().getResource(res);
            sessionFactory = new AnnotationConfiguration().configure(myURL).buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
}

Finally, the "createKeys" in the ChildFactory:

@Override
protected boolean createKeys(List list) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transac = null;
    try {
        transac = session.beginTransaction();
        Query query = session.createQuery("from Employees");
        list.addAll(query.list());
    } catch (HibernateException he) {
        Exceptions.printStackTrace(he);
        if (transac != null){
            transac.rollback();
        }
    } finally {
        session.close();
    }
    return true;
}

Note that Constantine Drabo has a similar article here.

Run the application and the result should be the same as yesterday.

Saturday Nov 17, 2012

Hibernate, PostgreSQL, Ubuntu, NetBeans IDE (Part 2)

Now let's create the start of a CRUD application on the NetBeans Platform, using Hibernate and PostgreSQL to do so. Here's what I see in NetBeans IDE after setting things up as outlined yesterday:


The NetBeans Platform CRUD Tutorial should get you up and started creating the NetBeans Platform application. Open the generated "persistence.xml" in Design mode and then switch the persistence library to Hibernate. Then the rest should be the same as described in the tutorial.

Here's the application structure I ended up with at the end, with the difference that PostgreSQL and Hibernate are now used instead of Java Derby and EclipseLink:

The Hibernate module that you see above has this content:


Here's the result when I run the application, i.e., the data shown in the first screenshot above is now displayed as Nodes in a TopComponent:

And here's the source code:

http://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.3/misc/NBPostgreSQL

Friday Nov 16, 2012

Hibernate, PostgreSQL, Ubuntu, NetBeans IDE (Part 1)

While setting up PostgreSQL from scratch, with the aim to use it in NetBeans IDE together with Hibernate, I found the following resources helpful:

http://railskey.wordpress.com/2012/05/19/postgresql-installation-in-ubuntu-12-04/

http://ohdevon.wordpress.com/2011/09/17/postgresql-to-netbeans-1/

http://ohdevon.wordpress.com/2011/09/19/postgresql-to-netbeans-2/

For quite a while I had problems relating to  "/var/run/postgresql/.s.PGSQL.5432", which had something to do with "postmaster.pid", which I somehow solved via a link I can't find anymore, and which may not have been a problem to begin with.

A key moment was this one, which was useful for setting the password of a new user I'd created:

http://stackoverflow.com/questions/7695962/postgresql-password-authentication-failed-for-user-postgres

This was useful for setting up a table in my database, which I did by pasting in the below into NetBeans after I made the connection there:

http://use-the-index-luke.com/sql/example-schema/postgresql/where-clause

Now I have a database set up with all permissions everywhere (which turned out to be the hard part) correct:

The next step will be to create a NetBeans Platform application based on this database. I'm assuming it shouldn't be any different to what's described in the NetBeans Platform CRUD Tutorial. But I'll be using Hibernate, instead of EclipseLink.

Monday Nov 12, 2012

Bricks & Bricklets at Devoxx

I will also be giving away a Tinkerforge starter kit!

Saturday Nov 10, 2012

Live Updates in PrimeFaces Line Chart

In the Facelets file:

<p:layoutUnit position="center">
    <h:form>
        <p:poll 
            interval="3" 
            update=":chartPanel" 
            autoStart="true" /> 
    </h:form>
    <p:panelGrid 
        columns="1" 
        id="chartPanel">
        <p:lineChart 
            xaxisLabel="Time"
            yaxisLabel="Position"
            value="#{chartController.linearModel}"
            legendPosition="nw" 
            animate="true"
            style="height:400px;width: 1000px;"/>
    </p:panelGrid>
</p:layoutUnit>

The controler:

import java.io.Serializable;
import javax.inject.Named;
import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.ChartSeries;

@Named
public class ChartController implements Serializable {

    private CartesianChartModel model;

    public ChartController() {
        createLinearModel();
    }

    private void createLinearModel() {
        model = new CartesianChartModel();
        model.addSeries(getStockChartData("Stock Chart"));
    }

    private ChartSeries getStockChartData(String label) {
        ChartSeries data = new ChartSeries();
        data.setLabel(label);
        for (int i = 1; i <= 20; i++) {
            data.getData().put(i, (int) (Math.random() * 1000));
        }
        return data;
    }

    public CartesianChartModel getLinearModel() {
        return model;
    }

}

Based on this sample.

What I need is, instead of the for loop, to have an incrementing index to be shown, i.e., each second should be displayed on the x axis, which should increment dynamically per second. Can anyone help?

Friday Nov 09, 2012

Smart Meter Management on the NetBeans Platform

Netinium® NCC is the operator console for the Netinium® AMM+ platform, a Head End system for multi-vendor smart meter and smart grid infrastructures.

The role based NCC provides a uniform operations environment for grid operators and utilities to securely manage millions of smart meters, in-home displays and other smart devices using different types of communication networks such as IP, PLC, GPRS, CDMA and BPL.

Based on the NetBeans Platform, the NCC offers the flexibility to easily extend the GUI with new functionality when new devices are added to the system. 

For more information visit http://www.netinium.com.

Thursday Nov 08, 2012

AgroSense in Java Magazine November/December 2012

AgroSense, the Duke's Choice Award winning open source farm management system from the Netherlands, is featured in the hot-off-the-presses latest edition of the always awesome Java Magazine (November/December 2012):

Read the whole article after subscribing for free to the magazine, via clicking the image above or by clicking this link.

Note: If you're reading this and your sofware organization is doing anything at all that relates to farm management, consider porting your software to an AgroSense plugin. That would save you an immense amount of time and your users will get a comprehensive farm management system out of the box. Don't reinvent the wheel: create your farm management software on top of the AgroSense Platform!

Wednesday Nov 07, 2012

Words Don't Mean What They Meant Anymore

Here are some words which, when I use them nowadays, mean completely different things to what they originally meant. As a reminder to technical people out there, I'm providing the actual (or at least, my short cut definition made up on the spot) definition of these words, i.e., as normal people understand them.

Consider this a friendly service for normal conversation, as opposed to "nerd speak". You're welcome.

  • WAR: armed conflict between two or more countries

  • EAR: natural hearing devices attached to both sides of head

  • JAR: container for drinkable fluids, e.g., milk

  • TAR: dark fluid substance that hardens roads

  • ZIP: device sown into pants for simplified access during bathroom visits

There are probably more, e.g., "mine" and "farm", both of which relate to hard work in the open air...

Tuesday Nov 06, 2012

EJB Exposed As RESTful Web Service

Here's the kind of URL I want to support:

http://localhost:12663/myapp/webresources/customers/Miami 

And here's the EJB that exposes a method as a RESTful web service:

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/customers")
@Stateless
public class CustomerSessionBean {

    @PersistenceContext
    EntityManager em;
    
    @GET
    @Path("{city}")
    @Produces("application/xml")
    public List<Customer> getCustomersByCity(@PathParam("city") String city) {
        Query cityQuery = em.createNamedQuery("Customer.findByCity");
        cityQuery.setParameter("city",city);
        return cityQuery.getResultList();
    }
    
    public List<Customer> getCustomers() {
        return em.createNamedQuery("Customer.findAll").getResultList();
    }

}

Monday Nov 05, 2012

Gradle Support in NetBeans IDE 7.2

Russel Winder and Steve Chin spent half an hour, and then gave up, setting up NetBeans IDE to use Gradle, because they couldn't find the NetBeans Gradle plugin, during Steve's NightHacking tour. That need happen no more because Attila Kelemen's NetBeans Gradle plugin is now available in the Plugin Manager in NetBeans IDE 7.2:

Aside from opening Gradle-based applications, you can now also create new ones:


Details and documentation: https://github.com/kelemen/netbeans-gradle-project

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« November 2012 »
SunMonTueWedThuFriSat
    
11
13
14
15
24
25
 
       
Today