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

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!

Tuesday Apr 01, 2014

Dynamically Creating Menu Items (Part 2)

OK, following on from yesterday, here's the next part. What we want to do is click a button, such as shown below, and, when the button is clicked, cause a new menu item to be added to a predefined menu, in this case the "Shortcuts" menu.

The first step is to define the Shortcuts menu in a layer.xml file:

<folder name="Menu">
    <folder name="Shortcuts"/>
</folder>

Next, we want to populate that folder dynamically, whenever the user clicks the button above. To do that, we need to get hold of the Shortcuts folder within the Menu folder. Then we add in there a new file with ".instance" as the extension, assign our own Action to it, and (as described here, thanks Ernie and the vi/vim project), use the "instanceCreate" and "instanceClass" attributes.

public class SomeTopComponent extends TopComponent {
    private DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    public SomeTopComponent() {
        setDisplayName("Some");
        setLayout(new BorderLayout());
        add(new JButton(new AbstractAction("Add new menu item to shortcuts") {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final String formatted = formatter.format(System.currentTimeMillis());
                        FileObject menuFolder = FileUtil.getConfigFile("Menu/Shortcuts");
                        try {
                            FileObject newMenu = menuFolder.createData(formatted, "instance");
                            AbstractAction action = new AbstractAction(
                                    "Added at: " + formatted) {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    JOptionPane.showMessageDialog(null, formatted);
                                }
                            };
                            newMenu.setAttribute("instanceCreate", action);
                            newMenu.setAttribute("instanceClass", action.getClass().getName());
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                });
            }
        }), BorderLayout.NORTH);
    }
}

OK. We now know how to dynamically add a new menu item within a top level menu. But can a top level menu be itself created dynamically too?

That's even simpler:

public class SomeTopComponent extends TopComponent {
    private DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    public SomeTopComponent() {
        setDisplayName("Some");
        setLayout(new BorderLayout());
        add(new JButton(new AbstractAction("Add new menu to main menubar") {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final String formatted = formatter.format(System.currentTimeMillis());
                        FileObject menuFolder = FileUtil.getConfigFile("Menu");
                        try {
                            menuFolder.createFolder("Added at: " + formatted);
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }

                    }
                });
            }
        }), BorderLayout.NORTH);
    }
}

The result:


Monday Mar 31, 2014

Dynamically Creating Menu Items (Part 1)

Let's set up an infrastructure for dynamically creating menu items in a NetBeans Platform application. We start with this, i.e., a simple skeleton. We have an Action presented as a JMenu over which we have control via Presenter.Menu, together with a LookupListener that we're going to use for listening to the Lookup for objects of interest:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.actions.Presenter;
@ActionID(category = "Shortcuts", id = "org.bla.core.DynamicShortcutMenu")
@ActionReference(path = "Menu/Shortcuts")
public class DynamicShortcutMenu 
    implements ActionListener, Presenter.Menu, LookupListener {
    JMenu menu = new JMenu();
    @Override
    public JMenuItem getMenuPresenter() {
        return menu;
    }
    @Override
    public void resultChanged(LookupEvent le) {
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // not used
    }
}

Next, let's develop our LookupListener further so that we can listen for new objects of interest. What the "object of interest" is, is up to you. Let's create an interface named "Clickable" as the currency, i.e., the communication mechanism that will be used to communicate with the Action that we have created above, i.e., to tell it that new menu items are needed.

import javax.swing.AbstractAction;
public interface Clickable {
    AbstractAction getAbstractAction();
}

OK. We have an interface that is a wrapper around an AbstractAction. Later on, we'll publish implementations of this interface.

For the moment, let's focus on changing the earlier code so that we can consume the implementations, once those implementations are published.

@ActionID(category = "Shortcuts", id = "org.bla.core.DynamicShortcutMenu")
@ActionRegistration(displayName = "not-used", lazy = false)
@ActionReference(path = "Menu/Shortcuts")
public class DynamicShortcutMenu extends AbstractAction
        implements ContextAwareAction, Presenter.Menu, LookupListener {
    private final Lookup.Result<Clickable> clickables;
    private JMenu menu = new JMenu("Dynamic");
    public DynamicShortcutMenu() {
        this(Utilities.actionsGlobalContext());
    }
    public DynamicShortcutMenu(Lookup lkp) {
        clickables = lkp.lookupResult(Clickable.class);
        clickables.addLookupListener(
                WeakListeners.create(LookupListener.class, this, clickables));
    }
    @Override
    public JMenuItem getMenuPresenter() {
        return menu;
    }
    @Override
    public void resultChanged(LookupEvent le) {
        for (Clickable c : clickables.allInstances()){
            menu.add(c.getAbstractAction());
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // not used
    }
    @Override
    public Action createContextAwareInstance(Lookup lkp) {
        return new DynamicShortcutMenu(lkp);
    }
}

Great. We're now listening to the global lookup for Clickables and then adding their AbstractActions to the menu we created above.

Now that we know how to consume Clickables, let's learn how to publish a Clickable. Below you see a TopComponent that contains a JButton. When clicked, the JButton publishes a Clickable into the Lookup of the TopComponent. At that stage, the Action code above causes a new JMenuItem to be added. Note that at no point is a JMenuItem removed, i.e., when selection changes to a different TopComponent, the JMenuItem added via the code below will still be in the dynamic menu, which is probably how you want things to be anyway.

@TopComponent.Description(
        preferredID = "SomeTopComponent",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
        mode = "explorer",
        openAtStartup = true)
public class SomeTopComponent extends TopComponent {
    private DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    private InstanceContent ic = new InstanceContent();
    public SomeTopComponent() {
        setDisplayName("Some");
        setLayout(new BorderLayout());
        add(new JButton(new AbstractAction("Add new menu item to shortcuts") {
            @Override
            public void actionPerformed(ActionEvent e) {
                ic.set(Collections.singletonList(new SomeClickable()), null);
            }
        }), BorderLayout.NORTH);
        associateLookup(new AbstractLookup(ic));
    }
    private class SomeClickable implements Clickable {
        @Override
        public AbstractAction getAbstractAction() {
            final String formatted = formatter.format(System.currentTimeMillis());
            return new AbstractAction("Added at: " + formatted) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null, "hello from " + formatted);
                }
            };
        }
    }
}

Here's the result.

Of course, this throws up some new questions. Especially, how to achieve this result for a menu within the menubar, rather than a submenu within a menu within the menubar. I.e., as you can see above, this only solves the situation where a third-level menu needs to be dynamic. But what about if the menu "Dynamic" above needs to itself be dynamic? And, even more complexly, what if the "Shortcuts" menu should, itself, be dynamic? See part 2 for the solutions to these questions.

Sunday Mar 30, 2014

"Cannot load even default layout, using internally predefined configuration"

When I created the FeedReader application in NetBeans IDE 8 and then ran it, this is what I saw:

The above tells you something is messed up in the System FileSystem.

The log shows among other things:

Caused: java.io.FileNotFoundException: [WinSys] Missing Window Manager configuration file
    at org.netbeans.core.windows.persistence.WindowManagerParser$PropertyHandler.readData(WindowManagerParser.java:911)
    at org.netbeans.core.windows.persistence.WindowManagerParser.readProperties(WindowManagerParser.java:365)
    at org.netbeans.core.windows.persistence.WindowManagerParser.load(WindowManagerParser.java:110)
    at org.netbeans.core.windows.persistence.PersistenceManager.loadWindowSystem(PersistenceManager.java:1156)
[catch] at org.netbeans.core.windows.PersistenceHandler.load(PersistenceHandler.java:130)
    at org.netbeans.core.windows.WindowSystemImpl.load(WindowSystemImpl.java:81)
    at org.netbeans.core.GuiRunLevel$InitWinSys.run(GuiRunLevel.java:229)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)

After quite a bit of searching, I discovered this file in the "branding" folder of the application. The "branding" folder can only be seen when you're in the Files window.

I deleted the "resources" folder above, together with the "layer.xml" file that you see there. It contained only "_hidden" elements, i.e., this is an older way of hiding menus and toolbars, that is now obsolete; now you do so within a module instead of in a file within the "branding" folder like the above. (Even better than deleting it is to move its content into one of the layer.xml files of your own modules, e.g., the Feed Reader module.)

Then I cleaned the application. And then I ran the application and everything was OK. Seems like an old file format of the layer.xml file, or maybe something changed in that module, I don't know what the reason is.

Saturday Mar 29, 2014

Cause a Wizard to Appear Automatically

Sometimes you may want a wizard to automatically appear, as a result of logic, rather than a user action. Normally, the user goes to the New File dialog or the New Project dialog or clicks an Action, such as provided by a menu item or toolbar button, and then a wizard starts up.

However, here's something slightly different. The module depends on the Window System API and hence the @OnShowing annotation is available.

import java.io.File;
import org.openide.awt.Actions;
import org.openide.windows.OnShowing;
@OnShowing
public class Startable implements Runnable {
    @Override
    public void run() {
        if (!new File("/path/to/some/folder").exists()) {
            Actions.forID("File", "org.something.core.CreateFolderWizardAction").actionPerformed(null);
        }
    }   
}

In the "run" method, use "Actions.forID" and pass in the category and the ID of the Action that starts up the wizard. Since when you use the Wizard wizard to create a wizard skeleton, you also get an Action, you should have an Action somewhere in your module structure. Instead of registering the wizard in the Action such that it appears as a toolbar button or menu item, just remove those annotations. The only annotations your Action needs are @ActionID and @ActionRegistration, not @ActionReference.

And with that, the wizard starts up after the application is initialized, automatically.

Friday Mar 28, 2014

Nashorn and NetBeans: Not Your Average Joe's Rhino

What can be done with JavaScript and Java together in NetBeans IDE via Nashorn is kind of mind blowing. Watch Jim Laskey explain Nashorn within 10 minutes, including mixing JavaScript and Java in NetBeans 8.

Based on JSR 292 and available in JDK 8, Nashorn is a JavaScript engine implemented fully in Java on the JVM. In the screencast above, from the Java 8 launch, the Nashorn JavaScript Engine is described and a top-level view of how it all works is provided, with demos of JavaScript & Java working together.

And, over on DZone, Constantin Drabo today published another great article with code from NetBeans 8 on this topic: Nashorn Application with NetBeans 8.

Thursday Mar 27, 2014

Absolutely Awesome NetBeans Plugin: JPA Modeler

Possibly the most exciting new NetBeans plugin that's under development is the JPA Modeler, led by Gaurav Gupta, who also works on the Business Process Modeling plugin for NetBeans:

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

Watch this short movie to see it in action. In its latest incarnation, available from the link above, you can reverse engineer a diagram from existing JPA sources, which is also amazing, and let's you use the JPA modeler on old sources, i.e., no need to create a new project from scratch to use this plugin. And, whenever the diagram becomes out of date, you can simply regenerate it, from the current state of your sources. I've tried it and it delivers exactly what I had expected. Plus, it looks seriously professional and very polished, as this annotated YouTube clip shows:

If you watch the above, you'll see right near the end that you can change the diagram, then regenerate the tables in your database, and recreate the JPA classes. I.e., this lets you visually model your data and then generate all the database content and Java classes from the diagram. Really powerful.

Also, follow the JPA Modeler YouTube Channel, there's lots of content there, constantly being updated with new movies.

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
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today