Friday, August 19, 2016

How to implement Drag and Drop Function in a JavaFX Application

I have spent alot of time working on implementing more functionality of our JavaFX PDF Viewer. I recently added a drag and drop functionality to the viewer which enables the user to drag and drop a PDF file into the viewer to be decoded and displayed. This is very easy to implement in JavaFX so here is a short tutorial for you to follow.

In this article, we will create a simple scene, and add the DnD function which will only accept image files (jpeg, jpg ,png) . This file will them be displayed when dropped unto the application.

Drag and drop support requires several items.

1. Component that will accept the draggable objects.

In this example we will use a StackPane to accept the DnD function. Once the image has been dropped onto the StackPane the we will use an ImageView to display the image

The code for displaying the image will be
  1. Image img = new Image("path_to_image");
  2. ImageView imageView = new ImageView();
  3. imageView.setImage(img);
2. Handling the DnD Events

There are different DnD events we can add to the StackPane. In this example we will add three events to the StackPane.

The first we will add is the setOnDragOver
  1. stackPane.setOnDragOver(new EventHandler() {
  2.             @Override
  3.             public void handle(final DragEvent event) {
  4.                //Do something when an Object is dragged over the StackPane
  5.             }
  6.         });
We will add an event which will detect when a an object is dropped onto the StackPane. This will be the setOnDragDropped
  1. contentPane.setOnDragDropped(new EventHandler() {
  2.             @Override
  3.             public void handle(final DragEvent event) {
  4.                 //Do something when an object is dropped onto the StackPane
  5.             }
  6.         });
The last we will add is the setOnDragExited
  1. contentPane.setOnDragExited(new EventHandler() {
  2.             @Override
  3.             public void handle(final DragEvent event) {
  4.                //Do something when an object exits the StackPane
  5.             }
  6.         });
3. Filter to control which types of file are supported

Since we only want our program to accept only images, we will want to accept specific file types (i.e. png, jpeg). In this case, when an object is dragged over the StackPane we will check if it is an image file, if not,we tell our program not to accept it. We will store any item which is being dragged to the StackPane in a DragBoard, we will then check if the object stored in the DragBoard is an image file type.
  1.  final Dragboard db = e.getDragboard();
  2.  
  3.         final boolean isAccepted = db.getFiles().get(0).getName().toLowerCase().endsWith(".png")
  4.                 || db.getFiles().get(0).getName().toLowerCase().endsWith(".jpeg")
  5.                 || db.getFiles().get(0).getName().toLowerCase().endsWith(".jpg");
  6.  
  7.         if (db.hasFiles() && isAccepted) {
  8.            //display the image file
  9.         } else {
  10.             e.consume();
  11.         }
Now we put this all together in a code example
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.util.logging.Level;
  5. import java.util.logging.Logger;
  6. import javafx.application.Application;
  7. import static javafx.application.Application.launch;
  8. import javafx.application.Platform;
  9. import javafx.event.EventHandler;
  10. import javafx.scene.Scene;
  11. import javafx.scene.image.Image;
  12. import javafx.scene.image.ImageView;
  13. import javafx.scene.input.DragEvent;
  14. import javafx.scene.input.Dragboard;
  15. import javafx.scene.input.TransferMode;
  16. import javafx.scene.layout.BorderPane;
  17. import javafx.scene.layout.StackPane;
  18. import javafx.scene.paint.Color;
  19. import javafx.stage.Stage;
  20.  
  21. public class DragAndDropExample extends Application {
  22.  
  23.     ImageView imageView;
  24.     StackPane contentPane;
  25.     BorderPane layout; 
  26.     public static void main(String[] args) {
  27.         launch(args);
  28.     } 
  29.     @Override
  30.     public void start(Stage primaryStage) {
  31.         primaryStage.setTitle("Drag and Drop");
  32.         layout = new BorderPane();
  33.         contentPane = new StackPane();
  34.         Scene scene = new Scene(layout, 800, 800, Color.WHITE);
  35.  
  36.         contentPane.setOnDragOver(new EventHandler() {
  37.             @Override
  38.             public void handle(final DragEvent event) {
  39.                 mouseDragOver(event);
  40.             }
  41.         }); 
  42.         contentPane.setOnDragDropped(new EventHandler() {
  43.             @Override
  44.             public void handle(final DragEvent event) {
  45.                 mouseDragDropped(event);
  46.             }
  47.         }); 
  48.          contentPane.setOnDragExited(new EventHandler() {
  49.             @Override
  50.             public void handle(final DragEvent event) {
  51.                 contentPane.setStyle("-fx-border-color: #C6C6C6;");
  52.             }
  53.         });
  54.        layout.setCenter(contentPane);
  55.         primaryStage.setScene(scene);
  56.         primaryStage.show();
  57.     }
  58.     void addImage(Image i, StackPane pane){
  59.         imageView = new ImageView();
  60.         imageView.setImage(i);
  61.         pane.getChildren().add(imageView);
  62.     }
  63.   private void mouseDragDropped(final DragEvent e) {
  64.         final Dragboard db = e.getDragboard();
  65.         boolean success = false;
  66.         if (db.hasFiles()) {
  67.             success = true;
  68.             // Only get the first file from the list
  69.             final File file = db.getFiles().get(0);
  70.             Platform.runLater(new Runnable() {
  71.                 @Override
  72.                 public void run() {
  73.                     System.out.println(file.getAbsolutePath());
  74.                     try {
  75.                         if(!contentPane.getChildren().isEmpty()){
  76.                             contentPane.getChildren().remove(0);
  77.                         }
  78.                         Image img = new Image(new FileInputStream(file.getAbsolutePath()));  
  79.  
  80.                         addImage(img, contentPane);
  81.                     } catch (FileNotFoundException ex) {
  82.                         Logger.getLogger(DragAndDropExample.class.getName()).log(Level.SEVERE, null, ex);
  83.                     }
  84.                 }
  85.             });
  86.         }
  87.         e.setDropCompleted(success);
  88.         e.consume();
  89.     }
  90.     private  void mouseDragOver(final DragEvent e) {
  91.         final Dragboard db = e.getDragboard();
  92.  
  93.         final boolean isAccepted = db.getFiles().get(0).getName().toLowerCase().endsWith(".png")
  94.                 || db.getFiles().get(0).getName().toLowerCase().endsWith(".jpeg")
  95.                 || db.getFiles().get(0).getName().toLowerCase().endsWith(".jpg");
  96.  
  97.         if (db.hasFiles()) {
  98.             if (isAccepted) {
  99.                 contentPane.setStyle("-fx-border-color: red;"
  100.               + "-fx-border-width: 5;"
  101.               + "-fx-background-color: #C6C6C6;"
  102.               + "-fx-border-style: solid;");
  103.                 e.acceptTransferModes(TransferMode.COPY);
  104.             }
  105.         } else {
  106.             e.consume();
  107.         }
  108.     }
  109. }
Now lets run the Application.


Hopefully you have found this quick guide useful.
Written by Ernest Duodu

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Java Developer Course

Java Programming For Beginners

Complete Java For Selenium WebDriver And Test Automation

The Complete Android & Java Course - Build 21 Android Apps


Basic guide for Class Objects and Methods in Java for Selenium Webdriver

Thursday, August 18, 2016

Java 8 Method References explained in 5 minutes

At IDR Solutions I spend alot of time on working on the development of our Java PDF Library. As I spend alot of time using Java 8 in our JavaFX PDF Viewer I thought that it might be useful to a series article of the new features in JDK8.

In my previous articles, we have looked at Lambda Expression, Streams API and Default Methods. In this latest article in the series, we will be looking at Method References.

What is Method References?
It is a feature which is related to Lambda Expression. It allows us to reference constructors or methods without executing them. Method references and Lambda are similar in that they both require a target type that consist of a compatible functional interface.

Types of Method Reference
There are four types of method reference, the table below summarizes this.


I will explain further about the four types of method referenced in the table.

1 . Reference to a Static Method
  1. public class ReferenceToStaticMethodExample {
  2.      /**
  3.      * @param args the command line arguments
  4.      */
  5.     public static void main(String[] args) {
  6.         List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16);
  7.         List primeNumbers = ReferenceToStaticMethodExample.findPrimeNumbers(numbers, 
  8.                 (number) -> ReferenceToStaticMethodExample.isPrime((int) number));
  9.  
  10.         System.out.println("Prime Numbers are " + primeNumbers);
  11.     }
  12.  
  13.     public static boolean isPrime(int number) {
  14.         if (number == 1) {
  15.             return false;
  16.         }
  17.         for (int i = 2; i < number; i++) {             
  18.             if (number % i == 0) {                 
  19.                 return false;             
  20.             }         }         
  21.         return true;     
  22.     }     
  23.  
  24.     public static List findPrimeNumbers(List list, Predicate predicate) {         
  25.         List sortedNumbers = new ArrayList();         
  26.         list.stream().filter((i) -> (predicate.test(i))).forEach((i) -> {
  27.             sortedNumbers.add(i);
  28.         });
  29.         return sortedNumbers;
  30.  
  31.     }
  32. }
As you can see in this code, we made reference to a static method in this class.

ContainingClass::staticMethodName


2. Reference To Constructor
  1. public class ReferenceToConstructor {
  2.  
  3.     /**
  4.      * @param args the command line arguments
  5.      */
  6.     public static void main(String[] args) {
  7.         // TODO code application logic here
  8.          List  numbers = Arrays.asList(4,9,16,25,36);
  9.          List squaredNumbers = ReferenceToConstructor.findSquareRoot(numbers,Double::new);
  10.          System.out.println("Square root of numbers = "+squaredNumbers);
  11.     }
  12.  
  13.     private static List findSquareRoot(List list, Function<double,double -> f){
  14.         List result = new ArrayList();
  15.         list.forEach(x -> result.add(f.apply(Math.sqrt(x))));
  16.         return result;
  17.     }
  18. }
This is very similar to reference to to a static method.The difference between the two is, the constructor reference method name is new.


3. Reference To an Instance Method Of An Arbitrary Object Of A Particular Type
  1. public class ReferenceToInstanceMethodAOPT {
  2.  
  3.     /**
  4.      * @param args the command line arguments
  5.      */
  6.  
  7.      private static class Person {
  8.  
  9.             private final String name;
  10.             private final int age;
  11.  
  12.  
  13.             public Person(String name, int age) {
  14.                 this.name = name;
  15.                 this.age = age;
  16.  
  17.             }
  18.  
  19.             public String getName() {
  20.                 return name;
  21.             }
  22.  
  23.             public int getAge() {
  24.                 return age;
  25.             }
  26.  
  27.  
  28.         }
  29.     public static void main(String[] args) {
  30.         // TODO code application logic here
  31.         List persons = new ArrayList();
  32.             persons.add(new Person("Albert", 80));
  33.             persons.add(new Person("Ben", 15));
  34.             persons.add(new Person("Charlote", 20));
  35.             persons.add(new Person("Dean", 6));
  36.             persons.add(new Person("Elaine", 17));
  37.  
  38.  
  39.             List allAges = ReferenceToInstanceMethodAOPT.listAllAges(persons, Person::getAge);
  40.             System.out.println("Printing out all ages \n"+allAges);
  41.     }
  42.  
  43.  
  44.     private static List listAllAges(List person, Function < person, integer="" -> f){
  45.         List result = new ArrayList();
  46.         person.forEach(x -> result.add(f.apply(x)));
  47.         return result;
  48.     }
  49. }
This mean providing reference to any of the persons object in the List of a particular type which is the Person.So the containing type is persons and the method name is getAge();


4. Reference To An Instance Method Of A Particular Object
  1. public class ReferenceToInstanceMethodOAPO {
  2.  
  3.     /**
  4.      * @param args the command line arguments
  5.      */ 
  6.     public static void main(String[] args) {
  7.         // TODO code application logic here
  8.         List names = new ArrayList();
  9.             names.add("David");
  10.             names.add("Richard");
  11.             names.add("Samuel");
  12.             names.add("Rose");
  13.             names.add("John");
  14.  
  15.            ReferenceToInstanceMethodOAPO.printNames(names,System.out::println);
  16.     }
  17.   
  18.     private static void printNames(List list, Consumer c ){
  19.         list.forEach(x -> c.accept(x));
  20.     }
  21. }
Since System.out is an instance of type PrintStream, we then call println method of the instance.


So what can we Take Away?
  1. You can use replace Lambda Expressions with Method References where Lamdba is invoking already defined methods.
  2. You can’t pass arguments to methods Reference
  3. To use Lambda and Method Reference, make sure you have Java 8 installed. They do not work on Java 7 and earlier versions.
Hopefully you have found this quick guide useful
Written by Ernest Duodu

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Java Developer Course

Java Programming For Beginners

Complete Java For Selenium WebDriver And Test Automation

The Complete Android & Java Course - Build 21 Android Apps

Java for Android Development - Getting Started (Khmer)

Monday, August 15, 2016

Top 10 Open Source Java and JavaEE Application Servers

At IDR Solutions we make use of a Open Source Java Application Server called Glassfish to run our free PDF to HTML5 Converter. I have wondered what the alternatives were to Glassfish and decided to do some research into other Open Source Java and JavaEE Application Servers.

What is an Application Server?

At IDR Solutions we make use of a Open Source Java Application Server called Glassfish to run our free PDF to HTML5 Converter. I have wondered what the alternatives were to Glassfish and decided to do some research into other Open Source Java and JavaEE Application Servers.

Join me as I guide you through my Top 10 Open Source Java and JavaEE Application Servers.

What is an Application Server?Firstly what is an Application Server? An application server can often be described as a software framework that resides in the middle tier of a server centric architecture.

The application server can often be viewed as part of a three-tier application, which are a graphical user interface (GUI) server, an application (business logic) server, and a database and transaction server and provide services for security and state maintenance, along with data access and persistence.

For Web applications, an application server will be running in the same environment as its web server(s), and application servers are there to support the construction of dynamic pages and implement services like clustering, fail-over, and load-balancing, so developers can focus on implementing the business logic.

At IDRsolutions we like to describe it to non-technical users as a magic door. It allows you to write code to run on a server and code on a client and allow them to talk to each other. It all just works and handles all the complexity transparently for you.

So now we have established what an Application server is, we will now take a look at the available Java Application Servers.

Glassfish

GlassFish is an open-source application server project  originally started by Sun Microsystems for the Java EE platform and now part of the Oracle Corporation. It is available under a dual-license: the Common Development and Distribution License (CDDL) and the GNU General Public License (GPL) with the classpath exception. Oracle no longer provides commercial support for GlassFish Server but several organisations have filled that space, most notably Payara who are co-sponsors for NetBeans Day UK.

GlassFish is often considered as the reference implementation of Java EE and so supports Enterprise JavaBeans (a managed, server-side component architecture for modular construction of enterprise applications), JPA (Java Persistence API ), JavaServer Faces, JMS (Java Message Service), RMI (Java Remote Method Invocation), JavaServer Pages, servlets and more. Glassfish allows you to to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. Optional components can also be installed for additional services.

It is built upon a modular kernel powered by OSGi, and runs straight on top of the Apache Felix implementation. It is also capable of running with Equinox OSGi or Knopflerfish OSGi runtimes. HK2 abstracts the OSGi module system to provide components, which can also be viewed as services and injected into the run time and uses a derivative of Apache Tomcat as the servlet container for serving Web content, with an added component called Grizzly which uses Java New I/O (NIO) for scalability and speed. We have previous covered how to set up Glassfish on a Linux Server.

JBoss Enterprise Application Platform

The JBoss Enterprise Application Platform which is also known as JBoss EAP is a open-source (available under the GNU Lesser General Public License) Java EE-based application server runtime platform used for building, deploying, and hosting highly transactional Java applications and services. It is also available as a subscription-based server. The JBoss Enterprise Application Platform is part of a wider portfolio of software known as the JBoss Enterprise Middleware portfolio.

JBoss works cross-platform and is usable on any operating system that supports Java. Its key features includes support for the Java EE and Web Services standards, Enterprise Java Beans (EJB),Java persistence using Hibernate, Object request broker (ORB) using JacORB for interoperability with CORBA objects,the JBoss Seam framework, including Java annotations, JavaServer Faces (JSF), including RichFaces, Web application services, including Apache Tomcat for JavaServer Pages (JSP) and Java Servlets

JBoss included Security services, including Java Authentication and Authorization Service (JAAS) and pluggable authentication modules (PAM) and additional Web Services and interoperability, including JAX-RPC, JAX-WS, many WS-* standards, and MTOM/XOP

There is also additional Integration and messaging services, management and service oriented architecture and Java management extensions and additional monitoring features are available.

Wildfly

WildFly, was better known as JBoss AS is an application server created by JBoss, but now under continuous development by Red Hat. WildFly is written in Java, and implements the Java Platform, Enterprise Edition (Java EE) specification separately/standalone from the JBoss Enterprise Application Platform. Being Java based means it can run multiple platforms.

WildFly is free and open-source software, and available under the GNU Lesser General Public License (LGPL), version 2.1. Wild Fly is currently in 8.2.0 Final and 9.0.0Beta2 Release.

Some of the functionality and features included in WildFly is Clustering, Deployment API, Distributed caching (using Infinispan, a standalone project) ,Distributed deployment, Enterprise JavaBeans versions 3 and 2.1, Failover (including Web and EJB sessions), persistence programming, Java Authentication and Authorization Service (JAAS), Java EE Connector Architecture (JCA) integration, Java Management Extensions, Java Message Service (JMS) integration, Java Naming and Directory Interface (JNDI), Java Transaction API (JTA), Java Authorization Contract for Containers,  (JACC) integration JavaMail, Java Server Faces 1.2 (Mojarra)Java Server Pages (JSP) / Java Servlet 2.1/2.5

Wildfly also supports web services like JAX-WSJDBCLoad balancing, and includes a Management API, a OSGi frameworkRMI-IIOP and can be executed in two server modes: a traditional, single JVM, standalone mode, and a multi-JVM option, Domain mode, which synchronizes configuration across any number of processes and hosts.

Apache Tomcat

Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies and was developed in an open and participatory environment and released under the Apache License version 2 and developed by the Apache Software Foundation (ASF). Apache Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a “pure Java” HTTP web server environment for Java code to run in.

Apache TomEE

Apache TomEE is the Java Enterprise Edition of Apache Tomcat which combines several Java enterprise projects which include the Apache OpenEJB, Apache OpenWebBeans, Apache OpenJPA, Apache MyFaces.

Apache TomEE Web Profile can deliver Servlets, JSP, JSF, JTA, JPA, CDI, Bean Validation and EJB Lite and also delivers JAX-RS (RESTfull Services) plus EJB Full, Java EE Connector Architecture, JMS (Java Message Service) and JAX-WS (Web Services) and includes Mojarra and EclipseLink support.

Apache Geronimo

Apache Geronimo is an open source application server developed by the Apache Software Foundation and distributed under the Apache license. Apache Geronimo is compatible with the Java Enterprise Edition (Java EE) 6 specification supports various technologies such as JMS, Enterprise JavaBeans, Connectors, servlets, JSP, JSF, Unified Expression Language and JavaMail. Developers can create applications that are both portable and scalable, and that integrate well with legacy technologies. It should be noted that development of Apache Geronimo has now largely been ceased although not completely.

Jetty

Jetty is a Java based HTTP (Web) server and Java Servlet container and is developed as a free and open source project as part of the Eclipse Foundation (originally it was developed as an independent open source project). The web server is relatively popular and is used in products such as Apache ActiveMQ, Alfresco, Apache Geronimo, Apache Maven, Apache Spark, Google App Engine,  Eclipse, Twitter’s Streaming API  and also supports the latest Java Servlet API (with JSP support) as well as AJP, JASPI, JMX, JNDI, OSGi, SPDY and WebSocket.

JOnAS

JOnAS is an open-sourced implementation of the Java EE application server specification, released under the LGPL open-source license and developed and hosted by the ObjectWeb consortium (ObjectWeb is a non-profit European consortium, founded by INRIA, Groupe Bull, and France Télécom).

JOnAS provides a fully compliant EJB container through EasyBeans and is available with an embedded Tomcat or Jetty web container which is 1.6 JVM supported, and can run on numerous operating systems including Linux, Windows, AIX, and many Posix platforms.

Version 5 of JOnAS is fully based on the OSGi framework; using either Apache Felix, Eclipse Equinox or Knopflerfish meaning JOnAS components are packaged as bundles,and contains tools for creating, deploying and monitoring JOnAS clusters; it also includes self-management features too.

Resin Servlet Container (Open Source)

Resin is a web server and Java application server created by Caucho Technology. Resin is available under a GPL license and a commercial license. The Commercial licensed version Resin Pro is available for enterprise and production environments. Resin supports the Java EE standard as well as a mod_php/PHP like engine known as Quercus. Resin is also one of the oldest application and web servers as it predates Apache Tomcat as it was released in 1999.

Resin Pro includes features such as built-in caching and features such as clustering support, advanced administration, and more but the Resin Open Source version is used without these features so will not be covered here,

In terms of the app server,  it is Java EE Web Profile certified, with support for Java CDI and Transaction support. The Web Server aspect includes support for Static files/JSP/Servlet/JSF, URL rewriting, Proxy caching, Gzip compression, SSL, Virtual Hosts, Comet/Server push, and WebSockets.

Blazix

Blazix is a fully featured Java application server and web server (serving HTML files and images in addition to the standard application server workload.) Currently Blazix provides Servlet 2.3, JSP 1.2, EJB 1.1 and JMS 1.0.2. It also implements HTTP/1.1 and is written entirely in Java, and can be used cross-platform. It can be used as a full web server all by itself, especially in high volume traffic.

Some of the features included are support for no-single-point-of-failure clustering for load balancing and failover, live EJB and Web archive deployments and updates, Secure Socket Layer web services, transaction management, security. Blazix provides all these features in a 2-megabyte download which is good if you’re looking for something small.

Hopefully you found this guide to Application Servers useful, let us know what your favourite Java and JavaEE Application Server.
Written by Alex Marshall

If you found this post interesting, follow and support us.
Suggest for you:


Friday, August 12, 2016

The top 11 Free IDE for Java Coding, Development & Programming


At IDR Solutions we spend a lot of our time working with Java as our Java PDF Library, Java Image Library and PDF to HTML5 Converter are written in Java.

Our developers spend alot of time buried in java code and we use a a variety of different IDE’s (Intergrated Development Environment) to develop Java Code, so I thought it would be good to compile a list of the best free IDEs out there for Java Programmers, developers and coders.

In this article I will be taking a look at 11 different IDE’s, some are used by us at IDR Solutions and others that should be worth considering if you like to experiment with alternative Java IDEs. Everyone has different requirements and we feel one of the strengths of the Java world is the choice available.

These IDEs offer a variety of features, like: building Java applications, TestNG, debugging, code inspections, code assistance, JUNIT testing, multiple refactoring, visual GUI builder and code editor, Java, Maven build tools, ant, do data modelling and build queries, and more.

NetBeans

NetBeans is an open source Integrated Development Environment written in Java and is one of IDR Solutions favourite IDE’s for Java Coding.

The NetBeans IDE supports development of all Java application types (Java SE, JavaFX, Java ME, web, EJB and mobile applications) standard out of the box. NetBeans is modular in design meaning it can be extended by third party developers who can create plugins for NetBeans to enhance functionality (Our PDF Plugin for NetBeans is a good example).

The NetBeans IDE is can be used to develop in Java, but also supports other languages, in particular PHP, C/C++, and HTML5.

NetBeans features are an Ant-based project system, support for Maven, refactoring, version control (supporting CVS, Subversion, Git, Mercurial and Clearcase) and is also released under a dual license consisting of the Common Development and Distribution License (CDDL) v1.0 and the GNU General Public License (GPL) v2.

NetBeans is cross-platform and runs on Microsoft Windows, Mac OS X, Linux, Solaris and other platforms supporting a compatible JVM.

NetBeans can also be used for working with Cloud applications, this useful guide covers how to use the NetBeans IDE with the Google App Engine.

Eclipse

Eclipse is another free Java IDE for developers and programmers and it is mostly written in Java. Eclipse lets you create various cross platform Java applications for use on mobile, web, desktop and enterprise domains.

Its main features include a Windows Builder, integration with Maven, Mylyn, XML editor, Git client, CVS client, PyDev,  and it contains a base workspace with an extensible plug-in system for customizing the IDE to suit your needs.  Through plugins you can develop applications in other programming languages some of which include , C, C++, JavaScript,, Perl, PHP, Prolog, Python, R, Ruby (including Ruby on Rails framework), to name just a few.

Eclipse is available under a Eclipse Public License and is available on Windows, Mac OS X and Linux.

IntelliJ IDEA Community Edition

IntelliJ IDEA Community Edition is a free Java IDE (Integrated Development Environment) mainly used for Android app development, Scala, Groovy, Java SE and Java programming. It is lightweight in design and comes with useful features like JUnit testing, TestNG, debugging, code inspections, code completion, support for multiple refactoring, Maven build tools, ant, visual GUI builder and code editor for XML and Java.

There are some features missing from the Community Edition but if you require more you can buy a license to unlock all the features.

IntelliJ Idea Community Edition is is released under a Apache 2 License.

Android Studio

Android Studio from Google is mainly designed for developing on the Android Platform however it is capable of running and editing some Java code.

Originally it was built on the IntelliJ IDEA Community Edition, created by JetBrains and features a Flexible Gradle-based build system, build variants and multiple APK generation, Expanded template support for Google Services and various device types, Rich layout editor with support for theme editing and Lint tools to catch performance, usability, version compatibility, and other problems.

It also comes with ProGuard and app-signing capabilities and also features Built-in support for Google Cloud Platform and projects can be configured to use Java Development Kit (JDK) 6 or JDK 7.

Android Studio is freely available under the Apache License 2.0 and it is available for download on Windows, Mac OS X and Linux and replaced Eclipse as Google’s primary IDE for native Android application development.

Enide Studio 2014

Enide Studio 2014 initially (version 0.11-preview) was released as stand-alone product for all Operating systems. However later changes saw it develop in a Tool Suite for Node.js, JavaScript and Java Development which is available from the Eclipse plugin store and from the main website.

Enide Studio 2014 Plugin includes:
– Nodeclipse 0.17, – Chrome Development Tools, AngularJS for Eclipse, TernIDE, Eclipse WTP WebResources, TCF Terminals, MarkDown (*.md) Editor, – GitHub Flavored Markdown (GFM) Viewer, various themes, Nodeclipse EditBox, RestClient Tool.  StartExplorer, Git Add-on, Maven, Gradle integration, Minimalist Jade Editor and more..

BlueJ

BlueJ is an integrated development environment (IDE) for the Java programming language, It has been mainly developed for educational purposes, but also suitable for those who wish to do small-scale software development. It runs with the help of a JDK(Java Development Kit).

BlueJ is mainly developed for the teaching of object-oriented programming, and its design differs from other development environments as a result.

The main screen graphically shows the class structure of an application under development and objects can be interactively created and tested. This interaction facility, combined with a clean, simple user interface, allows easy experimentation with objects under development and this allows beginners to get started more quickly, and without being overwhelmed.

Newbie users can check on values and call methods on them, pass them as parameters and more and Java expressions  can be invoked without compiling meaning BlueJ is a powerful graphical shell/REPL for Java.

The BlueJ project is free and an open source software, and licensed under GNU GPL with the classpath exception and there are popular textbooks designed for teaching introductory university/college courses with BlueJ, and a site full of teaching resources and is also can run on Windows, Mac OS X, Linux and other platforms which run Java. It can also run without installation from a USB stick.

jEdit

jEdit is a text editor with hundreds (counting the time developing plugins) of person-years of development behind it. Most people argue where jEdit beats many expensive development tools for features and ease of use is that the jEdit core, comes with  a built-in macro language; an extensible plugin architecture. Hundreds of macros and plugins available.

There is also an auto indent function, and syntax highlighting for more than 200 languages, support for a large number of character encodings including UTF8 and Unicode, folding for selectively hiding regions of text, Word wrap, and more.

It can also  be used for source code editing, search and replacing, file management and jEdit’s is written in Java, so it runs on Mac OS X, OS/2, Unix, VMS and Windows, and it is released as free software with full source code, provided under the terms of the GPL 2.0.

jGRASP

jGRASP is a lightweight IDE primarily created for automatic generation of software visualizations to improve the comprehensibility of software. It is capable of producing static visualizations of source code structure and visualizations of data structures at runtime and jGRASP produces Control Structure Diagrams (CSDs) for Java, C, C++, Objective-C, Python, Ada, and VHDL; Complexity Profile Graphs (CPGs) for Java and Ada; UML class diagrams for Java; and has dynamic object viewers and a viewer canvas that work in conjunction with an integrated debugger and workbench for Java.

The viewers have a built in feature that allows it to identify data structures which allows it to recognize objects that represent traditional data structures such as stacks, queues, linked lists, binary trees, and hash tables and display this appropriately.

jGRASP is implemented in Java and was developed by the Department of Computer Science and Software Engineering in the Samuel Ginn College of Engineering at Auburn University.

It can run on any platform that can run a Java Virtual Machine (Java version 1.5 or higher). At present the jGRASP web site offers downloads for Windows, Mac OS, and as a generic ZIP file suitable for Linux and other systems.

JSource

JSource is a free Java IDE and is a good option for Java developers and programmers.

It is useful for creating cross-platform java applications for various domains and is extremely lightweight. You can use JSource to run, compile, edit and create java files. Its main features are syntax highlighting for multiple languages and Java Swing components. In version  2.0 of JSource you can use jEdit syntax package and can incorporate other open source Java tools used for rapid development. These tools have been modified to work with the core JSource structure.

JSource is available under a GNU General Public License version 2.0 (GPLv2).

JDeveloper

JDeveloper is a IDE supplied by the Oracle Corporation and released as freeware. It offers various features for development in Java, XML, SQL and PL/SQL, HTML, JavaScript, BPEL and PHP. JDeveloper can be used for coding, debugging, optimization and profiling to deploying. JDeveloper integrates with the Oracle Application Development Framework (Oracle ADF) – an end-to-end Java EE-based framework that further simplifies application development.

JDeveloper comes in 3 flavors which include the Java Edition, J2EE edition and Studio Edition which comes with a whole different set of features.

In terms of the Java Edition what is included out of the box is Java SE 6 Support, Code Editor, Code Navigation, Refactoring, compatibility with Swing,Unit Testing, Version Control, Auditing & Metrics,Debugging, Profiling,Ant Support, Maven Support,XML Support and Open API & Extensions.

The same IDE platform also serves as the basis of another Oracle product, SQL Developer.

DrJava

DrJava is an extremely lightweight development environment that can be used for writing Java programs. It has been designed primarily for students, and provides an intuitive interface and the ability to interactively evaluate Java code.

Its main feature are for it to be used as a unit testing tool, a source level debugger, an interactive pane for evaluating text of the program, intelligent program editor and can be used for more depending on your requirements.
It is available for free under the BSD License, and it is under active development by the JavaPLT group at Rice University.

Hopefully you’ve found this guide on the best IDE’s for Programming, developing and coding Java useful.
Written by Alex Marshall

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Java Developer Course

Java Programming For Beginners

Complete Java For Selenium WebDriver And Test Automation

The Complete Android & Java Course - Build 21 Android Apps

Thursday, August 11, 2016

Build a Real-Time Chat Application With Modulus and Spring Boot_part 2 (end)

3.3. View
In the view part, we have only two pages. One of them is the login page, to get the nickname of the user, and the second one is the main chat page to send messages to chat users.

As you can see in the controller section above, they are rendered by using two endpoints, /login and /chat. To create interactive pages, we will use some third-party JavaScript libraries. We will use them from CDN pages. You can see the login page below:
  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4.     <meta charset="UTF-8"/>
  5.     <title></title>
  6.     <script src="//code.jquery.com/jquery-1.11.1.js"></script>
  7.     <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  8.     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  9.     <script>
  10.         $(function(){
  11.             if ($.cookie("realtime-chat-nickname")) {
  12.                 window.location = "/chat"
  13.             } else {
  14.                 $("#frm-login").submit(function(event) {
  15.                     event.preventDefault();
  16.                     if ($("#nickname").val() !== '') {
  17.                         $.cookie("realtime-chat-nickname", $("#nickname").val());
  18.                         window.location = "/chat";
  19.                     }
  20.                 })
  21.             }
  22.         })
  23.     </script>
  24.     <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
  25.     <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>
  26. </head>
  27. <body>
  28. <div class="container" style="padding-top: 50px">
  29.     <div class="row">
  30.         <div class="col-md-4 col-md-offset-4">
  31.             <div class="login-panel panel panel-default">
  32.                 <div class="panel-heading">
  33.                     <h3 class="panel-title">Choose a nickname to enter chat</h3>
  34.                 </div>
  35.                 <div class="panel-body">
  36.                     <form role="form" id="frm-login">
  37.                         <fieldset>
  38.                             <div class="form-group">
  39.                                 <input class="form-control" placeholder="Enter Nickname" name="nickname" id="nickname" type="text" autofocus="" required=""/>
  40.                             </div>
  41.                             <button type="submit" class="btn btn-lg btn-success btn-block">Enter Chat</button>
  42.                         </fieldset>
  43.                     </form>
  44.                 </div>
  45.             </div>
  46.         </div>
  47.     </div>
  48. </div>
  49. </body>
  50. </html>
On the login page, we have a sample nickname text box. When you click Enter Chat, your nickname will be saved to a cookie. This nickname will be used to set the chat message author field. When you click Enter Chat, the chat page will be opened. If you are already logged in and go to the login page, you will be redirected to the chat page.

Here's the chat page:
  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4.     <meta charset="UTF-8"/>
  5.     <title></title>
  6.     <script src="//code.jquery.com/jquery-1.11.1.js"></script>
  7.     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  8.     <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  9.     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-timeago/1.4.0/jquery.timeago.min.js"></script>
  10.     <script src="//cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.0.0/sockjs.min.js"></script>
  11.     <script src="//cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script> 
  12.     <script>
  13.         var stompClient = null; 
  14.         function connect() {
  15.             var socket = new SockJS('/newMessage');
  16.             stompClient = Stomp.over(socket);
  17.             stompClient.connect({}, function(frame) {
  18.                 stompClient.subscribe('/topic/newMessage', function(message){
  19.                     refreshMessages(JSON.parse(JSON.parse(message.body).content));
  20.                 });
  21.             });
  22.         } 
  23.         function disconnect() {
  24.             if (stompClient != null) {
  25.                 stompClient.disconnect();
  26.             }
  27.         } 
  28.         function refreshMessages(messages) {
  29.             $(".media-list").html("");
  30.             $.each(messages.reverse(), function(i, message) {
  31.                 $(".media-list").append('<li class="media"><div class="media-body"><div class="media"><div class="media-body">'
  32.                 + message.text + '<br/><small class="text-muted">' + message.author + ' | ' + new Date(message.createDate) + '</small><hr/></div></div></div></li>');
  33.             });
  34.         } 
  35.         $(function(){ 
  36.             if (typeof $.cookie("realtime-chat-nickname") === 'undefined') {
  37.                 window.location = "/login"
  38.             } else {
  39.                 connect();
  40.                 $.get("/messages", function (messages) {
  41.                     refreshMessages(messages)
  42.                 }); 
  43.                 $("#sendMessage").on("click", function() {
  44.                     sendMessage()
  45.                 }); 
  46.                 $('#messageText').keyup(function(e){
  47.                     if(e.keyCode == 13)
  48.                     {
  49.                         sendMessage();
  50.                     }
  51.                 });
  52.             } 
  53.             function sendMessage() {
  54.                 $container = $('.media-list');
  55.                 $container[0].scrollTop = $container[0].scrollHeight;
  56.                 var message = $("#messageText").val();
  57.                 var author = $.cookie("realtime-chat-nickname");
  58.  
  59.                 stompClient.send("/app/newMessage", {}, JSON.stringify({ 'text': message, 'author': author}));
  60.  
  61.                 $("#messageText").val("")
  62.                 $container.animate({ scrollTop: $container[0].scrollHeight }, "slow"); 
  63.             }
  64.         })
  65.     </script>
  66.     <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
  67.     <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>
  68.     <style type="text/css">
  69.         .fixed-panel {
  70.         min-height: 500px;
  71.         max-height: 500px;
  72.         }
  73.         .media-list {
  74.         overflow: auto;
  75.         }
  76.     </style>
  77. </head>
  78. <body>
  79. <div class="container">
  80.     <div class="row " style="padding-top:40px;">
  81.         <h3 class="text-center">Realtime Chat Application with Spring Boot, Websockets, and MongoDB </h3>
  82.         <br/><br/>
  83.  
  84.         <div class="col-md-12">
  85.             <div class="panel panel-info">
  86.                 <div class="panel-heading">
  87.                     <strong><span class="glyphicon glyphicon-list"></span> Chat History</strong>
  88.                 </div>
  89.                 <div class="panel-body fixed-panel">
  90.                     <ul class="media-list">
  91.                     </ul>
  92.                 </div>
  93.                 <div class="panel-footer">
  94.                     <div class="input-group">
  95.                         <input type="text" class="form-control" placeholder="Enter Message" id="messageText" autofocus=""/>
  96.                                     <span class="input-group-btn">
  97.                                         <button class="btn btn-info" type="button" id="sendMessage">SEND <span class="glyphicon glyphicon-send"></span></button>
  98.                                     </span>
  99.                     </div>
  100.                 </div>
  101.             </div>
  102.         </div>
  103.     </div>
  104. </div>
  105. </body>
  106. </html>
This page is for simply viewing and sending messages. Messages are delivered to this page via WebSockets. On this page you can see sockjs and stompjs. Those are for handling notifications. Whenever a new message comes, the latest messages area is repopulated.

By the way, when you first open the chat page, the latest messages will be retrieved in the messages area. As you can see on the JavaScript side, our message channel is newMessage. So, we are listening to this channel, and when you click the Send button, the message in the text box will be sent to the endpoint and that message will be broadcast to the connected clients after successful storage.

As you can see, the software architecture here is very simple and easy to develop. We have production-ready code, and let's deploy it to Modulus.

Modulus is one of the best PaaS for deploying, scaling and monitoring your application in the language of your choice.

4. Deployment 

4.1. Prerequisites
Before deploying the application, let's create a database by using the Modulus admin panel. You need a Modulus account for dba creation and application deployment, so please create an account if you don't have one.

Go to the Modulus dashboard and create a database:


On the database creation screen please provide a database name, select the MongoDB version (I have used 2.6.3, so it will be better if you choose 2.6.3 too), and finally define a user to apply database read/write operations.

You can get a MongoDB URL after successfully creating the database. We will use the MongoDB URL in the environment variables to be used by the Spring Boot application.

To set the environment variables for MongoDB, you need to have an application. Go to Dashboard and click Projects. On this page, click Create New Project.

To continue with configuring the environment variables, please go to Dashboard and click Projects. Select your project, and click Administration. Scroll down the page, and set environment variables with the key SPRING_DATA_MONGODB_URI and value of your database URI:


When you deploy your application, Spring will use that environment variable value. We have done with the requirements, and let's continue with the deployment part.

4.2. Deployment With CLI
In order to deploy the project, run a gradle build task:
  1. gradle build
This task will generate a war file called ROOT.war. Copy this file to a fresh folder and install modulus CLI if you haven't.
  1. npm install -g modulus
Log in to the system;
  1. modulus login
Now execute the following command to deploy ROOT.war to Modulus.
  1. modulus deploy
This will deploy the war file and you can tail project logs to see the status of your deployment by executing the following command:
  1. modulus project logs tail
That's all with the deployment!

5. Conclusion

The main purpose of this tutorial is to show you how to create a real-time chat application with Spring Boot, WebSockets, and MongoDB.

In order to run the project in production, Modulus is used as a PaaS provider. Modulus has very simple steps for deployment, and it also has an internal database (MongoDB) for our projects. Beside this, you can use very helpful tools in the Modulus dashboard like Logs, Notifications, Auto-Scaling, Db Administration, and more.
Written by Hüseyin Babal

If you found this post interesting, follow and support us.
Suggest for you:

Java Programming For Beginners

Complete Java For Selenium WebDriver And Test Automation

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

Scalable programming with Scala and Spark

Monday, August 8, 2016

Build a Real-Time Chat Application With Modulus and Spring Boot_part 1

In this tutoral, we will use Spring Boot for the web development environment, Websockets for real-time communication, Tomcat for the Java application container, Gradle for building and managing the dependencies, Thymeleaf for template rendering, MongoDB for data storage, and finally there will be no XML for bean configurations. Just to make you inspired, at the end of this article, you will see a fully working application like the one shown below.


1. Scenario
  1. Doe opens the chat page to communicate with his friends.
  2. He is prompted to choose a nickname.
  3. He enters the chat page and sends a message. The message is sent to the Spring MVC endpoint to be saved to the database and broadcast.
  4. The specified endpoint handles the message and broadcasts that message to all clients connected to the chat system.
2. Build Dependencies and Gradle Configuration

Before proceeding with the internal structure of the project, let me explain which libraries we will use for the project features listed above, and manage them by using Gradle. When you clone the project from GitHub, you will see a file called build.gradle in the project root directory as below.
  1. buildscript {
  2.     repositories {
  3.         mavenCentral()
  4.     }
  5.     dependencies {
  6.         classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.4.RELEASE")
  7.     }
  8. apply plugin: 'java'
  9. apply plugin: 'eclipse'
  10. apply plugin: 'idea'
  11. apply plugin: 'spring-boot'
  12. apply plugin: 'war' 
  13. jar {
  14.     baseName = 'realtime-chat'
  15.     version =  '0.1.0'
  16. war {
  17.     baseName = 'ROOT'
  18. sourceCompatibility = 1.7
  19. targetCompatibility = 1.7 
  20. repositories {
  21.     mavenCentral()
  22. sourceCompatibility = 1.7
  23. targetCompatibility = 1.7
  24. dependencies {
  25.     providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
  26.     compile("org.springframework.boot:spring-boot-starter-web")
  27.     compile("org.springframework.boot:spring-boot-starter-thymeleaf")
  28.     compile("org.springframework.boot:spring-boot-starter-data-mongodb")
  29.     compile("org.springframework.boot:spring-boot-starter-websocket")
  30.     compile("org.springframework:spring-messaging")
  31.     testCompile("junit:junit")
  32. }

  33. task wrapper(type: Wrapper) {
  34.     gradleVersion = '2.3'
  35. }
I will not dive into the Gradle internals, but let me explain the parts that we need for our project. Spring Boot is built mainly for developing standalone applications in jar format. In our project, we will generate a war project instead of jar. That is because Modulus needs a war file to deploy the project automatically to its cloud.

In order to generate a war file, we have used apply plugin: 'war'. Modulus also expects the war name to be ROOT.war by default, and that is why we have used:
  1. war {
  2.     baseName: 'ROOT.war'
  3. }
When you run the Gradle build task, it will generate a war file to deploy to the Tomcat container. And finally, as you can guess, the dependencies section is for third-party libraries for specific actions.

That is all for the project dependencies section, and you can refer to the Gradle user guide for more about Gradle.

3. Software Design

If you want to develop a good application, it is best practice to define your project structure in small pieces. You can see the pieces of the entire architecture of our application.

3.1. Model

We are developing a chat application, so we can say that we have a ChatMessageModel model (i.e. domain object). While we are saving or viewing the chat message detail, we can cast the chat object from or to this ChatMessageModel model. Also, we can use the User model for chat users, but to make the application simpler, we will use just nickname as text. The ChatMessageModel model has the following fields: textauthor, and createDate. The class representation of this model is as follows:
  1. package realtime.domain; 
  2. import org.springframework.data.annotation.Id; 
  3. import java.util.Date; 
  4. /**
  5.  * @author huseyinbabal
  6.  */
  7. public class ChatMessageModel { 
  8.     @Id
  9.     private String id; 
  10.     private String text;
  11.     private String author;
  12.     private Date createDate; 
  13.     public ChatMessageModel() {
  14.     } 
  15.     public ChatMessageModel(String text, String author, Date createDate) {
  16.         this.text = text;
  17.         this.author = author;
  18.         this.createDate = createDate;
  19.     }
  20.     public String getText() {
  21.         return text;
  22.     } 
  23.     public void setText(String text) {
  24.         this.text = text;
  25.     } 
  26.     public String getAuthor() {
  27.         return author;
  28.     } 
  29.     public void setAuthor(String author) {
  30.         this.author = author;
  31.     } 
  32.     public Date getCreateDate() {
  33.         return createDate;
  34.     } 
  35.     public void setCreateDate(Date createDate) {
  36.         this.createDate = createDate;
  37.     }
  38.     @Override
  39.     public String toString() {
  40.         return "{" +
  41.                 "\"id\":\"" + id + '\"' +
  42.                 ",\"text\":\"" + text + '\"' +
  43.                 ",\"author\":\"" + author + '\"' +
  44.                 ",\"createDate\":\"" + createDate + "\"" +
  45.                 '}';
  46.     }
  47. }
This domain object helps us to represent the chat message as JSON when needed. Our model is OK, so let's continue with the controllers.

3.2. Controller

The controller is the behavior of your application. This means you need to keep your controller simple and capable of easy interaction with domain models and other services. We are expecting our controllers to handle:
  1. Chat message save requests
  2. Listing the latest chat messages
  3. Serving the chat application page
  4. Serving the login page
  5. Broadcasting chat messages to clients
Here you can see the overall endpoints:
  1. package realtime.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.domain.PageRequest;
  4. import org.springframework.data.domain.Sort;
  5. import org.springframework.http.HttpEntity;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.messaging.handler.annotation.MessageMapping;
  9. import org.springframework.messaging.handler.annotation.SendTo;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import realtime.domain.ChatMessageModel;
  14. import realtime.message.ChatMessage;
  15. import realtime.repository.ChatMessageRepository; 
  16. import java.util.Date;
  17. import java.util.List; 
  18. /**
  19.  * @author huseyinbabal
  20.  */ 
  21. @Controller
  22. public class ChatMessageController {
  23.     @Autowired
  24.     private ChatMessageRepository chatMessageRepository; 
  25.     @RequestMapping("/login")
  26.     public String login() {
  27.         return "login";
  28.     } 
  29.     @RequestMapping("/chat")
  30.     public String chat() {
  31.         return "chat";
  32.     } 
  33.     @RequestMapping(value = "/messages", method = RequestMethod.POST)
  34.     @MessageMapping("/newMessage")
  35.     @SendTo("/topic/newMessage")
  36.     public ChatMessage save(ChatMessageModel chatMessageModel) {
  37.         ChatMessageModel chatMessage = new ChatMessageModel(chatMessageModel.getText(), chatMessageModel.getAuthor(), new Date());
  38.         ChatMessageModel message = chatMessageRepository.save(chatMessage);
  39.         List<ChatMessageModel> chatMessageModelList = chatMessageRepository.findAll(new PageRequest(0, 5, Sort.Direction.DESC, "createDate")).getContent();
  40.         return new ChatMessage(chatMessageModelList.toString());
  41.     } 
  42.     @RequestMapping(value = "/messages", method = RequestMethod.GET)
  43.     public HttpEntity list() {
  44.         List<ChatMessageModel> chatMessageModelList = chatMessageRepository.findAll(new PageRequest(0, 5, Sort.Direction.DESC, "createDate")).getContent();
  45.         return new ResponseEntity(chatMessageModelList, HttpStatus.OK);
  46.     }
  47. }
The first and second endpoints are just for serving the login and main chat page. The third action is for handling new chat message storage and broadcasting. After the message is stored, it will be notified to clients through the /topic/message channel. To store message data to MongoDB, we will use a MongoDB repository.

As you can see, there are two types of endpoint /messages: GET and POST. When you make a POST request to endpoint /messages with proper message payload, it will be automatically cast to the ChatMessageModel class, and the message will be saved to MongoDB. After successful saving, it will be automatically pushed to the clients. But, how? In that action, there is an annotation @SendTo("/topic/newMessage"). This will send the content returned from the function to the clients. And the returned content is like below:
  1. ...
  2. return new ChatMessage(chatMessageModelList.toString());
  3. ...
  4. This is the latest message from the database:


The above message will be converted to a format for WebSocket communication. This channel message will be handled on the client side with a third-party JavaScript library, and it will be handled in the following sections. 

For message db operations, spring-boot-starter-data-mongodb is used. This library helps us for repository operations, and to create a repository object for MongoDB is very simple. You can see the example ChatMessageRepository below:
  1. package realtime.repository; 
  2. import org.springframework.data.mongodb.repository.MongoRepository;
  3. import realtime.domain.ChatMessageModel; 
  4. import java.util.List; 
  5. /**
  6.  * @author huseyinbabal
  7.  */
  8. public interface ChatMessageRepository extends MongoRepository<ChatMessageModel, String> {
  9.     List<ChatMessageModel> findAllByOrderByCreateDateAsc();
  10. }
If you create an interface and extend MongoRepository<?, String>, you will be able to automatically use CRUD operations like find()findAll()save(), etc. 

As you can see, MongoRepository expects a domain object. We have already defined this model in the Model section of the tutorial. In this repository, we have defined a custom function called findAllByOrderByCreateDateAsc()

If you have ever used JPA before you can understand this easily, but let me explain this briefly. If you define a function name in an interface that extends MongoRepository, this function name will be parsed to a query on the back end by Spring automatically. It will be something like:
  1. SELECT * FROM ChatMessageModel WHERE 1 ORDER BY createDate ASC
In ChatMessageController, we used this function, and also we have used the default functions of the MongoRepository:
  1. chatMessageRepository.findAll(new PageRequest(0, 5, Sort.Direction.DESC, "createDate")).getContent()
findAll is used a parameter for sorting and pagination. You can have a look at the guide on the Spring website for more details about Spring JPA.
Written by Hüseyin Babal

If you found this post interesting, follow and support us.
Suggest for you: