Chapter 2. Developing First Applications with JBoss Developer Studio Tools

2.1. Configuring JBoss Developer Studio for use with JBoss EAP and JBoss Web Framework Kit

This article provides details for new and existing users who need to configure a fresh install of the IDE or upgrade the versions of Red Hat JBoss Enterprise Application Platform or JBoss Web Framework Kit in use.

The IDE supports application development and deployment with JBoss EAP and JBoss Web Framework Kit only after you configure the IDE for use with JBoss EAP and JBoss Web Framework Kit. This configuration is essential for using the enterprise versions of the example Maven projects provided in Red Hat Central. These projects are intended for deployment to JBoss EAP and necessitate IDE access to the JBoss EAP and JBoss Web Framework Kit Maven repositories.

Instructions are provided for the following tasks:

2.1.1. Setting Up JBoss EAP

To set up JBoss EAP for use in the IDE, you must direct the IDE to the local or remote runtime servers. This establishes a communication channel between the IDE and the JBoss EAP server for efficient deployment and server management workflows. Depending on your circumstance, you can set up the JBoss EAP server in one of three ways:

  1. If you are installing a new instance of the IDE, you can use Red Hat Development Suite to download, install, and set up the IDE and JBoss EAP.
  2. If you already have the IDE installed but not JBoss EAP, you can download, install, and set up JBoss EAP from within the IDE.
  3. If the IDE and JBoss EAP are already installed, you can use runtime detection to set up JBoss EAP from within the IDE.

2.1.2. Downloading, Installing, and Setting Up the IDE and JBoss EAP using the DevSuite Installer

If you are installing a new instance of the IDE, you can use the Red Hat Development Suite Installer to download, install, and set up the IDE and JBoss EAP. A specific JBoss EAP version is packaged in the installer. For details of the components installed through Red Hat Development Suite, see Component Details in the Red Hat Development Suite Installation Guide.

Note: If you want to install a different version of JBoss EAP, you can either download it from within the IDE (see download, install, and set up JBoss EAP from within the IDE) or install it separately and then follow the instructions in C,use runtime detection to set up JBoss EAP from within the IDE.

For detailed instructions on installing Red Hat Development Suite, see the Red Hat Development Suite Installation Guide.

To download, install and set up the IDE and JBoss EAP using the DevSuite Installer:

  1. Log in and download Red Hat Development Suite from the Red Hat Developers Portal product download page at Red Hat Developers Download. Note that you must unzip macOS installers before the next step. If using the Safari browser to download, the macOS installer is automatically unzipped.
  2. Run the downloaded installation file (Online or Bundled).
  3. In the Red Hat Development Suite window, click Next to continue.
  4. In the Target Folder window, in the Select the installation folder field, type the location where you wish to install Red Hat Development Suite and then click Next to continue. The Confirmation window lists the components that are available for download and installation through Red Hat Development Suite.

    Note

    This use case requires you to only download JBoss Developer Studio and Red Hat JBoss Enterprise Application Platform. However, you may choose to download any additional or all the components available through Red Hat Development Suite.

  5. Click the Red Hat JBoss Developer Studio and Red Hat JBoss Enterprise Application Platform checkboxes and click Next.
  6. In the Account window, enter your existing Red Hat Developer login credentials.
  7. Click Download & Install to continue. The Download & Install window shows the progress of the installation.
  8. In the Get Started window, click Open Red Hat JBoss Developer Studio.
  9. In the Eclipse Launcher window, select the workspace location where you want to store the project data and click Launch.
  10. The Searching for runtimes window, automatically searches and detects the available runtimes.
  11. From the table, click Red Hat JBoss EAP 7.0 and click OK.

    Figure 2.1. Searching for runtimes Window Listing Red Hat JBoss EAP 7.0

    Searching for runtimes Window Listing Red Hat JBoss EAP 7.0

    Result: Open the Servers view, to see the Red Hat JBoss EAP 7.0 server listed in the Stopped mode.

2.1.3. Downloading, Installing, and Setting Up JBoss EAP from within the IDE

If the IDE is already installed, you can download, install, and set up JBoss EAP from within the IDE. With this option, you can choose from a range of supported JBoss EAP versions; for details of supported JBoss EAP versions see https://access.redhat.com/site/articles/427493.

To download, install, and set up JBoss EAP from within the IDE:

  1. Start the IDE.
  2. Click WindowPreferences, expand JBoss Tools, and then click JBoss Runtime Detection.
  3. In the Paths pane, click Download.
  4. In the Download Runtimes window, from the Download Runtimes table select the JBoss EAP version that you want to download and click Next.

    Note: For JBoss EAP 6.1.x and later, continue to follow the steps given here. For JBoss EAP 6.0.x and earlier, follow the on-screen instructions for downloading JBoss EAP from the Red Hat Customer Portal and after JBoss EAP is installed continue to use runtime detection to set up JBoss EAP from within the IDE.

    Figure 2.2. Download Runtimes Window Listing Available JBoss EAP Versions

    Download Runtimes Window Listing Available JBoss EAP Versions
  5. In the JBoss.org Credentials window, enter your credentials and click Next.
  6. In the Runtime JBoss EAP_version window, read the terms and conditions, and then click I accept the terms of the license agreement and then click Next. Note that if you have previously accepted the terms and conditions in the IDE or through the jboss.org website, this window is skipped.
  7. In the Download Runtime window, in the Install Folder field, click Browse and choose a location in which to install JBoss EAP and click Finish. The Download 'JBoss EAP 1 window shows the progress of the downlaod.
  8. Click Apply and Close to close the Preferences window.

Result: The server is listed in the Servers view in stopped mode.

2.1.4. Using Runtime Detection to Set Up JBoss EAP from within the IDE

If the IDE and JBoss EAP are already installed, you can use runtime detection to set up JBoss EAP from within the IDE. The runtime detection feature automatically identifies the JBoss EAP instance installed on your local system and generates a corresponding default server setup for use in the IDE. This feature makes getting started with a default JBoss EAP server very quick.

Note: Specific JBoss EAP versions are supported by each IDE release; for details of supported JBoss EAP versions see https://access.redhat.com/site/articles/427493.

To use runtime detection to set up JBoss EAP for use in the IDE:

  1. Start the IDE.
  2. Click WindowPreferences, expand JBoss Tools, and then select JBoss Runtime Detection.
  3. Click Add.
  4. Navigate to path/to/jboss-eap and click OK. JBoss Server Tools recursively scans the path searching for installed servers and displays a list of those it finds.
  5. Ensure the jboss-eap-version check box is selected, where version denotes the JBoss EAP version, and click OK.

    Figure 2.3. Selecting a Runtime

    Selecting a Runtime
  6. Click Apply and Close to close the Preferences window.

Result: The server is listed in the Servers view in stopped mode.

2.1.5. Configuring Maven for JBoss EAP and JBoss Web Framework Kit Maven Repositories

To configure Maven to use the JBoss EAP and JBoss Web Framework Kit Maven repositories when working inside the IDE, you must ensure that the IDE knows the location of your Maven configuration settings.xml file and that the necessary profiles for the JBoss EAP and JBoss Web Framework Kit Maven repositories are contained in that file. This ensures that Maven knows where to search for project dependencies when it is called to build Maven projects from within the IDE.

2.1.6. Specifying Maven settings.xml File Location

If you have multiple Maven settings.xml files or you are using a shared settings.xml file, then this file may not be in the default location expected by the IDE. In this case, you must inform the IDE of the file location.

To specify the Maven settings.xml file location:

  1. Start the IDE.
  2. Click WindowPreferences, expand Maven, and then click User Settings.
  3. For the User Settings field, click Browse and locate the settings.xml file.
  4. Click Update Settings.
  5. Click Apply and then click OK.

2.1.7. Using JBoss EAP and JBoss Web Framework Kit Maven Repositories

You can either download the JBoss EAP and JBoss Web Framework Kit Maven repositories from the Red Hat Customer Portal or use the online Maven repository located at https://maven.repository.redhat.com/ga.

2.1.8. Using the Offline Maven Repositories

If you have not previously used these versions of JBoss EAP and JBoss Web Framework Kit, you must configure your Maven settings.xml file to use the associated product Maven repositories. You can manually edit your settings.xml file in a text editor or use the JBoss Developer Studio Maven integration feature to automatically detect the JBoss repositories and appropriately edit your settings.xml file.

Note: The JBoss EAP and JBoss Web Framework Kit Maven repositories must be already obtained from the Red Hat Customer Portal and located on a system that you can access.

To specify the JBoss EAP and JBoss Web Framework Kit Maven repositories locations using the IDE:

  1. Start the IDE.
  2. Click WindowPreferences, expand JBoss Tools, and then click JBoss Maven Integration.
  3. Click Configure Maven Repositories.
  4. Click Add Repository.
  5. Click Recognize JBoss Maven Enterprise Repositories.
  6. Navigate to path/to/jboss-eap-maven-repository and click OK. JBoss Maven Tools recursively scans the path searching for a Maven repository.
  7. Modify the information in the ID and Name fields as desired, ensure the Active by default check box is selected, and then click OK.

    Figure 2.4. Details of the Selected Maven Repository

    Details of the Selected Maven Repository
  8. Click Add Repository.
  9. Click Recognize JBoss Maven Enterprise Repositories.
  10. Navigate to path/to/jboss-wfk-maven-repository and click OK. JBoss Maven Tools recursively scans the path searching for a Maven repository.
  11. Modify the information in the ID and Name fields as desired, ensure the Active by default check box is selected, and then click OK.
  12. Click Finish and at the prompt asking if you are sure you want to update the Maven configuration file click Yes. If the specified configuration file does not exist, JBoss Maven Tools creates it.
  13. Click Apply and click OK to close the Preferences window.

2.1.9. Using the Online Maven Repositories

Adding the online repository to the IDE, adds https://maven.repository.redhat.com/ga to your settings.xml , which takes care of all the dependencies.

To use the online Maven repositories:

  1. Start the IDE.
  2. Click WindowPreferences, expand JBoss Tools, and then click JBoss Maven Integration.
  3. Click Configure Maven Repositories.
  4. Click Add Repository.
  5. In the Profile ID drop-down list, select redhat-ga-repository.

    Figure 2.5. Add a Maven Repository

    Add a Maven Repository
  6. Click OK.
  7. In the Configure Maven Repositories window, click Finish.
  8. Click Apply and then click OK to close the Preferences window.

2.2. Creating and Importing Node.js Applications

Node.js is an event-based, asynchronous I/O framework and is used to develop applications that run JavaScript on the client and server side. This allows the application to re-use parts of the code and to avoid switching contexts. Node.js is commonly used to create applications such as static file servers, messaging middleware, HTML5 game servers, web application framework, and others.

JBoss Developer Studio supports node.js application development using the npm package installer and offers a built-in debugging tool to identify and fix issues with applications. In the subsequent sections, instructions are available for the following tasks:

2.2.1. Setting Up Prerequisites for Node.js Development

Ensure that the following prerequisites are met to start developing node.js applications in JBoss Developer Studio:

  1. Install npm. On Red Hat Enterprise Linux and Fedora, use the sudo dnf install npm command. See the npm documentation (https://docs.npmjs.com/getting-started/installing-node) for installation information about other operating systems.
  2. Install JBoss Developer Studio.

Result: You are now ready to start developing Node.js applications with JBoss Developer Studio.

2.2.2. Creating a new JavaScript Application

To create a new JavaScript project and application in JBoss Developer Studio:

  1. To create a new JavaScript project:

    1. Click FileNewOther and type JavaScript in the search text box.
    2. Select JavaScript Project and click Next.
    3. In the Project Name field, add a name for your new project.
    4. Ensure that the rest of the fields, which are set to the default settings, are as required, and then click Finish to create the new project.
    5. If asked to view the JavaScript perspective, click Yes. Your new project is listed in the Project Explorer view.
  2. To interactively create a package.json file:

    1. Click FileNewOther and then type npm in the search box.
    2. From the search results, click npm Init.
    3. Set the Base directory to your JavaScript project folder in your JBoss Developer Studio workspace.
    4. Optionally, clear the Use default configuration check box to supply non-default values for these fields.
    5. Click Finish to continue with the default values for the package.json file or to continue after changing the default values.

      Figure 2.6. Generate a New package.json File

      Generate a New package.json File
    6. The new package.json file is generated and displayed for editing. If required, manually edit the file in the displayed pane and save the changes.

      Figure 2.7. Manually Edit the Generated package.json File

      Manually Edit the Generated package.json File
  3. Manually edit the package.json file to add dependencies. Dependencies are modules which provide extended functionality, such as libraries and frameworks. See the following screen capture for an example of the required format for dependencies and developer dependencies.

    Figure 2.8. Adding Dependencies to the package.json File

    Adding Dependencies to the package.json File

    For further details about dependencies, see the NPM documentation: https://docs.npmjs.com/files/package.json#dependencies

  4. Create a new JavaScript file with the required business logic:

    1. In the Project Explorer view, right-click the name of your project, and select NewFile.
    2. In the dialog box, add a name for the new file, for example index.js, and click Finish to create the new file.
    3. The new file displays for editing in a new tab. Add the required business logic to the your JavaScript files and save the changes.
  5. Run the project files by right-clicking the index.js file in your project and select Run AsNode.js Application. The Console view appears and displays details about the application as it runs, or errors if it is unable to run the application.

Result: You have created a new JavaScript project and application.

2.2.3. Importing an Existing JavaScript Project

You can import an existing JavaScript project directly into JBoss Developer Studio and then make changes and run the project as follows:

  1. Import an existing project into JBoss Developer Studio:

    1. Click FileImport.
    2. In the Import dialog box, expand the General option.
    3. Click Existing Projects into Workspace and then click Next.
    4. In the Import Projects dialog box:

      1. Click either the Select root directory or Select archive file options based on your project format.
      2. Click Browse to add the path to the project root directory or archive file.
      3. In the Projects box, select one or more projects to import into the workspace.
      4. If required, click the Search for nested projects option to locate nested projects in the root directory or archive file.
      5. Click the Copy projects into workspace option to save a copy of the imported project in the workspace directory specified for JBoss Developer Studio.
      6. If required, select the Add project to working sets checkbox and add the details for a new or existing working set.
      7. Click Finish to add the project to the workspace. The Project Explorer view now contains your imported project.
  2. If required, expand the project in the Project Explorer view and either double-click the project files to edit them, or right-click and select NewFile to add a new JavaScript file for your project.
  3. Run the project files by right-clicking the index.js file in your project and click Run AsNode.js Application. The Console view appears and displays details about the application as it runs, or errors if it is unable to run the application.

Result: You have imported an existing JavaScript project into JBoss Developer Studio.

2.2.4. Debugging Node.js Applications

After either creating a new Node.js project or importing an existing one and then running the project, some errors may appear. JBoss Developer Studio includes a debugger to help identify and resolve these issues. To use the debugging feature:

  1. Start the debugger for your project:

    1. In the Project Explorer view, expand your project.
    2. Right-click the index.js file for your project and click Debug AsNode.js Project.
    3. Select the Remember my decision check box in the dialog box to apply your selection to subsequent perspective shifts and then click Yes or No to continue.
  2. Review the elements of your project’s JavaScript files to locate errors in one of two ways:

    1. Expand any variable listed in the Variables tab to view additional objects and edit the details for each item.
    2. Hover the mouse cursor over any variables in the index.js tab to view and edit its property details.
  3. Make changes to the files to address the errors:

    1. Edit the index.js file in the appropriate view.
    2. Save the changes. The Console view runs the updated file and displays changes.
  4. After debugging the errors, use the Resume, Suspend, and Terminate buttons ( nodejs resume pause ) as follows to test your changes:

    1. The Resume button (green triangle) continues running the project files.
    2. The Suspend button (two yellow rectangles) temporarily stops running the project files to allow users to make changes.
    3. The Terminate button (red square) ends the running of the project files.
  5. Repeat steps 4 through 6 as necessary to locate and fix errors found by the debugger.
  6. When debugging is concluded, click WindowShow ViewOther and select Project Explorer from the options. This displays the list of projects again.

Result: You have debugged your application and returned to the Project Explorer view.

2.3. Developing Applications Using the Forge Tool

Red Hat JBoss Developer Studio offers Forge Tools for developing Java EE applications and to extend the IDE functionality in Eclipse. Start developing Java EE applications using either the Forge context menu or the command line from the IDE.

2.3.1. Creating a New Project

After you have created a Forge project you can set up persistence, add entities and fields, and create scaffold for the project.

To create a new project:

  1. Press Ctrl+4 to start Forge and open the JBoss Forge context menu.
  2. Click Project:New to open the Create a new project window.
  3. In the Create a new project window:

    1. In the Project name field, type a project name.
    2. In the Top level package field, type {com.example} as the top package.
    3. In the Project location field, enter a target location for the Forge project.
    4. In the Stack list, click Java EE 7.
  4. Click Finish.

Figure 2.9. Create a New Forge Project

Create a New Forge Project

Result: The project is listed in the Project Explorer view.

2.3.2. Setting Up Persistence

Setting up the JPA prerequisites, creates the persistence.xml file in the project and adds the required dependencies to the pom.xml file.

Note

While creating the JPA entity, the Forge console automatically detects any prerequisites that must be set up and prompts you to create those at runtime.

To set up persistence:

  1. Press Ctrl+4 to open the JBoss Forge context menu.
  2. Click JPA: New Entity. The window is populated with default values.
  3. Click Next to continue using the default values or edit the fields to change the values.
  4. In the Configure your connection settings window, ensure that the fields display the appropriate values and then click Next.
  5. In the Create a new JPA entity window:

    1. The Package Name field shows the system defined name of the package, example: {your_Forge_project_name}.model. Edit the package name if desired.
    2. In the Type Name field, type a name for the new entity. Example: Customer.
  6. Click Finish.

Result: The new entity appears in the JBoss editor and is also listed in the Project Explorer view with the name: .java.

Figure 2.10. .java Displayed in the JBoss Editor

.java Displayed in the JBoss Editor

2.3.3. Adding Fields to the Entity

To add fields to the entity:

  1. Press Ctrl+4 to open the JBoss Forge context menu.
  2. Click JPA: New Field.
  3. In the Create a new field window:

    1. In the Target Entity field, select {package_name.model.entity}.
    2. In the Field Name field, type FirstName.
  4. Click Finish.

    Figure 2.11. Add Field to the Entity

    Add Field to the Entity
  5. Repeat steps 1 through 4 to add more fields to the entity.

Result: The fields are added to the Customer.java file.

2.3.4. Creating a Scaffold

Scaffolding is automatic code generation by a program, using available information, usually a database to generate a basic CRUD (create, read, update, delete) admin interface. The Scaffold Generate command is used to create the scaffold.

To create the scaffold:

  1. Press Ctrl+4 to open the JBoss Forge context menu.
  2. Click Scaffold Generate.
  3. In the Scaffold Type list, click Angular JS and then click Next.
  4. If your project is not configured to use all the technologies that you want to use, Forge prompts you to set up the dependencies. Click Next.
  5. In the Select JPA entities window:

    1. Click the check box in the Targets field.
    2. Click the Generate REST resources check box.
  6. Click Finish.

Figure 2.12. Select JPA Entities to Create the Scaffold

Select JPA Entities to Create the Scaffold

Result: The entities are created and listed in the Project Explorer view.

2.3.5. Running and Testing the Application

In this example we use the JBoss EAP server to run the application.

To run the application:

  1. In the Project Explorer view, right-click the application and click Run As > Run on Server. Alternatively, drag and drop the application from the Project Explorer view to the JBoss EAP 1 server in the Servers view. The application opens in the default browser.
  2. Click Customers and then click Create to create a new customer.
  3. In the FirstName and the LastName fields, enter the first and last names and click Save. The customer is added to the application.

Use the Search for Customers section to search for customers by their first and/or last names.

2.3.6. Creating Extensions or Add-ons

The add-ons/extensions run inside the IDE. After adding commands and features to the add-on, no further changes are required for the extensions or add-ons to run in another IDE.

To create an add-on:

  1. Press Ctrl+4 to open the JBoss Forge context menu.
  2. Click Project:New.
  3. In the Create a new project window:

    1. In the Project name field, type a name for the add-on (example_addon, in this case).
    2. In the Project type list, click Forge Addon (JAR).
  4. Click Next.
  5. In the Furnace Addon Setup window, Depend on these addons section, Forge automatically selects the prerequisites. Review the dependencies and click Finish. The setting up of these dependencies may take some time to complete. The add-on is listed in the Project Explorer view.
  6. Press Ctrl+4 to open the Forge context menu.
  7. Select Java: New Class to open the Java: New Class window.
  8. In the Type Name field, type CustomCommand and click Finish. The CustomCommand.java file opens in the JBoss editor.
  9. To change this Java class into a Forge command:

    1. Press Ctrl+4 to open the Forge context menu.
    2. Select Addon: New UI Command to open the Generates a UICommand implementation window.
    3. In the Generates a UICommand implementation window:

      1. In the Type Name field, type CustomCommand.
      2. In the Command name field, type custom.
    4. Click Finish.

      Figure 2.13. Add a Command

      Add a Command

      The command is listed in the CustomerCommand.java file.

  10. In the Project Explorer view, click the CustomerCommand.java file to select the file.
  11. Press Ctrl+4 to open the Forge context menu.
  12. Select Build and Install an Addon to open the Build and install a Forge addon window. The Project directory field, by deafult, shows the path to the addon.
  13. Click Finish to install the add-on into the IDE.
  14. To execute the installed command:

    1. Press Ctrl+4 to open the Forge context menu.
    2. Select custom.
    3. Add parameters to the method in order to add user input to the command. Copy and paste the following command in the CustomCommand.java file and save the file.

              package org.example_addon.commands;
      
              import org.jboss.forge.addon.configuration.Configuration;
              import org.jboss.forge.addon.resource.URLResource;
              import org.jboss.forge.addon.ui.command.AbstractUICommand;
              import org.jboss.forge.addon.ui.context.UIBuilder;
              import org.jboss.forge.addon.ui.context.UIContext;
              import org.jboss.forge.addon.ui.context.UIExecutionContext;
              import org.jboss.forge.addon.ui.input.UIInput;
              import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
              import org.jboss.forge.addon.ui.metadata.WithAttributes;
              import org.jboss.forge.addon.ui.util.Metadata;
              import org.jboss.forge.addon.ui.util.Categories;
              import org.jboss.forge.addon.ui.result.Result;
              import org.jboss.forge.addon.ui.result.Results;
      
              import java.lang.Override;
              import java.lang.Exception;
      
              import javax.inject.Inject;
      
              public class CustomCommand extends AbstractUICommand
              {
                     @Inject
                     @WithAttributes(label = "JIRA URL", required = true)
                      private UIInput<URLResource> url;
      
              @Inject
              private Configuration config;
      
              @Override
              public UICommandMetadata getMetadata(UIContext context)
              {
      
                   return Metadata.forCommand(getClass())
                          .name("JIRA: Setup")
                          .description("Setup the JIRA Addon")
                          .category(Categories.create("JIRA", "Setup"));
              }
      
              @Override
              public void initializeUI(UIBuilder builder) throws Exception
      
              {
                    builder.add(url);
              }
      
               @Override
               public Result execute(UIExecutionContext context)
               {
                     String targetUrl = url.getValue().getFullyQualifiedName();
                     Configuration subset = config.subset("jira");
                     subset.setProperty("url", targetUrl);
                     return Results.success("JIRA URL set to: "+targetUrl);
                }
               }
  15. To rebuild and install:

    1. In the Project Explorer view, click the created add-on (example_addon, in this case).
    2. Press Ctrl+4 to open the Forge context menu.
    3. Select Build and Install an Addon. The Project directory field, by deafult, shows the path to the addon.
    4. Click Finish to install the add-on into the IDE.
    5. Press Ctrl+4 to open the Forge context menu.
    6. Click JIRA: Setup.

Figure 2.14. Add-on Listed in the Forge Context Menu

Add-on Listed in the Forge Context Menu

Result: The add-on is created and listed in the Forge context menu.

2.3.7. Did You Know?

  • You can launch the Forge Console by clicking Window > Show view > Forge Console. The Forge Console view opens in an inactive state.
  • You can start JBoss Forge by clicking the Start {JBoss Forge_version} button Start Button ).
  • To link the Forge Console output with the open editor, click the Link with Editor button ( Link with Editor Button ).

2.4. Developing Applications Using the Hibernate Tools

Hibernate Tools is a collection of tools for projects related to Hibernate version 5 and earlier. The tools provide Eclipse plugins for reverse engineering, code generation, visualization and interaction with Hibernate.

Use the Hibernate Tools to easily generate, test and prototype your Hibernate or JPA mapped projects. You can also use Hibernate to Run queries, browse mappings and generate code for your data projects.

2.4.1. Creating a JPA Project and Connecting to the Sakila-h2 Database

2.4.1.1. Prerequisites

To connect to the sakila-h2 database:

  1. Download the sakila-h2 database from the h2 version of the Sakila database.
  2. On the terminal, navigate to the directory where you have saved the sakila-h2.jar file and run the following command to start the database: $ ./runh2.sh.

To create a JPA project and connect to the database:

  1. In the workspace, click File > New > Other and then search for JPA Project and double-click it to open the New JPA Project wizard.
  2. In the New JPA Project wizard:

    1. In the Project name field, type a name for the project.
    2. In the Target runtime field, click a runtime server that you wish to use.
    3. In the JPA version list, click 2.1.
  3. Click Next.

    Figure 2.15. Create a New JPA Project

    Create a New JPA Project
  4. In the New JPA Project - Java window, select the source folder on the build path and click Next.
  5. In the JPA Facet window, click Add connection.
  6. In the New Connection Profile window:

    1. Click Generic JDBC.
    2. In the Name field, type sakila.
  7. Click Next.
  8. In the New Connection Profile window:

    1. Click the New Driver Definition icon ( New Driver Definition Icon ) located next to the Drivers field to open the New Driver Definition window.
  9. In the Name/Type tab, click Generic JBDC Driver and then click the JAR list tab.
  10. Click Add JAR/Zip and then select the previously downloaded .jar file in the sakila-h2-master folder.

    Figure 2.16. Select the JAR File

    Select the JAR File
  11. Click the Properties tab and enter the following details in the Properties table:

    1. Click Connection URL and type jdbc:h2:tcp://localhost/sakila.
    2. Click Driver Class, and then click the ellipsis icon ellipses icon .
    3. In the Available Classes from Jar List window, click Browse for class. Click OK when the required driver is found (org.h2.Driver, in this case).
    4. Click User ID, type sa.
  12. In the New Driver Definition window, click OK.
  13. In the New Connection Profile window, click Finish to return to the JPA Facet window.
  14. In the Platform list, click Hibernate (JPA 2.1).
  15. In the JPA implementation pane, Type list, either click User Library and to add the libraries in the Preferences (Filtered) window see, Did You Know, Add Libraries section for detailed steps, OR click Disable Library Configuration.
  16. Click Finish.
  17. If you see the Open Associated Perspective window asking if you want to open the JPA perspective, click Open Perspective.

Result: The project is created and is listed in the Project Explorer view.

2.4.1.2. Generating DDL and Entities

DDL, Data Definition Language, is a syntax to define data structures. Generate DDL and entities to enable Hibernate runtime support in an Eclipse JPA project.

To generate DDL and Entities:

  1. In the Project Explorer view, right-click the .
  2. Click JPA Tools > Generate Tables from Entities or Generate Entities from Tables. The Generate Entities window (or the Generate Tables from Entities window) appears.
  3. In the Generate Entities window:

    1. In the Output directory field, change the default directory, if required.
    2. Ensure that the Use Console Configuration check box is clicked.
    3. In the Console Configuration list, ensure that the relevant configuration is shown.
  4. Click Finish.

    Figure 2.17. Generate Entities

    Generate Entities

2.4.1.3. Creating a Hibernate Mapping File

Hibernate mapping files specify how your objects relate to the database tables. To create basic mappings for properties and associations, meaning, to generate the`.hbm.xml` files:

  1. Create a new Hibernate Mapping file:

    1. Click File > New > Other.
    2. In the New wizard, locate Hibernate and expand it. Click Hibernate XML Mapping file (hbm.xml).
  2. Click Next.
  3. In the New Hibernate XML Mapping files (hbm.xml) window:

    1. Click Add Class to add classes or click Add Packages to add packages. You can create an empty .hbm file by not selecting any packages or classes. An empty .hbm file is created in the specified location.
    2. Click the depth control check box to define the dependency depth used when choosing classes.
    3. Click Next.
    4. Select the parent folder location.
    5. In the File name field, type a name for the file (example: hibernate.hbm.xml) and click Finish.

Result: The hibernate.hbm.xml file opens in the default editor.

2.4.1.4. Creating a Hibernate Configuration File

For reverse engineering, prototype queries, or to simply use Hibernate Core, a hibernate.properties or a hibernate.cfg.xml file is needed. Hibernate Tools provides a wizard to generate the hibernate.cfg.xml file if required.

To create a Hibernate Configuration file:

  1. Create a new cfg.xml file:

    1. Click File > New > Other.
    2. In the New wizard, locate Hibernate and then click Hibernate Configuration File (cfg.xml).
  2. Click Next.
  3. In the Create Hibernate Configuration File (cfg.xml) window, select the target folder for the file and then click Next.
  4. In the Hibernate Configuration File (cfg.xml) window:

    1. The Container field, by default, shows the container folder.
    2. The File name field, by default, shows the configuration file name (hibernate.cfg.xml, in this case).
    3. In the Database dialect list, click the relevant database (H2, in this case).
    4. In the Driver class list, click the driver class depending on the database dialect that you just selected (org.h2.Driver, in this case).
    5. In the Connection URL list, click the relevant URL (jdbc:h2:tcp://<server>[:<port>]/<databaseName>, in this case).
    6. Click the Create a console configuration check box to use the hibernate.cfg.xml file as the basis of the console configuration.
  5. Click Finish.

    Figure 2.18. Create a New cfg.xml File

    Create a New cfg.xml File

Result: The new hibernate.cfg.xml file opens in the default editor.

2.4.1.5. Creating a Hibernate Console Configuration

A Console configuration describes how the Hibernate plugin configures Hibernate. It also describes the configuration files and classpaths needed to load the POJOs, JDBC drivers, etc. It is required to make use of query prototyping, reverse engineering and code generation. You can have multiple console configurations per project, but for most requirements, one configuration is sufficient.

To create a Hibernate console configuration:

  1. Create a cfg.xml file:

    1. Click File > New > Other.
    2. In the New wizard, locate Hibernate and then click Hibernate Console Configuration.
  2. Click Next.
  3. In the Main tab:

    1. In the Name field, if required, edit the generated name provided by default.
    2. In the Type pane, click Core.
    3. In the Hibernate Version list, select the relevant version.
    4. In the Project field, type a project name or click Browse to locate an existing project (my_JPA_project, in this case).
    5. In the Database connection list, click New to configure a new database connection or leave as is to use the default connection.
    6. In the Property file field, click Setup to set the path to the first hibernate.properties file found in the selected project (see, Did You Know, Setup Property File section for detailed steps). Once created the path of the .properties file displays in the Property file field.
    7. In the Configuration file field, click Setup to set the path to the first hibernate.cfg.xml file found in the selected project (refer to the Did you know, Setup Configuration File section for detailed steps). Once created, the path of the hibernate.cfg.xml file displays in the Configuration file field.
  4. Click Finish.

Figure 2.19. Create Hibernate Console

Create Hibernate Console

2.4.1.6. Modifying the Hibernate Configurations

You can edit the Hibernate Configurations from the Hibernate Configurations view.

To modify the Hibernate Configurations:

  1. Click Window > Show View > Other. Click Hibernate Configurations and then click Open.
  2. In the Hibernate Configurations view, right-click the and click Edit Configuration.
  3. The Edit Configuration window displays. Edit the fields. Click Apply and then click OK.

2.4.1.7. Generating Code and Reverse Engineering

Hibernate tools’ reverse engineering and code generation features allow you to generate a range of artifacts based on a database or an existing Hibernate configuration, like mapping files or annotated classes. Among others, these generated artifacts can be POJO Java source files, hibernate.hbm.xml files, hibernate.cfg.xml generation and schema documentation.

To generate code:

  1. Configure Hibernate:

    1. Click Window > Perspective > Open Perspective > Other.
    2. Search for Hibernate and double-click it. The Hibernate Configurations view appears.
  2. View the Hibernate Code Generation Configurations:

    1. In the toolbar, next to the Run icon, click the down arrow.
    2. Click Hibernate Code Generation Configurations.
  3. Expand Hibernate Code Generation and then click New_configuration.
  4. In the Create, manage, and run configurations window, in the Name field, type a logical name for the code generation launcher. If you do not specify a name, the default name, New_Generation, is used.
  5. In the Main tab, enter the following details:

    Note

    The At least one exporter option must be selected warning indicates that for the launcher to work you must select an exporter on the Exporter tab. The warning disappears after you select an exporter.

    +

    1. In the Console Configuration list, click the name of the console configuration to be used when generating code.
    2. In the Output directory field, click Browse and select an output directory. This is the default location where all output will be written. You can enter absolute directory paths, for example: d:/temp. Note that existing files will be overwritten/ if the correct directory is not specified.
    3. To reverse engineer the database defined in the connection information, click the Reverse engineering from JDBC connection check box. JBoss Developer Studio generates code based on the database schema when this option is used.If this option is not enabled, the code generation is based on the existing mappings specified in the Hibernate Console configuration.
    4. In the Package field, add a default package name for any entities found when reverse engineering.
    5. In the reveng.xml field, click Setup to select an existing reveng.xml file, or create a new one. This file controls certain aspects of the reverse engineering process, such as:

      • how JDBC types are mapped to Hibernate types
      • which tables are included or excluded from the process
    6. In the reveng. strategy field, click Browse and provide an implementation of a ReverseEngineeringStrategy. this must be done if the reveng.xml file does not provide enough customization; the class must be in the classpath of the Console Configuration because if not, you will get a class not found exception.

      Note

      Refer to the Did You Know, Create, manage, and run configurations window, Main tab, Check Boxes section for details of the selected check boxes.

    7. The Exporter tab specifies the type of code that is generated. Each selection represents an Exporter that generates the code. In the Exporter tab:
    8. Click the Use Java 5 syntax check box to use a Java 5 syntax for the Exporter

      1. Click the Generate EJB3 annotations check box to generate EJB 3 annotations
      2. Select the Exporters from the Exporters table. Refer to the Did You Know, Exporter section for details about the exporters.

        Each Exporter selected in the preceding step uses certain properties that can be set up in the Properties section. In the Properties section, you can add and remove predefined or custom properties for each of the exporters.

  6. Click Add next to the Properties table to add a property to the chosen Exporter. In the resulting dialog box, select the property from the proposed list and the appropriate value for it. For an explanation of the property and its value, refer to the Did You Know, Exporter Property and its Values section.
  7. Click the Refresh tab and enter the following:

    1. Click the Refresh resources upon completion check box to refresh the resources and click one of the following:

      • The entire workspace: To refresh the entire workspace.
      • The selected resource: To only refresh the selected resource
      • The project containing the selected resource: To refresh the project containing the selected resource
      • The folder containing the selected resource: To refresh the folder containing the selected resource
      • Specific resources: To refresh specific resources; then click Specify Resources to open the Edit Working Set window and select the working set.
    2. Click the Recursively include sub-folders check box to refresh the sub-folders.
  8. Click the Common tab and enter the following:

    1. In the Save as pane, click Local file to save the configuration as a local file, OR click Shared file and then select a shared file location.
    2. In the Display in favourites menu pane, click the menu to display the configuration.
    3. In the Encoding pane, click the format that you want the configuration to be encoded to.
    4. In the Standard Input and Output pane, click the Allocate console check box and optionally click the Input File and Output File check boxes and select the relevant options.
    5. Click the Launch in background check box to show the configuration launch progress in the background.
  9. Click Apply and then click Run.

2.4.2. Did You Know?

2.4.2.1. Add Libraries

To add libraries:

  1. Download Hibernate ORM from http://hibernate.org/orm/.
  2. Extract the file to locate the libraries in the lib/required folder.
  3. In the JPA Facet window, Platform list, click * User Library*.
  4. Click the Manage libraries icon ( manage libraries icon ).
  5. In the Preferences (Filtered) window, click New.
  6. In the New User Library window, User library name field, type a name for the user library and click OK (user_library, in this case).
  7. Click the System library (added to the boot class path) check box and click OK.
  8. In the Preferences (Filtered), click Add External JARs and locate the extracted hibernate-release-1/lib/required folder.
  9. Click the first library and click OK. Repeat the above step to add all the libraries from the hibernate-release-1/lib/required` folder.
  10. In the Preferences (Filtered), click Apply and Close.

2.4.2.2. Setting Up the Property File

To set up the property file:

  1. In the Create Hibernate Configuration window, Main tab, click Setup.
  2. In the Setup property file window, click Create new to create a new property file (or click Use existing to choose an existing file as a property file).
  3. In the Create Hibernate Properties file (.properties) window, click the parent folder name and then click Finish.
Set up Property File

2.4.2.3. Setting Up the Configuration File

To set up the configuration file:

  1. In the Create Hibernate Configuration window, Main tab, click Setup.
  2. In the Setup configuration file window, click Use existing to choose an existing file as a property file (or click Create new to create a new property file).
  3. In the Select hibernate.cfg.xml file window, expand the parent folder, choose the file to use as the hibernate.cfg.xml file, and then click OK.
Set up hibernate.cfg.xml File

2.4.2.4. Creating, Managing, and Running the Configurations Window, Main tab, Check Boxes

The following check boxes are selected by default in the Create, manage, and run configurations window, Main tab:

  • Generate basic typed composite ids: When a table has a multi-column primary key, a <composite-id> mapping will always be created. If this option is enabled and there are matching foreign-keys, each key column is still considered a 'basic' scalar (string, long, etc.) instead of a reference to an entity. If you disable this option a <key-many-to-one> property is created instead. Note that a <many-to-one> property is still created, but is simply marked as non-updatable and non-insertable.
  • Detect optimistic lock columns: Automatically detects optimistic lock columns. Controllable via reveng. strategy; the current default is to use columns named VERSION or TIMESTAMP.
  • Detect many-to-many tables: Automatically detects many-to-many tables. Controllable via reveng. Strategy.
  • Detect one-to-one associations: Reverse engineering detects one-to-one associations via primary key and both the hbm.xml file and annotation generation generates the proper code for it. The detection is enabled by default (except for Seam 1.2 and Seam 2.0) reverse engineering. For Hibernate Tools generation there is a check box to disable this feature if it is not required.

2.4.2.5. Exporter Property and Values

  • jdj5: Generates Java 5 syntax
  • ejb3: Generates EJB 3 annotations
  • for_each: Specifies for which type of model elements the exporter should create a file and run through the templates. Possible values are: entity, component, configuration.
  • template_path: Creates a custom template directory for this specific exporter. You can use Eclipse variables.
  • template_name: Name for template relative to the template path.
  • outputdir: Custom output directory for the specific exporter. You can use Eclipse variables.
  • file_pattern: Pattern to use for the generated files, with a path relative to the output dir. Example: /.java.
  • Dot.executable: Executable to run GraphViz (only relevant, but optional for Schema documentation).
  • Drop: Output will contain drop statements for the tables, indices, and constraints.
  • delimiter: Is used in the output file.
  • create: Output will contain create statements for the tables, indices, and constraints.
  • scriptToConsole: The script will be output to Console.
  • exportToDatabase: Executes the generated statements against the database.
  • outputFileName: If specified the statements will be dumped to this file.
  • haltOnError: Halts the build process if an error occurs.
  • Format: Applies basic formatting to the statements.
  • schemaUpdate: Updates a schema.
  • query: HQL Query template

2.4.2.6. Exporter

  • Domain code (.java): Generates POJOs for all the persistent classes and components found in the given Hibernate configuration.
  • Hibernate XML Mappings (.hbm.xml): Generate mapping (hbm.xml) files for each entity.
  • DAO code (.java): Generates a set of DAOs for each entity found.
  • Generic Exporter (<hbmtemplate>): Generates a fully customizable exporter that can be used to perform custom generation.
  • Hibernate XML Configuration (.cfg.xml): Generates a hibernate.cfg.xml file; used to keep the hibernate.cfg.xml file updated with any newly discovered mapping files.
  • Schema Documentation (.html): Generates a set of HTML pages that document the database schema and some of the mappings.
  • Schema Export (.ddl): Generates the appropriate SQL DDL and allows you to store the result in a file or export it directly to the database.
  • HQL Query Execution Exporter: Generates HQL Query according to given properties.

2.4.3. Troubleshooting

2.4.3.1. Problems While Loading Database Driverclass

Problems while loading database driverclass Warning

Error message: Problems while loading database driverclass (org.h2.Driver)

Resolution: To avoid this error, you must select a predefined DTP connection profile in the Database Connection dropdown. Also, the jar can be added on the Classpath page of the Console Configuration wizard if you don’t want to have it on the project classpath.

  1. Right-click {project_name}PropertiesJava Build Path.
  2. Click the Libraries tab and then click Add External JARs.
  3. Navigate to the downloaded database JAR file and click OK.
  4. In the Properties for {project_name} window, click Apply and then click OK.

2.5. Creating Your First Mobile Web Application

Mobile Web Tools provides an HTML5 Project wizard that enables you to create web applications optimized for mobile devices. The HTML5 Project wizard is a useful starting point for creating all new HTML5 web applications in the IDE. The wizard generates a sample ready-to-deploy HTML5 mobile application with REST resources from a Maven archetype.

As demonstrated in this article, you can customize the application using the JBoss Tools HTML Editor, deploy and view the application with the mobile browser simulator BrowserSim, and use LiveReload to refresh BrowserSim as the application source code is modified and saved in the IDE.

The instructions here demonstrate how to complete the following tasks:

This article guides you through each of these configuration requirements and must be completed in the order given.

2.5.1. Prerequisite: Configuring the IDE for an Available Server

The instructions in this article show you how to deploy your HTML5 web application to a server. The IDE must be configured for any servers to which you want to deploy applications, including the location and type of application server and any custom configuration or management settings. You can complete this configuration at the time of deploying the application but in this article it is assumed that you have completed the configuration beforehand.

For information on configuring a local runtime server and deploying applications to it, see Deploying Applications to a Local Server.

2.5.2. Creating an HTML5 Project

The HTML5 Project wizard generates a sample project based on a Maven archetype and the project and application identifiers provided by you. The Maven archetype version is indicated in the Description field in the first page of the wizard and you can change the version, and therefore the project look and dependencies, by selecting either an enterprise or non-enterprise target runtime within the wizard.

To create a HTML5 project:

  1. In Red Hat Central, in the Getting Started tab, click HTML5 Project.
  2. In the Target Runtime list, click an IDE-ready server and click Next.
  3. In the New Project Example window, complete the fields about the HTML5 project as follows:

    1. In the Project name field, type a name for the project.
    2. In the Package field, type an alpha-numeric package for the project.
  4. Click Finish.
  5. When prompted with 'HTML5 Project' Project is now ready, click Finish.

Result: The project is generated and listed in the Project Explorer view.

2.5.3. Building and Deploying the Application

After the HTML5 project is generated, it can immediately be built and deployed to an application server.

To build and deploy the application:

  1. In the Project Explorer view, right-click {project name} and click Run As > Run on Server.
  2. In the Run On Server window, ensure that Choose an existing server is selected.
  3. From the table of servers, expand localhost, select the server on which to deploy the application and click Finish.

    Figure 2.20. Selecting the Server to Run the Application

    electing the Server to Run the Application

The Console view shows output from the server starting and deploying the application. When deployment is complete, an IDE default web browser opens and shows the deployed web application.

Figure 2.21. Enterprise HTML5 web application Viewed in Browser

Select the runtime server to run the application.

2.5.4. Viewing the Application with BrowserSim

The HTML5 web application has an interface optimized for mobile devices. You can view and test such web pages as they would be on mobile devices using BrowserSim. This mobile device web browser simulator provides skins for different mobile devices, making it easy to test and debug web applications for mobile devices.

To view the application with BrowserSim:

  1. Ensure JBoss is the perspective in use. To open the JBoss perspective, click Window > Perspective > Open Perspective > Other and double-click JBoss (default).
  2. In the Servers view, expand the server adapter to list the application.
  3. Right-click {application name} and click Show In > BrowserSim.

Figure 2.22. HTML5 Web Application Viewed with BrowserSim

HTML5 Web Application Viewed with BrowserSim.

2.5.5. Enabling LiveReload for BrowserSim

Mobile Web Tools supports the LiveReload protocol for automatic reloading of web pages in enabled browsers as the application source is modified and saved. LiveReload can be enabled for your system browsers and, as demonstrated here, BrowserSim. This provides an interactive web development experience.

To enable LiveReload for BrowserSim, complete the following steps:

  1. Close any open BrowserSim simulated devices.
  2. In the Servers view, right-click an existing server to display the context menu and click New > Server.
  3. From the list, expand Basic, click LiveReload Server and click Finish.
  4. In the Servers view, right-click LiveReload Server and click Start.
  5. In the Servers view, right-click {application name} and click Show In > BrowserSim.

LiveReload is automatically enabled for this BrowserSim simulated device and all subsequent devices opened while the LiveReload server is running.

2.5.6. Changing the Application

With LiveReload enabled for BrowserSim, you can make changes to your application source code and BrowserSim automatically reloads the application when changes are saved. This is demonstrated here by making a simple change to the project index.html file, specifically changing the text in the application title banner.

To change your application:

  1. In the Project Explorer view, expand {project name} > src > main > webapp.
  2. Double-click index.html to open it for editing with the JBoss Tools HTML Editor.
  3. Locate the following line of code inside the <body> tags:

    <title>HTML5 Quickstart</title>

    and replace it with

    <title>My Quickstart</title>
  4. Save the file by pressing Ctrl+S (or Cmd+S).

This code change modifies the heading displayed on the main application page. Notice that BrowserSim automatically reloads the web page when you save the changed file and the application modifications are immediately visible.

2.5.7. Did You Know?

  • You can also launch the HTML5 Project wizard from the JBoss perspective by clicking File > New > HTML5 Project.
  • You can test an undeployed .html file with BrowserSim by right-clicking the .html file in the Project Explorer view and clicking Open With > BrowserSim.
  • To set BrowserSim as the IDE default web browser, in the JBoss perspective click Window > Web Browser > BrowserSim or click Window > Preferences > General > Web Browser and from the External web browsers list select BrowserSim.
  • You can also enable LiveReload for already opened BrowserSim simulated devices. After starting the LiveReload server, right-click the BrowserSim simulated device frame and click Enable LiveReload.

2.6. Generating a HTML5 Web Application Using the Mobile Web Palette

The IDE provides the Mobile Web palette that allows the user to make interactive web applications. This palette offers a wide range of features including drag-and-drop widgets for adding common web interface framework features such as HTML5, jQuery Mobile, and Ionic tags to html files. It also contains widgets like Panels, Pages, Lists, Buttons to make the applications more user friendly and efficient.

Use the instructions to complete the following steps:

2.6.1. Adding a New HTML5 jQuery Mobile File to a Project

The HTML5 jQuery Mobile file template consists of JavaScript and CSS library references that are inserted in the file’s HTML header. The template also inserts a skeleton of the jQuery Mobile page and listview widgets in the file’s HTML body. The following procedure details the steps to insert the template into your project.

To create a new HTML5 jQuery Mobile file in an existing project:

  1. In the Project Explorer view, expand [project name] > src > main.
  2. Right-click webapp and click New > HTML File.
  3. Complete the fields about the html file as follows:

    1. Ensure the parent folder field shows [project name]/src/main/webapp.
    2. In the File name field, type a name for the HTML5 file.
  4. Click Next.
  5. From the Templates table, select HTML5 jQuery Mobile Page (1.4) and click Finish.

Figure 2.23. Selecting the HTML5 jQuery Mobile Page (1.4) Option

HTML5 jQuery Mobile Page (1.4) Selected

Result: The new file is listed in the Project Explorer view under the project webapp directory and the file opens in the editor.

2.6.2. Adding New Pages to the Web Application

Use the jQuery Mobile Page widget to add pages to your mobile web application:

  1. In the Project Explorer view, expand [project name] > src > main > webapp.
  2. Right-click the new html file and click Open With > JBoss Tools HTML Editor.
  3. In the Palette view, click the jQuery Mobile tab to view the available widgets and click Page.
  4. Complete the fields about the page as follows:

    1. In the Header field, type a name for the page header.
    2. In the Footer field, type a name for the page footer.
  5. Click Finish.

    Figure 2.24. Adding a New Page

    Adding a New Page
  6. Save the changes to the file by clicking the Save icon.

Result: A page is added to the html file. JS and CSS references are also automatically added to the file by the Page widget wizard.

Figure 2.25. New Page Added to the HTML File

New Page Added to the HTML File

2.6.3. Customizing the Home Page of the Web Application

Use the widgets in the jQuery Mobile palette to customize the page. Use the instructions to add a menu to the page. This menu links to three other pages: Home, Search, and the Add Contacts page.

To create and add the menu to your application page:

2.6.4. Adding a Panel to the Page

To add a panel:

  1. In the html file, place the cursor where you want the panel.
  2. In the Palette view, in the jQuery Mobile tab, click Panel.
  3. Complete the fields about the Panel as follows:

    1. In the ID field, type my panel ID.
    2. Clear the Add Menu check box.
  4. Click Finish.
  5. Save the html file.

Figure 2.26. Adding a New Panel

Adding a New Panel

Result: A corresponding code snippet, for the newly added panel, is added to the html file where you had placed the cursor.

2.6.5. Adding a List to the Panel

To add a list:

  1. Within the panel’s code snippet, place your cursor at the desired location for the new list.
  2. In the Palette view, in the jQuery Mobile tab, click ListView.
  3. Complete the fields about the ListView as follows:

    1. In the Items section, 1 tab, in the Label field, type the name for the first list item on the page.
    2. In the URL (href) field, type a URL identifier for the label.

Figure 2.27. New Listitem Added to the Panel

New Listitem Added to the Panel
  1. Click Finish.
  2. Save the html file.

Result: The new list item name appears in the code snippet.

Figure 2.28. Code for the New Listitem in the Panel Added

Code for the New Listitem in the Panel Added

2.6.6. Adding a Button in the Header of the Page to Display the List

To add a button:

  1. Place the cursor within the header at the desired location for the new button.
  2. In the Palette view, in the jQuery Mobile tab, click Button.
  3. Complete the fields about the button as follows:

    1. In the Label field, type Menu.
    2. In the URL (href) field, type # followed by the panel ID (#my panel ID, in this case).
    3. In the Icon list, select an icon.
    4. In the Icon position list, select a desired value.
    5. Click the Icon only check-box.
  4. Click Finish.
  5. Save the html file.

Figure 2.29. Adding a Button

Adding a Button

Result: The following code is added to the body of the html file.

<div data-role="page" id="page-1">
    <div data-role="panel" id="my_panel_ID">
        <ul data-role="listview" id="listview-1">
            <li><a href="1st_item.html">1st_item</a></li>
            <li><a href="item2.html">Item 2</a></li>
            <li><a href="item3.html">Item 3</a></li>
        </ul>
    </div>

    <div data-role="header">
        <h1>This is the Page Header</h1>
        <a href="#my_panel_ID" id="button-1" class="ui-btn ui-icon-plus ui-btn-icon-notext ui-corner-all">Menu</a>
    </div>

    <div data-role="content">
        <p>Page content goes here.</p>
    </div>

    <div data-role="footer">
        <h4>This is the Page Footer</h4>
    </div>
</div>

2.6.7. Running and Testing the HTML5 Mobile Application Using BrowserSim

Test the newly added elements to the application by navigating to the interface on BrowserSim as follows:

  1. In the Project Explore view, expand [project name] > src > main > webapp.
  2. Right-click the changed html file and click Open With > BrowserSim.

Result: A simulated device appears and displays the application.

Figure 2.30. The Changes Made to the HTML File Displayed on BrowserSim

The Changes Made to the HTML File Displayed on BrowserSim

2.6.8. Did You Know?

  • To access the jQuery Mobile palette when the Palette view is not visible, click Window > Show View > Other, expand General and select Palette.
  • To add BrowserSim in the toolbar by clicking Window > Customize Perspective and select BrowserSim under Command Groups Availability. It appears as a Phone icon in the toolbar.
  • Use the Panel widget to create menus, collapsible columns, drawers, and more. The List View widget is an unordered list containing links to list items. jQuery Mobile applies the necessary styles to make the listview mobile friendly.
  • Add contacts to the Add Contacts page by following the above listed procedure. You can add Name, Email, Phone Number fields to the Add Contacts page by using the Text Input icon in the Mobile Web palette.

2.7. Creating Your First Hybrid Mobile Application

Mobile Hybrid Tools enables you to quickly create Cordova-based hybrid mobile applications using the Hybrid Mobile Project wizard. This wizard is a useful starting point for creating all new Cordova-based mobile applications in the IDE.

As illustrated in this article, from this foundation you can customize the application by adding a range of Cordova plug-ins for accessing device hardware with the Cordova Plug-in Discovery wizard. You can also test your Cordova-based hybrid mobile applications without leaving the IDE using CordovaSim, a mobile application simulator. The IDE also allows you to deploy your Hybrid Mobile project on the FeedHenry server.

The Hybrid Mobile Project wizard is also an ideal starting point for new users of Hybrid Mobile Tools and CordovaSim, guiding you through the necessary steps to set up the IDE and your system for developing Cordova applications before generating a basic Cordova project.

Note

Before attempting to install or create a hybrid mobile project with JBoss Tools, ensure that the Android SDK is installed and up to date. Creating or installing hybrid mobile projects without a working and updated installation of Android SDK can result in unexpected errors.

The instructions here demonstrate how to complete the following tasks:

2.7.1. Prerequisites

Ensure that the following prerequisites are met to create a hybrid mobile project:

2.7.2. Enabling the JBoss Hybrid Mobile Tools + CordovaSim Feature

To enable the JBoss Hybrid Mobile Tools + CordovaSim feature:

  1. In JBoss Central, click the Software/Update tab.
  2. In the Features Available list, select the JBoss Hybrid Mobile Tools + CordovaSim check box and then click Install/Update.

    Figure 2.31. Hybrid Mobile Tools + CordovaSim Check Box Selected

    Hybrid Mobile Tools + CordovaSim Check Box Selected
  3. Follow the on-screen instructions to complete the installation.

During the installation process you may receive warnings about installing unsigned content. If this is the case, review the details of the content and if satisfied click OK to continue with the installation.

Once installation is complete, you are prompted to restart Eclipse. Click Yes to restart immediately and No if you need to save any unsaved changes to open projects. Note that IDE changes do not take effect until the IDE is restarted.

2.7.3. Installing Android SDK

To install Android SDK:

  1. Download Android SDK and then unzip the file at the desired location.
  2. In the IDE, click Window > Preferences.
  3. In the Preferences window, in the type filter text field, type Hybrid Mobile.
  4. In the Hybrid Mobile category, click Android.
  5. Click Browse to locate and select the Android SDK directory on your machine.
  6. Click Apply and Close.

2.7.4. Creating a Hybrid Mobile Project

After the project wizard requirements are installed, you can restart the Hybrid Mobile Project wizard and follow it through to completion to create a template-based project. Within the wizard you must specify identifiers for the project and application and select the Cordova engine version to be used for building the project.

To create a Hybrid Mobile project, complete the following steps:

  1. In JBoss Central, under Start from scratch, click Hybrid Mobile Project.
  2. Complete the fields about the project and application as follows:

    1. In the Project name field, type a name for the project.
    2. In the Name field, type a name for the application
    3. In the ID field, type an alpha-numeric package name for the application; IDs are akin to Java package names and must begin with an alpha character and contain at least one dot.

      Figure 2.32. Provide the Project and Application Information

      Provide the Project and Application Information
  3. Click Next.
  4. From the Available Engines table, select the latest Apache Cordova version. If the Available Engines table is empty, first click Download and follow the instructions to install the latest Cordova engine version on your system.
  5. Click Finish.

Result: The project is created and listed in the Project Explorer view.

2.7.5. Customizing the Hybrid Mobile Project

Before building and running the Hybrid Mobile application, instructions are given here for customizing the project by adding the Cordova Device Motion plug-in and modifying the source code to make use of it. The plug-in gives access to the mobile device accelerometer and the code snippets added to this project check for data every one second and display the X, Y, Z acceleration values on the front page of the application. This plug-in is just one of a catalog of plug-ins available to add to your Hybrid Mobile project.

To customize the Hybrid Mobile project with the Cordova Device Motion plug-in, complete the following steps:

  1. In the Project Explorer view, right-click {project name} and click Install Cordova Plug-in.
  2. In the Find field, enter motion.
  3. From the filtered list of plug-ins, select org.apache.cordova.device-motion and click Finish.
  4. In the Project Explorer view, expand {project name} → www.
  5. Double-click index.html to open it in the JBoss Tools HTML Editor.
  6. Edit index.html as follows:

    1. Before the closing </head> tag, add the following lines

      <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
      <script type="text/javascript" charset="utf-8" src="js/index.js"></script>
    2. Replace the code inside the <body></body> tags with the following lines

      <div class="app">
           <h1>My Cordova Accelerometer App</h1>
           <div id="accelerometer">Waiting for accelerometer...</div>
      </div>

      Figure 2.33. The Modified index.html File

      The Modified index.html File
  7. Save the index.html file by pressing Ctrl+S (or Cmd+S).
  8. In the Project Explorer view, expand {project name} → www → js.
  9. Double-click index.js to open it in the IDE JavaScript Editor.
  10. Replace the code in index.js with the following lines

    // The watch id references the current `watchAcceleration`
        var watchID = null;
    
        // Wait for device API libraries to load
        document.addEventListener("deviceready", onDeviceReady, false);
    
        // device APIs are available
        function onDeviceReady() {
            console.log("deviceready");
            startWatch();
        }
    
        // Start watching the acceleration
        function startWatch() {
    
            // Update acceleration every 1 seconds
            var options = { frequency: 1000 };
            watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
        }
    
        // Stop watching the acceleration
        function stopWatch() {
            if (watchID) {
                navigator.accelerometer.clearWatch(watchID);
                watchID = null;
            }
        }
    
        // onSuccess: Get a snapshot of the current acceleration
        function onSuccess(acceleration) {
            var element = document.getElementById('accelerometer');
            element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
                                'Acceleration Y: ' + acceleration.y + '<br />' +
                                'Acceleration Z: ' + acceleration.z;
        }
    
        // onError: Failed to get the acceleration
        function onError() {
            alert('onError!');
        }
  11. Save the index.js file.

Result: Your Hybrid Mobile Project is now customized and saved.

2.7.6. Testing the Hybrid Mobile Application using CordovaSim

You can build and test the Hybrid Mobile application within the IDE using CordovaSim. CordovaSim is a mobile device simulator specifically for testing Cordova-based hybrid mobile applications. Using the CordovaSim control panel you can input sample data for mobile device hardware, as illustrated here for a device accelerometer.

To run and test your Hybrid Mobile application using CordovaSim, complete the following steps:

  1. In the Project Explorer view, right-click {project name} and click RunRun with CordovaSim.
  2. In the CordovaSim control panel, expand Accelerometer and drag the 3D device representation to generate device accelerometer data.

    Figure 2.34. Generated Device Accelerometer Data Displayed in Application

    Generated Device Accelerometer Data Displayed in Application

Result: Your Hybrid Mobile application is running for testing.

2.7.7. Deploying the Hybrid Mobile Project on the FeedHenry Server

The IDE allows users to quickly and easily publish a Mobile Hybrid (Cordova) application, developed in the IDE, on the FeedHenry server.

The instructions here demonstrate to complete the following tasks:

2.7.8. Connecting the Cordova Application to the FeedHenry Server

To connect the Cordova application to the FeedHenry server:

  1. In the Project Explorer view, right-click the {project name} and NewOther.

    Note

    Refer to the Create a Hybrid Mobile Project section to create the Hybrid Mobile (Cordova) application.

  2. In the search field, type FeedHenry and then select New FeedHenry Application and click Next.
  3. In the Create FeedHenry Application window, enter the following details:

    1. Ensure that the Source project field displays the name of the master Cordova project
    2. In the Select FeedHenry project field, select the FeedHenry project name
    3. In the Git remote name field, type a Git remote name for the FeedHenry repository
  4. Click Finish.

Result: The Almost Done window confirms that the project is created on the platform. The project structure in the Project Explorer view, shows the feedhenry.js and the fhconfig.json files.

Figure 2.35. Almost done Window Confirms the Application Creation

Almost done Window Confirms the Application Creation

2.7.9. Pushing the Cordova Application to the FeedHenry Server

To push the application to the FeedHenry server:

  1. In the Project Explorer view, right-click the {project name} and click TeamPush Branch “master”.
  2. If you are prompted for a confirmation to connect, click Yes.
  3. In the Push Branch master window, enter the following details:

    1. In the Remote field, enter the location for the remote Git repository.
    2. In the Branch field, type master.
  4. Click Next.

    Figure 2.36. Details of the Push Added in the Push Branch master Window

    Details of the Push Added in the Push Branch master Window
  5. Confirm the details in the Push Confirmation window and click Finish.
  6. The Pushed to git window confirms the push. Click OK.
  7. Log into FeedHenry at https://[your-studio-domain].feedhenry.com.
  8. Click Projects and then click the relevant application.

Result: The Cordova application is visible in the FeedHenry instance.

Figure 2.37. Cordova Application Published on the FeedHenry Server

Cordova Application Published on the FeedHenry Server

2.7.10. Modifying the Icon for a Mobile Application

Define the icons for the Mobile Hybrid application using the icon tag in the config.xml file. If an icon is not specified, the Apache Cordova logo is used as the default icon.

To change the application icon:

  1. Save the icon in the <workspace> /www/res/icon directory of your project.
  2. In the IDE, in the Project Explorer view, locate the config.xml file.

    Note

    If you are using Cordova 4.0.0 or lower, the config.xml file is located in the www directory. For Cordova versions higher than 4.0.0 the config.xml file is located, a level higher, in the project directory.

  3. Double-click config.xml to open it in the config.xml editor.
  4. Click the config.xml tab to edit the file.
  5. To define a single default icon for all platforms, add the following code anywhere withing the widget tag in the config.xml file:

    <icon src="www/res/icon[image name].png" />

    Figure 2.38. Icon Tag Added to the config.xml File

    Icon Tag Added to the config.xml File

    Alternatively,

    • To define a pixel-perfect icon for Android, add the following code in the config.xml file:
    <platform name="android">
    <icon src="www/res/android/[image name].png" density="ldpi" />
    <icon src="www/res/android/[image name].png" density="mdpi" />
    <icon src="www/res/android/[image name].png"density="hdpi" />
    <icon src="www/res/android/[image name].png" density="xhdpi" />
    </platform>
    • To define a pixel-perfect icon for iOS, add the following code in the config.xml file:
    <platform name="ios">
    <icon src="www/res/ios/[image name].png" width="180" height="180" >
    </platform>
  6. Save the config.xml file.
  7. Right-click the application and click Run AsRun on Android Emulator.
  8. On the emulator, click the Home button and then click the Applications button to view the modified icon for the application.

Result: The icon for the application is modified.

Figure 2.39. Modified Icon for the Application Displayed on the Android Emulator

Modified Icon for the Application on the Android Emulator

2.7.11. Editing an Application Splash Screen

You can edit the splash screen associated with your application using the splash tag within the platform tag in the config.xml file. If you are using Cordova 4.0.0 or higher, you must first install the new cordova-plugin-splashscreen to continue to use the splash screen and then use the steps below to edit the splash screen. For Cordova versions lower than 4.0.0, simply follow the steps below to edit the splash screen.

To change the application splash screen:

  1. Save the image for the splash screen in the <workspace> /www/res directory of your project.
  2. In the IDE, in the Project Explorer view, locate the config.xml file.

    Note

    If you are using Cordova 4.0.0 or lower, the config.xml file is located in the > www directory. For Cordova versions higher than 4.0.0, the config.xml file is located, a level higher, in the project directory.

  3. Double-click config.xml to open it in the config.xml editor.
  4. Click the config.xml tab to edit the file.
  5. To define the splash screen add the following code within the widget tag in the config.xml file:

    Note

    You can use any density that exists in the Android project.

    <platform name="android">
    <splash src="www/res/[image name].png" density="land-hdpi"/>
    <splash src="www/res/[image name].png" density="land-ldpi"/>
    <splash src="www/res/[image name].png" density="land-mdpi"/>
    <splash src="www/res/[image name].png" density="land-xhdpi"/>
    
    <splash src="www/res/[image name].png" density="port-hdpi"/>
    <splash src="www/res/[image name].png" density="port-ldpi"/>
    <splash src="www/res/[image name].png" density="port-mdpi"/>
    <splash src="www/res/[image name].png" density="port-xhdpi"/>
    </platform>
    <preference name="SplashScreenDelay" value="10000" />
  6. Save the config.xml file.
  7. Right-click the application and click Run AsRun on Android Emulator.

Result: The edited splash screen appears while the application is starting.

2.7.12. Did You Know?

  • You can manually initiate installation of JBoss Hybrid Mobile Tools and CordovaSim by locating them in the JBoss Central Software/Update tab or by dragging the following link into JBoss Central: https://devstudio.jboss.com/central/install?connectors=org.jboss.tools.aerogear.hybrid
  • You can change the Cordova engine associated with the project after it is created. In the Project Explorer view, right-click the project and click Properties. Click Hybrid Mobile Engine and select the engine you want to use. Click OK to save the engine change and close the Properties window.
  • You can download multiple Cordova engines to your system with which to build your projects. The Download wizard can be accessed from the Hybrid Mobile Engine pane in the project Properties window, in addition to the Hybrid Mobile Project wizard.
  • From the IDE you can also initiate testing of Cordova projects with a connected Android device, system Android Emulator, and system iOS Simulator. The project is built in the necessary native format during the process.
  • With the CordovaSim control panel, you can generate simulated data for a range of device hardware, including geolocation and battery status. CordovaSim also manages camera actions, enabling you to upload system images to simulate receiving camera data.
  • A Shake button under Accelerometer in the CordovaSim control panel enables you to simulate a hardware-shake gesture and test the impact on your application.

2.8. Importing and Developing an Existing FeedHenry Application

The IDE includes an Import wizard to allow users to quickly and easily import previously created FeedHenry applications. Once the application is imported, you can change or enhance the application, test the changes, and then push it back to the FeedHenry server.

Note

Before attempting to install or create a hybrid mobile project with JBoss Tools, ensure that the Android SDK is installed and up to date. Creating or installing hybrid mobile projects without a working and updated installation of Android SDK can result in unexpected errors.

Follow the provided steps to import and make changes to a FeedHenry application in your workspace:

2.8.1. Prerequisites

Ensure that the following prerequisites are met to enable the FeedHenry feature:

2.8.2. Installing Android SDK

To install Android SDK:

  1. Download Android SDK and then unzip the file at the desired location.
  2. In the IDE, click Window > Preferences.
  3. In the Preferences window, in the type filter text field, type Hybrid Mobile.
  4. In the Hybrid Mobile category, click Android.
  5. Click Browse to locate and select the Android SDK directory on your machine.
  6. Click Apply and Close.

2.8.3. Enabling the FeedHenry Feature

To enable the FeedHenry feature:

  1. In JBoss Central, click the Software/Update tab.
  2. In the Features Available list, locate and click the Hybrid Mobile Tools + CordovaSim check box and then click Install/Update.

    Figure 2.40. Hybrid Mobile Tools + CordovaSim Check Box Selected

    Hybrid Mobile Tools + CordovaSim Check Box Selected
  3. Follow the on-screen instructions to complete the installation.

2.8.4. Setting the Preferences for Your Application Import

To set the preferences:

  1. Click Window > Preferences.
  2. In the Preferences window, in the search field type, FeedHenry and press Enter.
  3. Complete the following fields in the Preferences window:

    1. Ensure that the Target URL field displays the URL to your FeedHenry server. The URL to your FeedHenry server should be something like: https://[your-studio-domain].feedhenry.com.
    2. In the API Key field, copy and paste the API key from the FeedHenry website.

      Figure 2.41. Setting Preferences for FeedHenry

      Setting Preferences for FeedHenry
      Note

      The user can either use an existing API key or generate a new one to set the preferences. To obtain the API key from the FeedHenry website click Settings > API Key Management. To generate a new API key, click Settings > API Key Management, and then click Add New Key.

  4. Click Apply and Close to close the Preferences window.

2.8.5. Importing Your FeedHenry Application

Ensure that your Preferences are set before importing a FeedHenry application. If not set yet, you are prompted to set the preferences. These preferences are set once when importing an application for the first time and the configured preferences are used for all imports in the future.

To import your FeedHenry application:

  1. Click File > Import.
  2. Expand FeedHenry, click Import Cordova Application, and click Next. The Import wizard displays the projects that you can import.

    Note

    In case the Invalid Preferences window appears, click Yes to correct the preferences.

  3. Expand the project to import an application from and select the FeedHenry application to be imported.
  4. In the Directory field, enter the location where you want to clone the application locally.
  5. Click Finish.

Figure 2.42. Selecting an Application to be Imported

Selecting an Application to be Imported

If you have set a password for the SSH keys, you are prompted to enter the password so that it can import the application.

Result: The FeedHenry project is successfully imported and appears in the Project Explorer view. The Cordova config.xml file for this project opens in the Editor.

2.8.6. Testing the Application Import

To test the application import:

  1. In the Project Explorer view, right-click the application and then click Run AsRun w/remote FeedHenry server. A CordovaSim simulated device displaying the application appears.

    Figure 2.43. Simulated Device Displaying the Imported Application

    Simulated Device Displaying the Imported Application
  2. In the Enter Your Name Here field on the simulated device, type your name.
  3. Click Say Hello From The Cloud.

Result: The simulated device displays the “Hello [Your Name] string.

2.8.7. Changing the Application

After successfully importing the FeedHenry application, follow the instructions to change the application:

  1. In the Project Explorer view, expand [application name]www and then double-click index.html to open it using the Editor.
  2. In the code, locate and delete the following line:

    This is a basic Cordova App that can take in your name, send it to a cloud app and display the response.
  3. Replace the deleted text with the following line:

    Hello from Hybrid Mobile Tools!
  4. Save the index.html file by pressing Ctrl+S. Alternatively, to save click FileSave or click the Save icon.

Figure 2.44. The Edited index.html File

The Edited index.html File

2.8.8. Testing the Application

To test the imported application, right-click the application and then click Run AsRun w/remote FeedHenry server.

Figure 2.45. The Edited FeedHenry Application

The Edited FeedHenry Application

The changes made to the index.html file are reflected on the simulated device. Click a corner of the displayed device to rotate it in that direction. Alternatively, right-click the simulated device and click Rotate Right or Rotate Left as to rotate it in the desired direction. To view the application on a different CordovaSim simulated device, right-click the device and click Skin. From the list of skins, select a skin to view the application.

2.8.9. Pushing the Changes Back to the FeedHenry Server

Use the following instructions to push changes to the application back to the FeedHenry server:

  1. In the Project Explorer view, right-click the application name.
  2. Click TeamCommit.
  3. In the Commit Changes window, Commit message field, type a message for the commit.
  4. In the Files field, select the files that you have edited and want to push to the server and then click Commit and Push.
  5. In the Push Results [application name] window, ensure all the details are correct and click OK.
  6. Log into FeedHenry at https://[your-studio-domain].feedhenry.com.
  7. Click Projects.
  8. Click the Project Title under which your application is located and then click the application.

Result: The simulated device in the App Preview section displays the change that you have just pushed to the FeedHenry server.

Figure 2.46. FeedHenry Application Edited and Displayed on the FeedHenry Server

FeedHenry Application Edited and Displayed on the FeedHenry Server

2.8.10. Did You Know?

  • Add a new API key to your FeedHenry account by clicking Add New Key and then following the on-screen instructions.
  • Set up your SSH key in the FeedHenry account by clicking SettingsSSH Key Management and then following the on-screen instructions.

2.8.11. Troubleshooting

2.8.11.1. Git Communication Error

Figure 2.47. Git Communication Error

Git Communication Error

Error Message

Problem when cloning the application. This can be due to a network problem or missing security credentials. Refer to error log for details.

Issue

When a FeedHenry account is set up, the user’s API Keys are configured by default, but the SSH Public key must be manually configured. Importing a FeedHenry application means that the application repository is accessed via Git. Without a Public SSH key, the tools are unable to complete the action and this error appears.

Resolution

  1. Click OK to close the Git Communication Error window.
  2. Log into FeedHenry at: https://[your-studio-domain].feedhenry.com.
  3. Click the icon located in the uppermost right-side corner of the screen to display the context menu.
  4. Click SettingsSSH Key Management and then click Add New Key.
  5. In the Public Key field, enter your SSH Public key. An existing Public SSH key is available at ~/.ssh/id_rsa.pub. Alternatively, generate a new Public SSH key with the following command:

    $ ssh-keygen -t rsa -C "username@example.com"

2.8.11.2. Invalid Preferences

Figure 2.48. Invalid Preferences

Invalid Preferences

Issue

When the user logs into FeedHenry for the first time, the Invalid Preferences dialog box appears informing the user that the FeedHenry connection preferences are unidentified or invalid and that the user must correct the preferences. Refer to the Set the Preferences section for details to set the connection preferences.