Tag Archives: Java

Design and discussion of an idea for Saas Application

In this post of building an application, we discussed what is a saas application and how it can be designed and built. There are possibly a few ideas that I had in my mind or that I came across on the internet. So, I will discuss an idea for the saas application here.

One of the ideas that I have chosen, is to build a web application for small businesses so they can monitor their social media progress. A report that can give details about how the business is performing. From the outside, the whole idea seems very simple – build a report. But there are a lot of complexities involved here if we will be connecting to multiple social media.

We will be discussing the design of this idea and see if we can make progress to build a final design.

Discussion of the idea for the saas application –

  1. A small business can subscribe to this application on two models. One model will be free and others will be paid.
  2. The free model will offer a basic report about the business’ performance in social media.
  3. The paid model will offer a detailed report along with an action plan to improve marketing ratings.
  4. Part of this architecture and development, first we will build a free model only. Depending on how long it is going to take me to build the entire product, we will plan the paid model.
  5. We will use Twitter, Instagram, and Facebook as the three main social media to connect to. All these three social services offer their APIs for developers.

A User flow

  1. If a small business is looking for a marketing tool as part of its social media strategy, they can subscribe to the application that I will be building herewith.
  2. A sign-up page. A user coming across this web application will have to sign up for an account to use the tool.
  3. Sign up will be unique for a business. At least for an alpha version of this tool, only a single user from a business can sign up/login. Maybe next versions or paid versions will give more flexibility to sign up or log in for multiple users from the same business.
    1. A sign-up page will ask for a business name, person’s name, contact number, email address.
    2. A person who is signing up will receive an email for confirmation with login details.
    3. Alpha version will have basic security to login and logout.
  4. Once the business has signed up, that person will access the web application to login.
  5. Alpha version will not deal with security policies at least.
  6. A user once logged into the application will see a dashboard to access the reports.
  7. There will be three reports available for the free subscription model and all three reports will give details about how a business is performing on social media. These three reports will correspond to Facebook, Twitter, and Instagram.
  8. There will be a logout button available for the user to logout. Logout will clear all the session cookies.
  9. Each report will fetch the live data from the respective social media services. Depending on the restrictions for APIs provided by Facebook, Twitter, and Instagram, fetching of new data will be developed.
  10. The report will also show a graphical representation of performance.

How will this help?

What’s the value of this application for small businesses? Of course, this is the basic question. I had to think about the answer if I had to design this application. That is going to be a unique selling point (USP) of this app.

  1. The tool will provide fact-based data about how the business is doing.
  2. It will provide strategies to improve social media presence.
  3. In turn, this will give an idea to small businesses to market themselves and improve customer satisfaction.

Technology Stack

we will be using Java, Spring Boot, MySQL, Github, and AngularJS.

References

The idea for this saas application was borrowed from here.

 

Top 5 Java Coding Practices

In this short post, we will discuss the top 5 Java coding practices. One reason I like to revisit best practices is to remind myself if I am following them or not. Another reason to verify if anything has changed with language. Even if I visit the best practices after a few years, it gives me a refreshing perspective to understand where I am and how I am improving or not. Everybody has their own way, but programming is a skill and over time, you can continue to improve it just like any other skill. So here we go with the top 5 Java best coding practices.

   1. Methods Naming Convention – 

The name of the method should reveal the intention of the method. Example calculateHeight but if you name your method height , it is just bad because that can be more of a variable name. A method should also do a single job. If it is doing more than one job, you can always refactor the code.

   2. Use a consistent style –

The syntax style you use while writing Java code should be consistent across any code you write.

   3.  Use logging –

There are a number of logging APIs available, but the most popular log4j is available as a blanket for logging APIs. While writing an enterprise application, it is of utmost importance to log. From a code review perspective, it is helpful to have logged in your code. Another advantage of logging is in production while resolving a lot of issues, logging is the only way to debug the code in a short amount of time.

    4.  Variable encapsulation –

Most variables when declared should be private . This ensures safety so that accidental usage of this variable does not change the state of it. Adding getter and setter for such variables is standard practice.

    5.   Use comments frequently –

As a programmer, your responsibility begins when you start coding and good code is easy to read with well-documented comments. If a new programmer or developer joins the team, he should be able to understand the code without much context. Also for this reason specifically, read and revisit open source code often.

Conclusion

In this post, I discussed top 5 Java coding practices. What are your favorite tips for Java? If you enjoyed this post, subscribe to my blog here.

References

 

How to implement a chatbot in Java

So we are back on our discussion about chatbots. I will not talk about the basics of chatbots that I covered here. I will directly start showing how to implement a chatbot in Java. We are going to use AIML (Artificial Intelligence Markup Language) library for this implementation. This library is opensource and provided by google.

chatbot in Java

A maven project

As a first step, let’s create a maven project in Eclipse with groupId com.betterjavacode and artifactId as chatbot. Once the project is created, we can add ab.jar to project by adding the respective dependency in maven pom.xml  like below:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.betterjavacode</groupId>
  <artifactId>chatbot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>JavaChatbot</name>
  
  <dependencies>
    <dependency>
        <artifactId>com.google</artifactId>
        <groupId>Ab</groupId>
        <version>0.0.4.3</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/Ab.jar</systemPath>
    </dependency>
</dependencies>
</project>

Google library for AIML provides default AI rules to use to implement chatbot. We will add these rules in resources directory of our project. Copy bots folder from program-ab directory into resources folder.

Chatbot Program

Now we will write the chatbot program which will be part of main method. In simple terms, once we invoke this program through main method, it will be in an infinite loop. An input command will wait for user input and then based on our aiml library chatbot will answer to what an user had input.


try {
            String resourcesPath = getResourcesPath();
            System.out.println(resourcesPath);
            MagicBooleans.trace_mode = TRACE_MODE;
            Bot bot = new Bot("Mr. Chatter", resourcesPath);
            Chat chatSession = new Chat(bot);
            bot.brain.nodeStats();
            String textLine = "";
            while (true) {
                System.out.println("human: ");
                textLine = IOUtils.readInputTextLine();
                if ((textLine == null) || (textLine.length() < 1))
                    textLine = MagicStrings.null_input;
                if (textLine.equals("q")) {
                    System.exit(0);
                } else if (textLine.equals("wq")) {
                    bot.writeQuit();
                    System.exit(0);
                } else {
                    String request = textLine;
                    if (MagicBooleans.trace_mode)
                        System.out.println("STATE=" + request + ":THAT=" + ((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" + chatSession.predicates.get("topic"));
                    String response = chatSession.multisentenceRespond(request);
                    while (response.contains("<"))
                        response = response.replace("<", "<"); while (response.contains(">")) response = response.replace(">", ">");
                    System.out.println("Robot : " + response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

Now if we run this program, it will show us input to ask a question to the chatbot Mr. Chatter.

Conclusion

In this article, we showed how to add a chatbot in Java. Similarly, we can enhance this program by adding custom patterns that the chatbot can respond to.

References

Chatbot Implementation

Chatbots and more

What are chatbots? This is not the regular programming post, but more of a discussion post and where we are heading with our technology. Alexa, Google Home, Cortona, and the number of personal assistants are available at our perusal. With these kinds of products, we are slowly evolving into artificial intelligence-driven technology. A lot of manual labor jobs might be in danger in the near future. Politics aside, I am more interested to understand this topic from technology and humane perspective. While we still struggle with a lot of other ethical issues with existing technology, AI will only create social conundrums.

What I want to discuss in this post, is more about chatbots. You can think of this as a scribbling post. I am just bringing some ideas forefront to build a chatbot using java.

What are chatbots?

Chatbots are a crude version of personal assistants. Personal assistants help you in many ways, in-process saving you time, providing you leisure. The simplest version of these chatbots is those that answer your questions like “What’s the weather like today?”, a chatbot will connect to a weather website to find out today’s weather and then answer you accordingly. Similarly, on an eCommerce site, I can ask a question by typing “Where can I find this book?”, the chatbot will answer “In literature and short stories section”. A chatbot can also help build customer support, taking away the traditional customer support people. In a more advanced version, the same chatbots can build a library based on your likings, dislikings, answers, and provide more options for lifestyle.

Wikipedia definition says

A chatbot is a computer program that conducts a conversation via auditory or textual methods.

Chatbots are part of Artificial intelligence that has been popularized these days.

Design of chatbots

In this article, we will not be showing any code for chatbots, but we will be building chatbots in the next post. This is a post where we bring the idea of a chatbot into the design. As we discussed the definition of a chatbot, we will be building an agent that will chat with us in a natural language that we use for daily communication.

Me: “Hi Mr. Chatbot, how are you today?”

Mr. Chatbot: “I am fine, Mr. Mali. Thank You”

Me: “What’s the day today?”

Mr. Chatbot: “It’s Wednesday today.”

This is an example of a conversation about how a chatbot would answer. We will build a database that will have natural language processing ability to find out what question has been asked and based on that answer the question as accurately as possible. This chatbot is an experimental build-up.

Does it mean it can falter? Glad you ask that it definitely means it can answer erratic. But it’s ok in our experimentation world, even Google home had his off days.

We will need a chat engine and we will be using plain English to type our messages. We will use AIML (Artificial Intelligence Markup Language) to build this chatbot.

In conclusion, I would provide the implementation of this chatbot in the next few posts. We will have more discussion about chatbots in future articles. If you enjoyed this post, subscribe to my blog here.

 

References

  1. AIML
  2. Chatbot

 

How to deploy Spring Boot Application on docker – Part IX

In this post, I show how to deploy a spring application in a docker container.

What is docker

Docker is a container platform delivered by a company named “Docker Inc.” It can be used by developers, operators, and enterprise users to deliver and use packaged software. Docker has something called a container. A container can be a virtual machine (VM) in lay man’s terms, but still a little different from VM. Container contains packaged software delivered in a way that it can be run isolated on a shared operating system. As per official definition – Unlike VMs, the container does not bundle a full operating system – only libraries and settings required to make the software work are needed.

In this demo, we will use our spring boot application built throughout from Part I to Part VIII.

I am using Windows Platform Toolbox for docker to build my docker containers. 

We will build a container with MySQL database deployed and another container where we will deploy spring boot application. This spring boot application container will connect to MySQL database container at runtime. The process is a little complicated, but once you get your hands on the docker container, it becomes very straight forward to understand. Also for this post, I will not explain anything about spring boot application. You should review all the previous posts I have written explaining how to build and deploy spring boot application on an embedded tomcat.

Once we know about docker, it is easy to deploy an application in docker.

Building a docker container with MySQL

Few things to remember

  1. Make sure your spring boot application is working with MySQL database before you build a container.
  2. If your application contains user administration and password, make sure you have a super administrator whose password you can insert in the database with password_hash. This is specifically true for the application we will be deploying in the docker container.

For most standard applications (like MySQL, java 8, spring-boot), there are a number of images available in the docker hub. When we will run our docker container for the database, the docker shell will pull the version of that application from the hub to build a container. We will not be creating any new or blank docker image. To run a docker container with mysql version 5.6, we will use below command.



docker run --name benefitsmysql -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -e MYSQL_DATABASE=benefitsmysql -p 3308:3306 -d mysql:5.6

 

  • The name of our docker container is benefitsmysql.
  • We are not using any password. This is not recommended for production code, I am just doing this for demo purposes.
  • The database name is benefitsmysql.
  • Also this database is running at port 3308 to 3306 of localhost machine.
  • -d to tell Docker to daemonize the container and keep it running.
  • mysql:5.6 to download MySQL 5.6 Server image from Docker public repo

Once this is started, there are couple of ways you can verify if we are able to connect to this database or not.

Get the ip address of this container host with command docker-machine ip . Now in mysql administrator workbench, access the mysql server with ip address and port 3308 and see if you can access the database.

Another way on docker shell terminal – use this command docker exec -it benefitsmysql -l , this will connect you as a root to the shell where mysql is installed. And then you can use mysql as regular command to access mysql.

To run our Spring boot application successfully, once you access mysql, create the following tables:



use benefitsmysql;

create table companyprofile (id int not null auto_increment, establisheddate date, status varchar(50),corporationtype varchar(50), primary key(id));

create table company(id int not null auto_increment, name varchar(255), statusid int, type varchar(255), ein varchar(50), companyprofileid int, primary key(id), foreign key(companyprofileid) references company(id));

create table userprofile(id int not null auto_increment, dob date, doh date, maritalstatus varchar(50),sex varchar(50),ssn varchar(50),weight varchar(50), height varchar(50),employmentstatus varchar(50), terminationdate date, primary key(id));

create table user(id int not null auto_increment, createdate date, email varchar(255),firstname varchar(255), middlename varchar(255), lastname varchar(255),username varchar(100),jobtitle varchar(255),password_hash text,enabled tinyint(4), userprofileid int, primary key(id), foreign key(userprofileid) references userprofile(id));

create table role(id int not null auto_increment, role varchar(255), primary key(id));

create table user_role(user_id int not null, role_id int not null, primary key(user_id, role_id));

 

Building a docker image for Spring Boot Application along with mysql

To dockerize my spring boot application, we will use a maven plugin to build a docker image.


<plugin>
		<groupId>com.spotify</groupId>
            	<artifactId>docker-maven-plugin</artifactId>
            	<version>1.0.0</version>
            	<configuration>
                	<imageName>${docker.image.prefix}/benefits</imageName>
                	<dockerHost>https://192.168.99.100:2376</dockerHost>
                	<dockerCertPath>C:\Users\Yogesh Mali\.docker\machine\machines\default</dockerCertPath>
                	<dockerDirectory>src/main/docker</dockerDirectory>
                	<resources>
                    	<resource>
                        	<targetPath>/</targetPath>
                        	<directory>${project.build.directory}</directory>
                        	<include>${project.build.finalName}.jar</include>
                    	</resource>
                	</resources>
            	</configuration>
	</plugin>

I am passing dockerDirectory where Dockerfile will be stored to build our image. Also another change I have made to my original pom file, is that i have added packaging as jar.


<groupId>com.betterjavacode</groupId>
	<artifactId>Benefits</artifactId>
	<packaging>jar</packaging>
	<version>0.0.1-SNAPSHOT</version>
  .................
  <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <configuration>
          <mainClass>com.betterjavacode.benefits.Application</mainClass>
      </configuration>
      <executions>
          <execution>
              <goals>
                 <goal>repackage</goal>
              </goals>
          </execution>
      </executions>
  </plugin>

I have also changed in my application.properties to point to mysql database container by updating database url with ipaddress of docker container.

spring.datasource.url=jdbc:mysql://192.168.99.100:3308/benefitsmysql

My Dockerfile to build a docker image is as below:


FROM java:8
VOLUME /tmp
ADD Benefits.jar Benefits.jar
EXPOSE 8443
RUN bash -c 'touch /Benefits.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/Benefits.jar"]

Basically this will build a Benefits.jar using java 8 and will expose port 8443 that I can use to access my application.

Now build a new docker container image by using maven goal as

mvn clean package docker:build

To run the application

docker run -p 8443:8443 --name benefits --link benefitsmysql:mysql -d containerid

This will execute the jar built within that container. Important to note here is --link as it links other container where we have mysql server deployed. So we are linking two containers and we will call the database from our spring boot application container. The same command can be used little differently to see the detail execution log as below

docker run -p 8443:8443 --name benefits --link benefitsmysql:mysql -it containerid

 

Executing the application

Once the application starts successfully, we will access our application with url https://192.168.99.100:8443/home , this will look like below:

Another note – Make sure to update IP addess in all angular js references.

In this post, we showed how we can deploy Spring boot application connected to MySQL on a docker container. Code for this post will be available on GitHub repository here

References

To write my post, I used the following references

  1. Docker
  2. Connection refused error
  3. Spring Boot docker