Thursday Apr 24, 2014

Meaningful HTML/Java DukeScript Framework Applications (Part 2)

OK, so now the application I started working on is even more meaningful.

Firstly, what is it all about? Well, with the DukeScript Framework, you use Java to write application logic, with HTML5 to render the UI. No Swing. No JavaFX. HTML takes the place of those toolkits. Then you can manipulate the HTML page from Java, use REST or WebSockets, and do anything else with Java that you might want to do.

So here's the state of my CRUD app right now, i.e., still only R, but with improved code (thanks Jarda), and now the selected customer is displayed when a row is selected. 

Let's start by looking at the HTML file that defines the above.

<html>
    <body>
        <h1>Sample Database</h1>
        <table border="1">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>City</th>
                    <th>State</th>
                    <th>Mail</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: customers">
                <tr data-bind="click: $root.selectCustomer" style="cursor: pointer">
                    <td data-bind="text: name"></td>
                    <td data-bind="text: city"></td>
                    <td data-bind="text: state"></td>
                    <td data-bind="text: email"></td>
                </tr>
            </tbody>
        </table>
        <br/>
        <b>Current Selection</b>
        <p data-bind="with: selectedCustomer">
            <font color="red">Name</font>: <span data-bind="text: name"> </span>
            <br/>
            <font color="red">City</font>: <span data-bind="text: city"> </span>
        </p>
    </body>
</html>

What you see here is plain HTML together with Knockout bindings. The rows in the table are bound to properties in the model. When a row is selected, a method in the model is called that changes a property, which is bound with the Knockout "with" binding so that the currently selected name and city are shown.

Here's the definition of the Main class, which is annotated with the @Model annotation, and can be understood as a singleton:

@Model(className = "CrudApp", properties = {
    @Property(name = "selectedCustomer", type = CustomerData.class),
})
public final class Main {
    @ComputedProperty
    static java.util.List<CustomerData> customers() {
        EntityManager entityManager
                = Persistence.createEntityManagerFactory("myPU").
                createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findAll");
        List<CustomerData> arr = new ArrayList<>();
        for (Object object : query.getResultList()) {
            arr.add(((Customer) object).getData());
        }
        return arr;
    }
    @Function
    static void selectCustomer(CrudApp myModel, CustomerData data) {
        myModel.setSelectedCustomer(data);
    }
    private Main() {
    }
    /**
     * Launches the browser
     */
    public static void main(String... args) throws Exception {
        BrowserBuilder.newBrowser().
                loadPage("pages/index.html").
                loadClass(Main.class).
                invoke("onPageLoad", args).
                showAndWait();
        System.exit(0);
    }
    /**
     * Called when page is ready
     */
    public static void onPageLoad(String... args) throws Exception {
        new CrudApp().applyBindings();
    }
}

There's also a Customer POJO, i.e., a JPA entity, which in addition to the JPA annotations is annotated as follows:

@Model(className = "CustomerData", properties = {
    @Property(name = "name", type = String.class),
    @Property(name = "addressline1", type = String.class),
    @Property(name = "addressline2", type = String.class),
    @Property(name = "city", type = String.class),
    @Property(name = "state", type = String.class),
    @Property(name = "phone", type = String.class),
    @Property(name = "fax", type = String.class),
    @Property(name = "email", type = String.class),
    @Property(name = "creditLimit", type = int.class)
})

Plus, there's a getter that returns the CustomerData, so that the "customers()" method in the Main class can build up the list of customers.

The next step is to persist the data back into the database. Weird to be manipulating the DOM from Java but, obviously, great. 

Wednesday Apr 23, 2014

Register Today for Virtual Developer Day!

Virtual Developer Day: Java 2014 is on May 6th (Americas), May 14th (EMEA), and May 21st (APAC).

Hear from experts on Java SE 8, Java EE 7, and Java Embedded.

Watch tutorials from the experts to improve your expertise in Java, and ask questions during live chats. This FREE virtual event will cover:

  • Java SE 8 New Features: Lambdas and more
  • The latest on the Java EE 7
  • How Java makes it easy for you to control a wide range of embedded devices

Go here to register.

Tuesday Apr 22, 2014

Meaningful HTML/Java DukeScript Framework Applications (Part 1)

In an effort to make a meaningful application on the DukeScript Framework, here's the start of a JPA-based CRUD app (right now, only R is supported):

There are three parts to this.

  1. Model. I generated JPA entity classes from my database. I ended up with the "Customer" class, which has relationships with "DiscountCode" and "MicroMarket". Then I added a new annotation, on top of all the JPA annotations, to the "Customer" class:
    @Model(className = "CustomerData", properties = {})

    Then, in the same class, i.e., in "Customer", I exposed the data as follows:

    @ComputedProperty
    static java.util.List customers() {
        EntityManager entityManager
                = Persistence.createEntityManagerFactory("myPU").
                createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findAll");
        return query.getResultList();
    }
  2. Controler. In the Main class, I changed "onPageLoad" to this:
    public static void onPageLoad(String... args) throws Exception {
        new CustomerData().applyBindings();
    }
  3. View. Finally, the "index.html" that is bound to the model is as follows:
    <html>
        <body>
            <h1>Sample Database</h1>
            <table border="1">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>City</th>
                        <th>State</th>
                        <th>Mail</th>
                    </tr>
                </thead>
                <tbody data-bind="foreach: customers">
                    <tr>
                        <td data-bind="text: $data.getName()"></td>
                        <td data-bind="text: $data.getCity()"></td>
                        <td data-bind="text: $data.getState()"></td>
                        <td data-bind="text: $data.getEmail()"></td>
                    </tr>
                </tbody>
            </table>
            <p>
        </body>
    </html>

Notice that the method "customers()" in the model is bound in the "foreach" in the view.

Probably I'm doing all kinds of things wrong. Probably I should be using properties in the model. Happy to be corrected. 

Monday Apr 21, 2014

Entity Expander for NetBeans IDE 8 (Part 5)

Now package-level expansion is supported:


When you select a template while on a package, as above, all Java classes within the package are all transformed at the same time, for example, choosing "Panel" above results in the below all being added in one go:

Go here to get it:

http://plugins.netbeans.org/plugin/53874

Sunday Apr 20, 2014

Themes for NetBeans JPA Modeler

The latest release, which came out today, of the awesome JPA Modeler plugin for NetBeans (by Gaurav Gupta) provides a theme switcher. Click to enlarge the image below.

Not one line of code in the many classes you see above was created by me. Instead, they were all generated from the diagram, which was generated from my database.

Get it here:

http://plugins.netbeans.org/plugin/53057/jpa-modeler

Saturday Apr 19, 2014

Entity Expander for NetBeans IDE 8 (Part 4)

Toni suggested it would be cool to create some templates for Nodes, ChildFactories, and TopComponents, on top of POJOs, for the Entity Expander that I blogged about last month

That way, NetBeans would have the start of something like EMF in Eclipse.

So, here are the templates I have so far.

Node ("BeanNode"):

package ${package};

import java.beans.IntrospectionException;
import java.util.List;
import javax.swing.Action;
import org.openide.nodes.BeanNode;
import org.openide.util.Utilities;

public class ${object}BeanNode extends BeanNode {
    
    public ${object}BeanNode(${object} bean) throws IntrospectionException {
        super(bean);
        //setDisplayName();
        //setShortDescription();
    }

    @Override
    public Action[] getActions(boolean context) {
        List myActions = 
            Utilities.actionsForPath("Actions/${object}");
        return myActions.toArray(new Action[myActions.size()]);
    }

}

Child Factory ("BeanChildFactory"):

package ${package};

import java.beans.IntrospectionException;
import java.util.List;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;

public class ${object}BeanChildFactory extends ChildFactory<${object}> {
    
    @Override
    protected boolean createKeys(List<${object}> toPopulate) {
        //connect to data source
        //and populate "toPopulate" list
        return true;
    }
    
    @Override
    protected Node createNodeForKey(${object} key) {
        ${object}BeanNode cbn = null;
        try {
            cbn = new ${object}BeanNode(key);
        } catch (IntrospectionException ex) {
            Exceptions.printStackTrace(ex);
        }
        return cbn;
    }
    
}

TopComponent ("ViewerTopComponent"):

package ${package};

import java.awt.BorderLayout;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;

@TopComponent.Description(
        preferredID = "${object}ViewerTopComponent",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
        mode = "explorer", 
        openAtStartup = true)
@ActionID(category = "Window", 
        id = "${package}.${object}ViewerTopComponent")
@ActionReference(
        path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_${object}ViewerAction",
        preferredID = "${object}ViewerTopComponent"
)
@Messages({
    "CTL_${object}ViewerAction=${object}Viewer",
    "CTL_${object}ViewerTopComponent=${object}Viewer Window",
    "HINT_${object}ViewerTopComponent=This is a ${object}Viewer window"
})
public class ${object}ViewerTopComponent extends TopComponent implements ExplorerManager.Provider {
    
    private ExplorerManager em = new ExplorerManager();

    public ${object}ViewerTopComponent() {
        setName(Bundle.CTL_${object}ViewerTopComponent());
        setToolTipText(Bundle.HINT_${object}ViewerTopComponent());
        setLayout(new BorderLayout());
        //somehow create your children:
        //Children.create(new MyChildFactory(), true);
        Node rootNode = new AbstractNode(Children.LEAF);
        em.setRootContext(rootNode);
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return em;
    }

}

Friday Apr 18, 2014

org.netbeans.spi.palette.PaletteItemRegistration

With APIs from NetBeans IDE 8.0, there's the new annotations @PaletteItemRegistration and @PaletteItemRegistrations for registering items in a palette:

As you can see, you use the annotations in the package-info.java class, which you can create by using the template Java | Java Package Info in the New File dialog.

References:

http://bits.netbeans.org/dev/javadoc/org-netbeans-spi-palette/org/netbeans/spi/palette/PaletteItemRegistrations.html

http://bits.netbeans.org/dev/javadoc/org-netbeans-spi-palette/org/netbeans/spi/palette/PaletteItemRegistration.html

Therefore, will need to update this tutorial with the new annotations:

https://platform.netbeans.org/tutorials/nbm-palette-api1.html

Thursday Apr 17, 2014

Three Tips for DukeScript Fanboys

Here's my advice for DukeScript fanboys, of which there are some, but mainly two: Jaroslav Tulach and Toni Epple.

  1. Stop talking about "DukeScript". Whenever you say "DukeScript", any sane person assumes you're talking about a language. You're not. And that's what's confusing. You're talking about a framework. The DukeScript Framework is equivalent to HTML5 minus JavaScript plus Java. That's it. And that's a powerful message.

  2. Stop playing games. Instead, create real applications. Create CRUD applications, for example. Here's my humble first beginning, showing data from the Sample database in GlassFish displayed in HTML via Java in the JavaFX WebView thanks to the DukeScript Framework:

    But, please, make several complete scenarios that run out of the box, including, and especially, CRUD apps. This is where Vaadin and PrimeFaces have succeeded so far, i.e., they have complete widget samples, component demos, etc, etc, etc. Focus on business scenarios, not funny games.

  3. Seriously, sit down and think about all that stuff that you're exposing. Vaadin somehow gets away with it, because they're based on a known entity, i.e., GWT, and the DukeScript Framework should be able to do so, too. There's just so much going on in the background, it's scary. Somehow, you need to at least explain absolutely everything. Either shit or get off the pot, i.e., describe fully what's going on in the implementation or accept that it's going to be adopted by a small subset of developers. Since all the ideas in the DukeScript Framework are so completely brand new and so much magic is done via annotations, you either explain it all, down to the smallest details, or run the risk that no one will adopt it because, since there are several more understandable competitors, you're running the risk that something simpler, e.g., Vaadin, is going to become the standard, whether de-facto or not.
My two cents. And I have never been (very) wrong.

Wednesday Apr 16, 2014

Swedish Economy Modeling on the NetBeans Platform

WamSys AB, located in Gothenburg, Sweden, focuses on developing products with Oracle DB and the NetBeans Platform.

In particular, the NetBeans Platform is used as the basis of their Mozart Platform, which provides generic modules for custom Swing components, including a table component with support for grouping, "frozen" rows and columns, and built-in aggregates.

Furthermore, the Mozart Platform facilitates the building of products on top of it. For example, it has its own widget framework, providing a customizable start page comparable to a web portal, while the Options window manages look & feel properties, such as support for switching to the JTattoo look and feel.

Here you can see a YouTube clip of the Mozart table component:

https://www.youtube.com/watch?v=KTm6IrsTzDM

And here is a YouTube clip of the Mozart dashboard:

https://www.youtube.com/watch?v=o6nn4ns52t8

One of the products based on the Mozart Platform is Mozart Economy, a fully customizable billing system able to calculate fees based on complex conditions and provide data for invoicing. The system is used by Swedish schools for calculation of fees paid in preschool, where many different factors affect the price, such as the child's age, family income, and number of hours at school. The module corrects invoices over any period back in time with respect to changed conditions over time.

Another part of the solution is Mozart Statistics, which retrieves data from a database and creates statistical reports in Microsoft Excel, using the Apache POI library.  This enables customers to get powerful statistical reports with pivot tables and various type of charts.


Tuesday Apr 15, 2014

DukeScript Framework for Dummies

Jaroslav Tulach's Java/JavaScript framework DukeScript explained for dummies (e.g., me):

Or watch it here:

https://www.youtube.com/watch?v=v3ITo889ypI

Further info:

http://wiki.apidesign.org/wiki/DukeScript

http://www.slideshare.net/steveonjava/dukescript

http://nighthacking.com/dukescript-with-toni-epple/

Friday Apr 11, 2014

Python in NetBeans IDE 8.0

Copy this to the clipboard:

http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastStableBuild/artifact/nbbuild/nbms/updates.xml.gz

Then go to Tools | Plugins and open the Settings tab. Add the above as a new update center:

Then switch to the Available Plugins tab and you'll see the Python plugin:

Install the Python plugin:

Then create a new Python project, using the New Project dialog:

Give it a name and choose your platform. Either import existing sources as a new Python project...

...or create a Python project from scratch:

Then you have an editor with code completion, other editor features, plus a debugger:

Right-click a project to see a bunch of Python commands:

Add to the classpath after right-clicking a project and choosing Properties:

That's it, you're now ready to use Python in NetBeans IDE.

Thursday Apr 10, 2014

Context-Sensitive TopComponent (Part 2)

Another way a TopComponent can be context sensitive is in the requirement that the menubar and toolbar need to relate to a specific TopComponent. Below you see that when Win1 is active, a different group of menus and toolbars is available...

... than when Win2 is active:


Part of the solution to this is described here recently about multiple rows of toolbars. However, this only addresses the topic of toolbars. What about menubars? And maybe other components too? I.e., when a TopComponent is active, it would be great if a subfolder of the FileSystem would become enabled, while all other parts would become disabled.

The complete solution to this scenario has been described before, here. Jesse Glick has all the code for this here:

https://bitbucket.org/jglick/dynamicmenudemo

What the above lets you do is create layer entries like this:

<folder name="win1">
    <folder name="Menu">
        <folder name="First">
            <attr name="position" intvalue="150"/>
        </folder>
        <file name="Help.hidden"/>
    </folder>
    <folder name="Toolbars">
        <file name="UndoRedo.hidden"/>
    </folder>
</folder>
<folder name="win2">
    <folder name="Menu">
        <folder name="Second">
            <attr name="position" intvalue="250"/>
        </folder>
    </folder>
</folder>

Then, each TopComponent can specify which folder they want to own:

associateLookup(Lookups.singleton(new SystemSubPathLayerProvider("win1")));

The "SystemSubPathLayerProvider" does all the work in the background to enable and disable items appropriately, whether they are toolbars, menubars, or whatever else.

Nothing is written to disk, this is all done programmatically within the code, and not written to the user directory.

Wednesday Apr 09, 2014

Context-Sensitive TopComponent (Part 1)

I picked up a cool idea from a Polish developer, Dominik Cebula, recently. In the same way that the NetBeans Platform has context sensitive Actions, there should be context sensitive TopComponents.

Only if an Object of a specific type specified in the public constructor of the TopComponent is found in the Lookup should it be possible to open the TopComponent. And then the Object is available to the TopComponent, without the TopComponent needing to implement a LookupListener.

For example, below "FlightLeg Editor" and "Delay Editor" are both disabled, because no "FlightLeg" and no "Delay" is in the Lookup. Hence it doesn't make sense to open the editor, i.e., when the Object for which the editor exists is not available.


On the other hand, below a "FlightLeg" is available in the Lookup, because one of the flight legs has been selected and hence the underlying "FlightLeg" object is now in the Lookup. Therefore, the "FlightLeg Editor" menu item is enabled so that an editor can be opened for editing the selected flight leg:


In the same way, here the "Delay Editor" can be opened, because an Object of the type "Delay" is published when a DelayNode is selected:


Here is one of these TopComponents:

@TopComponent.Description(
        preferredID = "FlightLegEditorTopComponent",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
        mode = "editor", 
        openAtStartup = false)
@ActionID(
        category = "Window", 
        id = "org.cool.viewer.FlightLegEditorTopComponent")
@ActionReference(
        path = "Menu/Window")
@ObjectTopComponent.OpenActionForObjectRegistration(
        displayName = "#CTL_EditorAction",
        preferredID = "FlightLegEditorTopComponent"
)
@NbBundle.Messages({
    "CTL_EditorAction=FlightLeg Editor",
})
public class FlightLegEditorTopComponent extends ObjectTopComponent implements ActionListener{
    private FlightLeg fl;
    //no-arg constructor is required:
    private FlightLegEditorTopComponent() {}
    public FlightLegEditorTopComponent(FlightLeg fl) {
        this.fl = fl;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        setDisplayName(fl.getName());
        open();
        requestActive();
    }
}

In the above, notice there is a public constructor that receives the domain object "FlightLeg" (i.e., for an airline-type application). Also, there's a new annotation up there, "@ObjectTopComponent.OpenActionForObjectRegistration".

Here's what that annotation looks like (copied and then simply renamed from "@TopComponent.OpenActionRegistration"):

public class ObjectTopComponent extends TopComponent {
    @Retention(RetentionPolicy.SOURCE)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    public static @interface OpenActionForObjectRegistration {
        String displayName();
        String preferredID() default "";
    }
} 

However, the annotation above is processed in such a way that a context-sensitive Action is created that uses the type in the constructor of the TopComponent:

@SupportedSourceVersion(SourceVersion.RELEASE_6)
@ServiceProvider(service = Processor.class)
public final class ObjectTopComponentProcessor extends LayerGeneratingProcessor {
    public ObjectTopComponentProcessor() {
    }
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> hash = new HashSet<String>();
        hash.add(ObjectTopComponent.OpenActionForObjectRegistration.class.getCanonicalName());
        return hash;
    }
    @Override
    protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
        for (Element e : roundEnv.getElementsAnnotatedWith(ObjectTopComponent.OpenActionForObjectRegistration.class)) {
            ObjectTopComponent.OpenActionForObjectRegistration reg = e.getAnnotation(ObjectTopComponent.OpenActionForObjectRegistration.class);
            assert reg != null;
            Description info = findInfo(e);
            ActionID aid = e.getAnnotation(ActionID.class);
            if (aid != null) {
                File actionFile = layer(e).
                        file("Actions/" + aid.category() + "/" + aid.id().replace('.', '-') + ".instance").
                        methodvalue("instanceCreate", "org.openide.windows.TopComponent", "openAction");
                actionFile.instanceAttribute("component", TopComponent.class, reg, null);
                if (reg.preferredID().length() > 0) {
                    actionFile.stringvalue("preferredID", reg.preferredID());
                }
                generateContext(e, actionFile);
                actionFile.bundlevalue("displayName", reg.displayName(), reg, "displayName");
                if (info != null && info.iconBase().length() > 0) {
                    actionFile.stringvalue("iconBase", info.iconBase());
                }
                actionFile.write();
            }
        }
        return true;
    }
    private void generateContext(Element e, File f) throws LayerGenerationException {
        ExecutableElement ee = null;
        ExecutableElement candidate = null;
        for (ExecutableElement element : ElementFilter.constructorsIn(e.getEnclosedElements())) {
            if (element.getKind() == ElementKind.CONSTRUCTOR) {
                candidate = element;
                if (!element.getModifiers().contains(Modifier.PUBLIC)) {
                    continue;
                }
                if (ee != null) {
                    throw new LayerGenerationException("Only one public constructor allowed", e, processingEnv, null); // NOI18N
                }
                ee = element;
            }
        }
        if (ee == null || ee.getParameters().size() != 1) {
            if (candidate != null) {
                throw new LayerGenerationException("Constructor has to be public with one argument", candidate);
            }
            throw new LayerGenerationException("Constructor must have one argument", ee);
        }
        VariableElement ve = (VariableElement) ee.getParameters().get(0);
        TypeMirror ctorType = ve.asType();
        switch (ctorType.getKind()) {
            case ARRAY:
                String elemType = ((ArrayType) ctorType).getComponentType().toString();
                throw new LayerGenerationException("Use List<" + elemType + "> rather than " + elemType + "[] in constructor", e, processingEnv, null);
            case DECLARED:
                break; // good
            default:
                throw new LayerGenerationException("Must use SomeType (or List<SomeType>) in constructor, not " + ctorType.getKind());
        }
        DeclaredType dt = (DeclaredType) ctorType;
        String dtName = processingEnv.getElementUtils().getBinaryName((TypeElement) dt.asElement()).toString();
        if ("java.util.List".equals(dtName)) {
            if (dt.getTypeArguments().isEmpty()) {
                throw new LayerGenerationException("Use List<SomeType>", ee);
            }
            f.stringvalue("type", binaryName(dt.getTypeArguments().get(0)));
            f.methodvalue("delegate", "org.openide.awt.Actions", "inject");
            f.stringvalue("injectable", processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString());
            f.stringvalue("selectionType", "ANY");
            f.methodvalue("instanceCreate", "org.openide.awt.Actions", "context");
            return;
        }
        if (!dt.getTypeArguments().isEmpty()) {
            throw new LayerGenerationException("No type parameters allowed in ", ee);
        }
        f.stringvalue("type", binaryName(ctorType));
        f.methodvalue("delegate", "org.openide.awt.Actions", "inject");
        f.stringvalue("injectable", processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString());
        f.stringvalue("selectionType", "EXACTLY_ONE");
        f.methodvalue("instanceCreate", "org.openide.awt.Actions", "context");
    }
    private String binaryName(TypeMirror t) {
        Element e = processingEnv.getTypeUtils().asElement(t);
        if (e != null && (e.getKind().isClass() || e.getKind().isInterface())) {
            return processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString();
        } else {
            return t.toString(); // fallback - might not always be right
        }
    }
    private Description findInfo(Element e) throws LayerGenerationException {
        Element type;
        switch (e.asType().getKind()) {
            case DECLARED:
                type = e;
                break;
            case EXECUTABLE:
                type = ((DeclaredType) ((ExecutableType) e.asType()).getReturnType()).asElement();
                break;
            default:
                throw new LayerGenerationException("" + e.asType().getKind(), e);
        }
        TopComponent.Description info = type.getAnnotation(TopComponent.Description.class);
        return info;
    }
}
 

The above processor is a combination of the TopComponentProcessor and the ActionProcessor in the NetBeans Platform.

And now you have a layer generating processor that creates a context sensitive Action for opening a TopComponent. If no Object of the type specified in the constructor of the TopComponent is in the Lookup, the Action will be disabled. If an Object of the specified type is available, the Action is enabled and immediately available to the TopComponent as soon as it is opened.

That's an example of a view that is bound to a model. Useful for editors that need to be created for one or more specific Objects. Data binding for TopComponents, hurray.

Tuesday Apr 08, 2014

Disable Module on Authentication Failure

The user starts the application. The splash screen is shown. Right after the modules are loaded, as indicated by the text in the splash screen, a small login screen appears. The user fills in the wrong login credentials and clicks OK. The text in the splash screen shows that one or more modules are being turned off. Then the main window of the application appears. Because the login credentials were wrong, one or more of the modules have been disabled. 

import java.util.List;
import org.netbeans.api.autoupdate.OperationContainer;
import org.netbeans.api.autoupdate.OperationException;
import org.netbeans.api.autoupdate.OperationSupport;
import org.netbeans.api.autoupdate.UpdateElement;
import org.netbeans.api.autoupdate.UpdateManager;
import org.netbeans.api.autoupdate.UpdateUnit;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.modules.OnStart;
import org.openide.util.Exceptions;

@OnStart
public class Startable implements Runnable {
    @Override
    public void run() {
        NotifyDescriptor.InputLine nd = new NotifyDescriptor.InputLine("Name", "Login");
        //Got tired of typing it by hand:
        nd.setInputText("admin");
        Object response = DialogDisplayer.getDefault().notify(nd);
        if (response == NotifyDescriptor.OK_OPTION) {
            String username = nd.getInputText();
            NotifyDescriptor.Message msg;
            if (!username.equals("admin")) {
                List<UpdateUnit> updateUnits = 
                  UpdateManager.getDefault().getUpdateUnits(UpdateManager.TYPE.MODULE);
                for (UpdateUnit updateUnit : updateUnits) {
                    //Get each module that is installed:
                    UpdateElement el = updateUnit.getInstalled();
                    //Of those that are installed, if it has the code name base
                    //of the module we are interested in, and it is enabled,
                    //continue with this procedure to disable it:
                    if (el != null
                            && el.getCodeName().equals("com.mycompany.admin")
                            && el.isEnabled()) {
                        try {
                            //Specify how we want to handle the module; 
                            //here, we want to disable it:
                            OperationContainer oc = OperationContainer.createForDirectDisable();
                            oc.add(el);
                            //Finally, do the operation,
                            //passing a progress handle or, as in this case, null:
                            OperationSupport supp = (OperationSupport) oc.getSupport();
                            supp.doOperation(null);
                        } catch (OperationException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            }
        }
    }
}

Finally, the module is not shown in the Plugin Manager, so that it cannot be enabled from there. Only if the user logs in correctly is the module enabled.

Related reading:

Monday Apr 07, 2014

Multiple Rows of Toolbars

Realized today that toolbars can be placed in different rows:

The above is a result of a file I named "All.xml" that has this content and is found in the same package as the layer.xml file:

<?xml version="1.0"?>
<!DOCTYPE Configuration PUBLIC "-//NetBeans IDE//DTD toolbar//EN"
 "http://www.netbeans.org/dtds/toolbar.dtd">
<Configuration>
    <Row>
        <Toolbar name="File" />
    </Row>
    <Row>
        <Toolbar name="UndoRedo" />
        <Toolbar name="Clipboard"/>
    </Row>
    <Row>
        <Toolbar name="Memory"/>
    </Row>
</Configuration>

It is registered as follows in the layer.xml file:

<folder name="Toolbars">
    <file name="All.xml" url="All.xml"/>
</folder>

And then, as a handy final step, here's code in one of my TopComponents for switching between different toolbar definitions:

@Override
protected void componentActivated() {
    ToolbarPool.getDefault().setConfiguration("All");
}
@Override
public void componentDeactivated() {
    ToolbarPool.getDefault().setConfiguration("Standard");
}

Here's some related reading:

Sunday Apr 06, 2014

org.openide.awt.Actions.ButtonActionConnector

Handy, need to explore this further.

import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.JMenuItem;
import org.openide.awt.Actions;
import org.openide.awt.Actions.ButtonActionConnector;
import org.openide.util.lookup.ServiceProvider;
@ServiceProvider(
        service = ButtonActionConnector.class, 
        position = 100)
public class MyButtonActionConnector implements ButtonActionConnector {
   @Override
   public boolean connect(AbstractButton button, Action action) {
      String text = (String)action.getValue("displayName");
      if (text != null) {
         button.setAction(action);
         button.setText(Actions.cutAmpersand(text));
         String desc = (String)action.getValue(Action.SHORT_DESCRIPTION);
         if (desc != null) {
            button.setToolTipText(desc);
         } else {
            button.setToolTipText((String)action.getValue(Action.NAME));
         }
         return true;
      }
      return false;
   }
   @Override
   public boolean connect(JMenuItem item, Action action, boolean popup) {
       return false; // use default implementation
   }
} 

Further reading:

http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/Actions.ButtonActionConnector.html

http://anchialas.wordpress.com/2012/04/16/toolbar-icons-with-label/#comments

http://praxisintermedia.wordpress.com/2012/04/10/branding-project-action-icons/

Saturday Apr 05, 2014

Creating MultiViewElements on the Fly

Following from the above, here's how to add a new tab in the Java Editor, on the fly (as described here, possible from 8.0 onwards), i.e., when the "Design Custom Component" menu item (which is only available when you right-click a subclass of com.vaadin.ui.CustomComponent, as described yesterday) is clicked:

@Override
public void actionPerformed(ActionEvent ev) {
    dobj.getLookup().lookup(Openable.class).open();
    TopComponent activated = WindowManager.getDefault().getRegistry().getActivated();
    MultiViewHandler mvh = MultiViews.findMultiViewHandler(activated);
    mvh.addMultiViewDescription(new DesignerMVD(), 1);
}

In short, the above gets you this:


DesignerMVD, referenced above, is as follows:

import java.awt.Image;
import org.netbeans.core.spi.multiview.MultiViewDescription;
import org.netbeans.core.spi.multiview.MultiViewElement;
import org.openide.util.HelpCtx;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;

public class DesignerMVD implements MultiViewDescription {
    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_NEVER;
    }
    @Override
    public String getDisplayName() {
        return "Designer";
    }
    @Override
    public Image getIcon() {
        return null;
    }
    @Override
    public HelpCtx getHelpCtx() {
        return HelpCtx.DEFAULT_HELP;
    }
    @Override
    public String preferredID() {
        return "Designer";
    }
    @Override
    public MultiViewElement createElement() {
        return new DesignMVE(Utilities.actionsGlobalContext());
    }
}
 

And DesignerMVE is like this, i.e., a JPanel, which will later contain a Visual Library Scene that visualizes the content of the CustomComponent in some way, so that it can be graphically edited:

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import org.netbeans.core.spi.multiview.CloseOperationState;
import org.netbeans.core.spi.multiview.MultiViewElement;
import org.netbeans.core.spi.multiview.MultiViewElementCallback;
import org.openide.awt.UndoRedo;
import org.openide.loaders.DataObject;
import org.openide.util.Lookup;

public class DesignMVE extends JPanel implements MultiViewElement {
    private JToolBar toolbar = new JToolBar();
    private DataObject obj;
    public DesignMVE(Lookup lkp) {
        obj = lkp.lookup(DataObject.class);
        assert obj != null;
    }
    @Override
    public JComponent getVisualRepresentation() {
        return this;
    }
    @Override
    public JComponent getToolbarRepresentation() {
        toolbar.setFloatable(false);
        return toolbar;
    }
    @Override
    public Action[] getActions() {
        return new Action[0];
    }
    @Override
    public Lookup getLookup() {
        return obj.getLookup();
    }
    @Override public void componentOpened() {}
    @Override public void componentClosed() {}
    @Override public void componentShowing() {}
    @Override public void componentHidden() {}
    @Override public void componentActivated() {}
    @Override public void componentDeactivated() {}
    @Override
    public UndoRedo getUndoRedo() {
        return UndoRedo.NONE;
    }
    private transient MultiViewElementCallback callback;
    @Override
    public void setMultiViewCallback(MultiViewElementCallback mvec) {
        this.callback = mvec;
    }
    @Override
    public CloseOperationState canCloseElement() {
        return CloseOperationState.STATE_OK;
    }
}
 

Finally, the action for opening the DesignerMVD is slightly more complex because we don't want a new DesignerMVD whenever the Action is invoked. Specifically, we do not want a new DesignerMVD if the file is already open, since then a new DesignerMVD will already have been created. Hence (thanks to instructions here), we get this:

@Override
public void actionPerformed(ActionEvent ev) {
    //Need to make sure to add a designer
    //only if the file hasn't been opened yet,
    //otherwise we'll get a new designer
    //whenever the action is invoked:
    FileObject fileObject = dobj.getPrimaryFile();
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    if (javaSource != null) {
        try {
            javaSource.runUserActionTask(new Task<CompilationController>() {
                @Override
                public void run(CompilationController compilationController) throws Exception {
                    compilationController.toPhase(Phase.ELEMENTS_RESOLVED);
                    Document document = compilationController.getDocument();
                    if (document == null) {
                        dobj.getLookup().lookup(Openable.class).open();
                        TopComponent activated = WindowManager.getDefault().getRegistry().getActivated();
                        MultiViewHandler mvh = MultiViews.findMultiViewHandler(activated);
                        mvh.addMultiViewDescription(new DesignerMVD(), 1);
                    }
                }
            }, true);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 

A different approach might be to disable the Action when the file has been opened, so that it cannot be invoked again while the file is open, which means the above code would not be needed anymore.

The next step is to work on the Visual Library Scene, which will be contained within the JPanel above, together with a Palette (as described here) that contains all the relevant Vaadin components.

And then we'll have a Visual Designer for Vaadin!

Friday Apr 04, 2014

Popup Action Based on Java Subclass

Climb up the hierarchy (thanks to this) to determine whether a class is a subclass of com.vaadin.ui.CustomComponent and, if so, enable and display a popup menu on it so that it can be opened in a visual designer of some kind.

@ActionID(
        category = "Tools",
        id = "org.tc.customizer.DesignCustomComponentAction")
@ActionRegistration(
        displayName = "#CTL_DesignCustomComponentAction",
        lazy = false)
@ActionReferences({
    @ActionReference(path = "Loaders/text/x-java/Actions", position = 150)
})
@Messages("CTL_DesignCustomComponentAction=Design Custom Component")
public final class DesignAbstractFormAction extends AbstractAction implements ContextAwareAction {
    private final DataObject dobj;
    private static Map args = new HashMap();
    public DesignAbstractFormAction() {
        this(Utilities.actionsGlobalContext());
    }
    public DesignAbstractFormAction(Lookup context) {
        super(Bundle.CTL_DesignCustomComponentAction());
        this.dobj = context.lookup(DataObject.class);
        JavaSource javaSource = JavaSource.forFileObject(dobj.getPrimaryFile());
        if (javaSource != null) {
            try {
                javaSource.runUserActionTask(new ScanForObjectTask(this), true);
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        //Hide the menu item if it isn't enabled:
        putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
    }
    @Override
    public void actionPerformed(ActionEvent ev) {
        //Starting point for designer:
        TopComponent tc = new TopComponent();
        tc.setDisplayName(dobj.getName());
        tc.open();
        tc.requestActive();
    }
    @Override
    public Action createContextAwareInstance(Lookup actionContext) {
        return new DesignAbstractFormAction(actionContext);
    }
    private static class ScanForObjectTask implements Task<CompilationController&g; {
        private final DesignAbstractFormAction action;
        private ScanForObjectTask(DesignAbstractFormAction action) {
            this.action = action;
        }
        @Override
        public void run(CompilationController compilationController) throws Exception {
            compilationController.toPhase(Phase.ELEMENTS_RESOLVED);
            new MemberVisitor(compilationController, action).scan(
                    compilationController.getCompilationUnit(), null);
        }
    }
    private static class MemberVisitor extends TreePathScanner<Void, Void&g; {
        private CompilationInfo info;
        private final AbstractAction action;
        public MemberVisitor(CompilationInfo info, AbstractAction action) {
            this.info = info;
            this.action = action;
        }
        @Override
        public Void visitClass(ClassTree t, Void v) {
            Element el = info.getTrees().getElement(getCurrentPath());
            if (el != null) {
                TypeElement element = (TypeElement) el;
                Types typeUtils = info.getTypes();
                while (element!=null&&!element.toString().equals("com.vaadin.ui.CustomComponent")) {
                    element = (TypeElement) typeUtils.asElement(element.getSuperclass());
                    if (element!=null&&element.toString().equals("com.vaadin.ui.CustomComponent")) {
                        action.setEnabled(true);
                    } else {
                        action.setEnabled(false);
                    }
                }
            }
            return null;
        }
    }
}

Thursday Apr 03, 2014

YouTube: Vaadin/NetBeans Webinar

The webinar is live on YouTube. Watch how Matti the Vaadin guy deletes almost my entire application and replaces it with Vaadin:

Or click here to get there: https://www.youtube.com/watch?v=3TompuzySD8

Here's a pic of the after party with Matti, my co-presenter:

And the after after party in a viking restaurant with Fredrik, Matti, and Sami:


Wednesday Apr 02, 2014

Sign Up for Tomorrow's Vaadin/NetBeans Webinar!

Click the image above or click here to get to the sign up form!

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
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
24
25
26
27
28
29
30
   
       
Today