torsdag 14 november 2013

GAE - Could not determine the dependencies of task ':backend-gae:appengineExplodeApp'.

Last night I was porting a old project from Maven to Gradle. The project runnings on Google App Engine, and I was looking for a good plugin to use. Luckily there is a nice plugin, https://github.com/GoogleCloudPlatform/gradle-appengine-plugin. Which from the beginning was created by Benjamin Muschko, but now days maintain by Google.

So far so good. It was super easy to apply the plugin to your project, however when I tried to run the appengineRun task it failed with the message (on version 1.8.6 of the plugin):

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':backend-gae:appengineExplodeApp'.

So the best thing with open source is that it is open. Digging into the code one will find that the appendingExplodeApp task have a dependency to either the ear or the war plugins (you will find the hint for it at row 193-210, in this file: AppEnginePlugin.groovy).

With that in mind and until it has been fixed (I do believe that the plugin should do this for us) you just can add either the ear or the war plugin to your projects.

Bellow is also an example of a full build script:

/** 
 * Info about the plugin: https://github.com/GoogleCloudPlatform/gradle-appengine-plugin 
 */
buildscript {
  repositories {
      mavenCentral()
  }

  dependencies {
      classpath 'com.google.appengine:gradle-appengine-plugin:1.8.6'
  }
}

apply plugin: 'war'
apply plugin: 'appengine'

appengine {
  downloadSdk = true      
  httpPort = 9085 
}

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.8.6'
  
  compile      'com.google.appengine:appengine-api-1.0-sdk:1.8.6'
  compile      'com.google.appengine:appengine-api-labs:1.8.6'
}

måndag 20 maj 2013

Android - Site Tracker

I am pleased to announce that the first public version of my latest Android app, Site tracker, is available in the Google Play store.

Site tracker is a tool with the goal to reduce the time one spend browsing favorite web-sites looking for any updates. Instead of browsing around you config your sites in Site tracker, which upon your request will check the sites and notify you if there where any updates.


Example of the app with an update check ongoing.

The motivation behind the app is quite simple. Each day I have a bunch of sites, which I use to visit and check for any updates. Some of the sites offered RSS feeds, but not all of them.

In the future I plan to add more functionality to the app. Among others: background check of the sites, notifications, and import / export of the sites.

Download the app and try it out your self, and do not hesitate if there are something not working or something you think could be made better, let me know. You will find the app by clicking the icon below or using the given link.

lördag 27 april 2013

JavaFX - Creating a Windows 7 screen saver using JavaFX

Is it possible to use JavaFX to create a screen saver which shows a specific web page in Windows 7? Yes it actually is, but there are some bumps on the road. In this post we will look at the various steps we need to perform to actually create a full functional Windows screen saver.

Before we dig into the code we first we need to understand what a screen saver is in Microsofts world. According to this support page from Microsoft a screen saver is a Windows 32bit application with the file-ending .scr, which is started using different command line arguments. The screen saver should be able to show a configuration dialog when given a empty argument, or the '/c' argument. Likewise should it be possible to get a preview using the '/p' argument, and the screen saver should be shown using the '/s' command. Here will we have some problem if we like to solve the preview function since it is supposed to be shown in a given window using a window handler, which we can not use from JavaFX. However the screen saver can be made without the support for the preview.

So we need to create a application which by command line supports the '/c' (configuration), and the '/s' (screen saver) commands, the application needs to store the user settings, when the application runs in screen saver mode it should be terminated upon input and be in full screen, create a executable jar, and finally we need to package the executable jar as a windows 32 application. Some things to do so let us get going.

We start by focusing on the application, later on we package the application, and last we create a Windows batch script which we convert to a executable Windows 32bit application.

A screen saver implemented using JavaFX
For the screen saver I would like to show a web page, so using the WebView in full screen will suit us well. The configuration dialog will only have a simple URL field and a save button. The settings will be saved in a property file in the users home folder.

I have chosen to implement the application using FXML. One could argue if FXML is needed for the actual screen saver, since it will only be one WebView. Let us start by looking into the code which will convert the command line arguments into a understandable "mode" for the application.
@Override
public void init() throws Exception {
 List<string> rawParameters = getParameters().getRaw();
 if (rawParameters == null || rawParameters.isEmpty()) {  
  mode = Mode.SETTINGS;
 } else if(!rawParameters.isEmpty()) { 
  switch (rawParameters.get(0).trim().substring(0, 2)) { 
   case "/c":
    mode = Mode.SETTINGS;
    break;
   case "/s":
    mode = Mode.SCREEN_SAVER;       
    break;
   default:
    mode = Mode.NA;
    break;
  }
 }
}
Line 1-2: By overriding the init()-method you can perform tasks which will be executed before the start()-method in a JavaFX application.
Line 3: By calling getParamters() we can get the parameters submitted to the application.
Line 4: If we call the application without any parameters we should start the configuration dialog.
Line 7: We only use the first characters of the parameter since Windows will give us a string like '/c:12345' when we call configuration from the screen saver dialog.
Line 8: '/c' for settings so lets get into the settings mode.
Line 11: '/s' for the screen saver mode.

The code for the parameter parsing and start up of the application is quite straight forward and the mode is later used in the start()-method for a more readable way of starting the different parts of the application.
@Override
public void start(Stage stage) throws Exception {
 ResourceBundle resourceBundle = ResourceBundle.getBundle(RESOURCE_TEXTS);
 switch (mode) {
  case SCREEN_SAVER:
   stage.initStyle(StageStyle.UNDECORATED);
   stage.setResizable(false);
   stage.setIconified(false);
   stage.setFullScreen(true);
   stage.setScene(new Scene(FXMLLoader.<Parent>load(
     getClass().getResource("/fxml/screensaver.fxml"), resourceBundle)));
   
   // Close the screen saver when any key is being pressed.
   stage.getScene().setOnKeyTyped(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
     event.consume();
     Platform.exit();
    }
   });
   
   // Close the screen saver when the mouse is moved.
   stage.getScene().setOnMouseMoved(new EventHandler<MouseEvent>() {
    private long firstMouseMove = -1;
    
    @Override
    public void handle(MouseEvent event) {
     if (firstMouseMove != -1 
                                && firstMouseMove + 1000 < System.currentTimeMillis()) {
      event.consume();
      Platform.exit();
     } else {
      firstMouseMove = System.currentTimeMillis();
     }
    }
   });
   stage.show();
   break;
  case SETTINGS:
   stage.setTitle(resourceBundle.getString("title"));
   stage.initStyle(StageStyle.UTILITY);
   stage.setResizable(false);
   stage.setIconified(false);
   stage.setScene(new Scene(FXMLLoader.<Parent>load(
     getClass().getResource("/fxml/configuration.fxml"), resourceBundle)));
   stage.show();
   break;
  default:
   System.err.println("Unkown command.");
   Platform.exit();
   break;
 }
}
Line 3: Here we load the internationalized strings used in the application.
Line 5: Time to show the screen saver.
Line 6-9: Define the stage to be a un-resizable full screen window without a icon.
Line 10-11: Load the FXML for the scene.
Line 14-20: When the screen saver is active we like to be able to hide it by typing a key like a standard screen saver. On a KeyEvent we colse the screen saver sicne it has full fitted its purpose.
Line 23-36: Likewise with the MouseEvents we like to terminate the screen saver when we move the mouse. However we need to do a lite trick since when the screen saver is started some "old" mouse events are propagated into the program. Instead of terminate the screen saver on the first mouse event we wait a second before we start to listen for events. This will not be a problem when the screen saver is activated due to inactivity, however when you "test" the screen saver it would be nice to actually see it.

The controllers are simply FXML controllers, but the screen saver controller has a little method for hiding the scroll-bar in the WebView.
webView.getChildrenUnmodifiable().addListener(new ListChangeListener<Node>() {
 @Override
 public void onChanged(javafx.collections.ListChangeListener.Change<? extends Node> change) {
  for (Node scrollBar : webView.lookupAll(".scroll-bar")) {
   scrollBar.setVisible(false);
  }
 }
});
Line 1: When the content is change in the WebView we add a listener to keep track of the changes.
Line 4-6: Simply find all scroll-bars and hide them.

That is the application. The saving of the user settings is done by the standard Java Properties which are serialized to a XML-file. If you are interested in that part you find the source code in the end of this post. Look in the class Configuration.

Packaging the application and create a Windows 32bit application
Next step in the processes will be to create a executable jar-file. I will be using the javafx-maven-plugin to create a executable jar. All you need to do is to configure you main class and the run mvn jfx:jar. This will create a jar which will be executed when you run it. See the pom.xml in the submitted source code.

So how can we make a Windows 32bit application out of our Java application? There are actually some solutions. We could build a executable binary using the build tools in the JDK, but I think for this task a simple batch-script which we compile into a executable exe-file suits us better. For this we will use a little tool called "Bat To Exe Converter" which you find here: http://www.softpedia.com/get/System/File-Management/Batch-To-Exe-Converter.shtml. The following batch-script will be used to create a exe-file.
@echo off
IF NOT "%1" == "/p" IF NOT "%1" == "/a" (
  %JAVA_HOME%\bin\java -jar fxwss-0.0.1-SNAPSHOT-jfx.jar %1
)
Line 2: Since we can not support the preview we can skip those commands. We could have let the application handle this for us, but starting the application takes some time and the user experience will be much better if we handle it smooth and nice instead.
Line 3: Here we start the application and passes the arguments. Note: you have to use the whole path to "java", for some reason java is not found otherwise and you will not get any errors. Just a not working screen saver.

Next open the "Bat To Exe Converter" and select you bat-file as input. What this program will do is to create a exe-file for you which we later on just change the name to  a .scr-file. In the "Batch-To-Exe-Converter" I selected to create a "Invisible application" since I do not like to see the command-window when starting the screen saver or the configuration window.

"Bat To Exe Converter" in action.
Take the created exe-file and change the name of it to .scr. Place this file together with the jar in the windows/system32 folder. When you now open the screen saver settings you will see the "fx-web-screen-saver" in the drop down. That is all, now enjoy your JavaFX screen saver.

In this post we have seen how we can create our own screen saver which actually execute a JavaFX application. There are some steps involved, but when one understand the concept of the screen savers in Windows it is quite straight forward. One things which is a bit frustrated is that you can not disable the text which is shown when you show a stage in full-screen, at least it would have been nice if one could style the message. Also some error messages when running a faulty screen saver in Windows would have been nice.

You can find the source code and binaries here: http://files.loop81.com/rest/download/e972a38a-7954-4d43-8dc7-29bad09cb7ba.

söndag 14 april 2013

Project "FXComparer" part 4 - Packaging the application

In this last part of the "FXComparer" series we will have a look at a Maven plugin called javafx-maven-plugin which we will use to package our application.

The javafx-maven-plugin is really easy to use and can be used to create among others executable JARs, native installers, and Windows BAT-files. In this post we will focus on the executable JAR.
<plugin>
  <groupId>com.zenjava</groupId>
  <artifactId>javafx-maven-plugin</artifactId>
  <version>1.5</version>
  <configuration>
    <mainClass>com.loop81.fxcomparer.FXComparer</mainClass>
  </configuration>
</plugin>
That is all we need to configure in our pom.xml to enable the plugin. However before we can create a binary we need to do some configuration to our environment.

  1. You need to use a JDK which is greater or equal to update 9.
  2. JAVA_HOME need to be specified to point to your JDK.
  3. Run mvn jfx:fix-classpath. You can read more about this here: https://github.com/zonski/javafx-maven-plugin/wiki. In short this is needed because the fxrt.jar is not included in the classpath by default.
When the environment is configured all we have to do is to run mvn jfx:build-jar and we will get a nice runnable JAR for our application. 

FXComparer version 1.0.2
This last part conclude the "FXCompararer" series. We have seen how we can use JavaFX to create a modern application. There is still some parts in the JavaFX API that needs some improvements. Mostly these are small things. As some example you can not change the text of a TableView when it is empty or you can not disable the scroll bars in the TableView. However all in all JavaFX is so much better then Swing and it will interesting to see where JavaFX ends up in the future. 

You find the "FXComparer" and all source code at https://code.google.com/p/fx-comparer/.

The articles in this series are the following:

Project "FXComparer" part 3 - Handling input and showing results using a TableView

In this third part of the "FXComparer" series we will focus on how to connect the FXML with a controller, and how to show results in a TableView.

Connecting a controller to the FXML
When creating a UI using FXML interactions from the users are performed either by having inline scripts  in the FXML (like to old JavaFX) or using a controller. We will focus on the controller alternative.

A controller is a simple Java class. Before we needed to implement Initializable if we liked to do anything when the controller was created, but today this can be omitted and instead just use a no-arg initialize() method.

Nodes from the scene are "injected" to the controller using the @FXML annotation. The nodes are looked up using there id. We can also manually lookup nodes in a scene using the lookup(css selector) method.

Binding actions to nodes is also done in the FXML. Here we specify action by using the method name for the action to perform. The method needs to be defined in the controller with one argument of the type ActionEvent and annotated with the FXML-annotation.

Let us see a example of some FXML and a controller.
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" 
    minHeight="-Infinity" minWidth="-Infinity" prefHeight="90.0" 
    prefWidth="200.00009999999747" xmlns:fx="http://javafx.com/fxml" 
    fx:controller="com.loop81.blog.fxml.FXMLDemoController">
  <children>
    <Label fx:id="labelHello" alignment="CENTER" contentDisplay="CENTER" 
      layoutX="16.0" layoutY="11.0" prefWidth="170.0" />
    <Label layoutX="14.0" layoutY="30.0" text="Times pressed:" />
    <Label fx:id="labelCounter" alignment="CENTER_RIGHT" 
      contentDisplay="RIGHT" layoutX="100.0" layoutY="30.0" prefWidth="84.0" />
    <Button layoutX="27.0" layoutY="54.0" mnemonicParsing="false" 
      onAction="#onButtonClick" text="Increase counter by one" />
  </children>
</AnchorPane>
public class FXMLDemoController {

 @FXML
 private Label labelHello;
 
 @FXML
 private Label labelCounter;
 
 private IntegerProperty counter = new SimpleIntegerProperty(0);
 
 public void initialize() {
  labelHello.setText("Hello!");
  labelCounter.textProperty().bind(counter.asString());
 }
 
 @FXML
 public void onButtonClick(ActionEvent event) {
  event.consume();
  counter.set(counter.get() + 1);
 }
}
Line 4 (FXML): Defines that FXMLDemoController should be the controller for this FXML.
Line 6 (FXML): Notice that we have given the label a unique id which is later matched against the Label variable name in the controller.
Line 12 (FXML): Here we define which method in the controller that should be called when a user presses the button. The method name needs to start with a '#'. This is easy forgotten and when actions is not working this is probably one of the reasons.
Line 3-7 (controller): Here we define that we like to have a reference to the two labels injected for us. Notice that we need to annotate the label with the @FXML annotation.
Line 9 (controller): Defines a integer property. Which we will use to show a counter for the clicking. If you are unsure about properties and bindings in JavaFX I recommend you to have a look at http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm.
Line 11-14 (controller): This method will automatically be called when the controller is instantiated. All injections of @FXML annotated nodes will be loaded before this method is called.
Line 12 (controller): Here we simply update the text of the "hello label".
Line 13 (controller): Each Label has a StringProperty and what we do here is that we assign the string value of our counter property to the labels property. Each time we update our counter with a new value the label also will be updated.
Line 16-20 (controller): Last we increase the counter when the button is clicked. It is always a good practice to consume the event if you do not like it to be propagated any further.

You can download the source of the demo here: http://files.loop81.com/rest/download/64925d28-4626-4662-bacd-7f07da55b31f

In the FXComparer application the controller is defined in com.loop81.fxcomparer.FXComparerController and the FXML in fxml/layout.fxml.

Showing results in a TableView
The result from a compare in FXComparer is presented using a TableView. In the FXComparer we have 3 columns which widths is 50%, 25%, 25%. Today there is no way where you can specify the width of the columns in the Scene Builder and needs to done pragmatically. The whole TableView is highly configurable and quite nice to work with. Bellow is a demo showing the most common use cases for the TableView, size of the columns, handle of a row click, and sorting.
private static final List<TableData> DATA = new ArrayList<>(Arrays.asList(
  new TableData("The first text", 99),
  new TableData("The second text", 0),
  new TableData("The third text", -99)));

@FXML
private Label labelSelectedRow;

@FXML
private TableView<TableData> tableView;

@FXML
private TableColumn<TableData, String> column1;

@FXML
private TableColumn<TableData, String> column2;

@FXML
private TableColumn<TableData, TableData> column3;

public void initialize() {
 // Column 1 should be 50% wide and show the text in the TableData.
 column1.prefWidthProperty().bind(tableView.widthProperty().divide(2));
 column1.setCellValueFactory(new PropertyValueFactory<TableData, String>("text"));
 
 // Column 2 should be 25% wide and show the number.
 column2.prefWidthProperty().bind(tableView.widthProperty().divide(4));
 column2.setCellValueFactory(new PropertyValueFactory<TableData, String>("number"));
 
 // Column 3 should be 25% wide and show the text + number, but the sorting should be on 
    // the number.
 column3.prefWidthProperty().bind(tableView.widthProperty().divide(4));
 column3.setCellValueFactory(
   new Callback<TableColumn.CellDataFeatures<TableData,TableData>, 
                            ObservableValue<TableData>>() {
  @Override
  public ObservableValue<TableData> call(CellDataFeatures<TableData, TableData> cell) {
   return new SimpleObjectProperty<>(cell.getValue());
  }
 });
 
 // Last we add the data to the table.
 tableView.setItems(FXCollections.observableList(DATA));
 
 // Add a listener to the selected item property so we can detect a selection change 
    // in the table.
 tableView.getSelectionModel().selectedItemProperty().addListener(
          new ChangeListener<TableData>() {
  @Override
  public void changed(ObservableValue<? extends TableData> value, TableData oldValue, 
                  TableData newValue) {
   labelSelectedRow.setText(tableView.getSelectionModel().getSelectedIndex() + " " 
                     + newValue.toString());
  }
 });
}
Line 1-4: The TableData is a simple object which has two properties, one for a text, and one for a number. The TableData also implement Comparable<TableData> which handles the sorting of the third column.
Line 12-19: We inject the TableColumns so we later on can modify the width of them.
Line 23: To specify the width of a column use the prefWidthProperty(). To this property we bind half the size of the TableView. If the TableView would change its size the column will change as well.
Line 24: The value of a cell is rendered using a CellFactory and a CellValueFactory. For the first two columns it is enough to use the PropertyValueFactory which simply fetch the value from the object in the data model for the table using the property.
Line 27: Column 2 and Column 3 will only have a size of 1/4 of the TableView.
Line 33-40: Since the last columns value is a concatenation of the string and the number we have to use a custom CellValueFactory which returns a new SimpleObjectProperty.
Line 43: Here we assign the items to the table. The TableView requires that we use a observable list since if the data is changed this also should be reflected in the table.
Line 47-55: When a user selects a item in the table the SelectionModel is updated. What we like to know is simply when that property is updated and when it is updated we show the new item together with the row id in the label.

Understanding the properties and bindings in JavaFX is important. I have seen a lot of different solution to the problem of getting the row a user click on. Some solutions added a custom ClickListener using a CellFactory when all you need is to listen for changes in the selection model.

You can download the source of the demo here: http://files.loop81.com/rest/download/6b6bcf5c-c8ed-47a2-9373-b12e0a7f66f2

In the FXComparer application the TableView code is defined in com.loop81.fxcomparer.FXComparerController.

Wrapping up
Using FXML really makes us write less Java-code. In some cases however I guess writing Java code would make sense, but for common parts of the application I do not see any reason for not using FXML. The TableView is a highly customization component and I suggest you to have a look in the official TableView tutorial http://docs.oracle.com/javafx/2/ui_controls/table-view.htm.

In the next post in the series about "FXComparer" we will see how we can use a nice Maven plugin for deployment of the application.

All source code for "FXCompare" is found here: https://code.google.com/p/fx-comparer/.

The articles in this series are the following:


Project "FXComparer" part 2 - Building the UI using FXML and JavaFX Sceen Builder

This is the second part in the "FXComparer" series where we will see how we can design a fluid application using the FXML layout files. We will be using JavaFX Sceen Builder which is free to download at http://www.oracle.com/technetwork/java/javafx/tools/index.html.

Instead of trying to write down how to create the UI I have recorded a video describing all the steps to turn the sketch into a real layout, enjoy.


The video was created using CamStudio and Windows Movie Maker. I am not sure that those are the best tools for the job. It took quite a while to edit the movie and add the description text. Also the text effects in Movie Maker are a bit limited and I would like to have a tool where you could highlight areas and at least add a background color to the texts to make them more readable. If you know any better way to create a screen cast please post a comment.

Some helpful tips regarding the Scene Builder
  • Remember: Ctrl + P for a quick preview of you UI.
  • Wrapping nodes instead of moving around. If you right-click on a node in the hierarchy pane you will see a entry in the menu for "Wrap in". Selecting this will give you a menu with the different layout which you can wrap the node in. Super nice! Likewise you can unwrap a layout-node by selecting unwrap and the node will be removed.
  • Keep an eye on the "Layout" section for the different nodes. Here you will find component specific layout options which will help you to create a better UI. Example like the AnchorPane constraints or the VGrow constraints for the VBox layout.

Using the FXML in the application
The FXML is easy loaded into the application using the FXMLLoader. Below is a little stub for loading a FXML-file located in /src/main/fxml/ into a stage and showing it.

public class FXCompare extends Application {
   
 @Override
 public void start(Stage stage) throws Exception {  
  stage.setScene(new Scene(FXMLLoader.load(
                    getClass().getResource("/fxml/layout.fxml")));
  stage.show();
 }
 
 public static void main(String[] args) {
  launch(args);
 }
}

That is all for today. In the next post we will "hook" up the FXML with a controller so we can interact with the users and see how we can present data in a TableView.

For the the full source of the FXComparer see: https://code.google.com/p/fx-comparer/.

The articles in this series are the following:

Project "FXComparer" part 1 - Defining the project, setup using Eclipse and Maven

From time to time I have the needs for comparing two jar-archives with each other to verify that tings are as expected. For this I have been using a old Swing application called JarComparer. The application is super simple and did not have the best usability. So I decided to create a new tool for comparing my archives, the "FXComparer" using JavaFX.

In this post we will lay down the requirements of the application and setup the basic Maven project.

Requirements on the application
Comparing two archives is not the hardest task, but some basic requirements are needed.
  • It should be possible to compare *.WAR, *.JAR, and *.ZIP archives.
  • The user should either select the file from a file-dialog or drop them into the application using drag and drop.
  • The difference of the archives should be presented with size and entry differences (new, removed, and deleted).
  • It should be possible to see the difference for each of the files in the archive.

A first sketch of the UI
Bellow is a first sketch of how the UI should look. When I'm about to create a new application or web-page for that part, I usually start by drawing some mocks using Pencil project, which is a nice free tool.

A first sketch of the UI. The areas for the archives should support that files be dragged to them.

Setting up the project using Eclipse and Maven
A while ago I wrote a post "Get started with Maven, Eclipse and Java FX" which will describe all the steps we need to perform to get a first Java FX application up and running. However I would like to point out a slight improvement to that post. Instead of hard-code the path to the javafx-runtime decency we can use the environment.

Start by pointing JAVA_HOME to you JDKs home path. If you do not know how to set a environmental a quick Google will help you. Define a property in the pom.xml which points out the jfxrt.jar and use the property in the system path of the dependency.
  ...
  <groupId>com.loop81</groupId>
  <artifactId>fxcompare</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <properties>
    <dependecy.javafx.rj.path>${env.JAVA_HOME}\jre\lib\jfxrt.jar</dependecy.javafx.rj.path>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>javafx-runtime</artifactId>
      <version>1.7.u7</version>
      <scope>system</scope>
      <systemPath>${dependecy.javafx.rj.path}</systemPath>
    </dependency>
  </dependencies>
  ...
If you followed the "Get started with Maven, Eclipse and Java FX" post you should have a project up and running. If you get stuck have a look at the source code to FXComparer, https://code.google.com/p/fx-comparer/.

That is all for this first part. I the next part we will take a look at how to transfer the sketch to a real UI using JavaFX Scene Builder to create our layout (FXML).

The articles in this series are the following: