Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, February 8, 2014

How to debug Maven Applications in Intellij IDEA

Before I start, I would like to emphasize that this article is based on a Java console application and you need to make minor justifications in order to make it work for web apps in general.

I am assuming that you have a maven project (check out Getting Started with Maven) to make sure that project structure is valid.

To be able to debug a maven application, you need to set a Maven Debug Configuration in your Intellij IDEA project. If you do not know anything about existence of such thing, do not be scare as I will follow you through the steps.

First, in order to create a maven debug configuration, go to Run and click on Edit Configurations:


After that the Run/Debug Configuration window will pop up. Click on the "+" sign at the top-left part of the window, find Maven and click on it:


Now, you will see your Maven Configuration window. You can set a name  for it based on the goal of this debug or even name of the project. Just right below the name textbox, there are three tabs: Parameters, General and Runner. For this tutorial, we stick with the project settings options for the last two tabs and just consider the options inside the first Tab. As you can see in the following screen capture, the project directory has already been set for you. The most important task here is to set the command line of this configuration plus the profile of which you would like to debug your application.




Since we have a console application here, we will use Exec Maven Plugin which exists in Maven version 1 onwards.

exec:java -Dexec.mainClass=MainClass -Dexec.args=args

The -Dexec.mainClass will be set to the entry point of the application, here is the class with the main method, and -Dexec.args will be a set of arguments which will be passed to that main method. Here is an example:


exec:java -Dexec.mainClass=TopologyMain -Dexec.args=src/main/resources/words.txt

Now after you have set your debug breakpoint, set your Maven configuration in the dropdown of Select Run/Configuration and click on Debug (Or alternatively, go to Run and click on Debug and in the new window, select your Maven Config file):


After that, the Exec Plugin will compile your code and detach to the debugger process, like the following:



Happy Debugging your Maven Code!

Monday, May 27, 2013

Handling Multiple Exceptions in Java 7

Not much introduction in this post, but as most of you know, that was how Java SE used to handle multiple exceptions:
catch (DataFormatException ex) {
     ex.printStackTrace();
     throw ex;
catch (FileNotFoundException ex) {
     ex.printStackTrace();
     throw ex;
}
Now the problem rises when you do not want to write much code specifically to each clause, maybe you just are printing the stack trace or logging the exception. With the Java SE 7, you can write less code and be more flexible, something like this:
catch (DataFormatException|FileNotFoundException ex) {
    ex.printStackTrace();
    throw ex;
}

Tuesday, January 22, 2013

How to resolve 'Could not find the required version of the Java(TM) 2 Runtime Environment'?

I was encountering the 'Could not find the required version of the Java(TM) 2 Runtime Environment' error when I was trying to install JDK 64-bit on my 64-bit Windows 7 machine.

The reason for throwing such error is that JDK installer is written in Java, therefore you need to have JRE installed. I assume that this is a bug in the Java installer somewhat, because after installing JDK EE, you will have a JRE inside that as well, so you end up having two JREs. Surprisingly, if you install JRE 64-bit and set your %JAVA_HOME% and path variables, you will still see that issue remains the same.

Solution is that you should install JRE 32-bit instead of 64 bit version of JRE. If you install it, then you can install JDK EE or/and Glassfish via the installer. This might sound strange but it is true!

Wednesday, January 9, 2013

Create a Dynamic Web Project with Maven in Eclipse Juno

Recently, I began to show my interest to start using Apache Maven in nearly all of my projects. Today, I was  trying to get hold of creating a Dynamic Web Project (Jave EE) project using the M2Eclipse Plugin, which is a fascinating tool to work with, but is tricky as well. While there are other related posts like here, they are outdated and in case you will follow them, you will be exhausted.


1. Prerequisites

You have to have the followings in advance:

  • Eclipse Juno for Java EE developers
  • JDK 1.6 or above
  • Apache Maven 3.0 or above
  • M2E Plugin (You can get this easily by searching it in the search bar of Eclipse Market Place inside the Help  menu of your Eclipse)
  • Apache Tomcat 

2. Create a Maven Project

2.1 Plugin Prerequisites 

You need to have a plugin called M2Eclipse which you can fetch it via Eclipse Marketplace (In case you do not know, just browse to Help and then you can find it there)

Some of you may not know but you also need another plugin called Eclipse WTP plugin. The latter is the plugin that lets you run Web Applications with Built-in servers. Have a look at the plugins you need to have  in advance:


Also note that there is another Maven Eclipse WTP plugin which is not depreciated in favor of the one you can see in the above picture. Everytime you need to install a plugin, you also need to restart your Eclipse.


2.2 Create your project

This step is just simple and easy. First, click on File, then go to New and click on Other... . In there you can search for the word "Maven" and you will get the following options:



Then, simple click on the Next button and in the next dialogue, select maven-archetype-webapp move on:





And the final step is to name your project:



You should by now see the following structure of your project with the new look:


Notice that you have your Deployment Descriptor which enables you to run it on Eclipse's internal server. Open your pom.xml and change it to the following:



  4.0.0
  telecom
  agent
  war
  0.0.1-SNAPSHOT
  agent Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
 javax.servlet
   servlet-api
   2.5
    
  
  
    agent
  

As you can see I just added the servlet-api.jar to the dependencies of the project, when later on we will have to compile our Maven project. Now, I will add a basic Servlet in the package src/main/java/servlet/HelloWorld.java:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException {
     
             response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("The app is up and running!");
  out.close();
  
 }

}


After that, add the servlet information and pattern in the web.xml which you may find under src/main/webapp:

  Archetype Created Web Application
  
      hello
      servlet.HelloWorld
  
  
      hello
      /hello
  



Now it is the time to compile the project. Here you have two options. First is to Right click on your project, then choose Maven and Click on Maven Clean and after that on Maven Install or else, run the following command inside your project directory:

cd /project/directory
mvn clean install

You can have your .war file in your target directory now and you can deploy it in your Apache Tomcat container, however the missing part here is that Eclipse does not know that your project is a web project, therefore you cannot deploy it in your local Apache Tomcat Server (Also your development Server). Every time you code, you need to compile and see the result in your Tomcat. Now we do two more steps so that we can have both the .war file and you will be able to run the application while coding in your tomcat server. First, go to Servers menu which resides in Window and then Show View:


And simply add a Apache Tomcat 7 instance, without changing any settings and click Finish.


3. Run the Project

Now, click on your project in Eclipse's navigation bar and click Refresh. As you can see, the project structure changes. Now you can simple right click on HelloWorld.java and run it on Server, as following:


And that is it! You now have a fully working Dynamic Web Project Maven Project in eclipse!


Remark: In contrast with a lot of tutorials out there, you should not manually change Project Facets of your project, while you are working with Maven projects in Eclipse. The project should read everything from your pom file and change the facets on the fly.

Sunday, January 6, 2013

Multi-Threaded Socket Programming in Java (Part II- Client)

As you saw in first part of Multi-Threader Socket Programming, we handled everything from the server's point of view. There are not so much thing going on at the client's side, and technically speaking you should bear in mind that client will not even know how the server processes its request. So the client part's code is not really dependent toward the context of threading obviously.
        
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            socket = new Socket("Amir", 8081);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: Amir.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: Amir.");
            System.exit(1);
        }

As you can see, we initiated the socket with the Server Socket's name and port. The PrintWriter is getting the output stream of the socket so that we can later write on it and we also initialized an BufferedReader object to receive the stream of server's response.
        
        String serverMessage;
        while ((serverMessage = in.readLine()) != null) {
            System.out.println("Server: " + serverMessage);
            if (serverMessage.contains("MESSAGE RECEIVED"))
                break;
        }  

As you can see, listening for server's response and if the Server's response contains the String literal "MESSAGE RECEIVED", the loop is broken. This part is inside my very own protocol, and you can have whatever you would like to have there. Finally, you just have to remember to close the streams and sockets in order to avoid any resource leaks:

        out.close();
        in.close();
        socket.close();

So we are done. I tried to come up with something very easy and therefore you do not get lost in there. However, if anyone is interested in having a whole sort of real application up and running, take a look at the Source repository here: https://github.com/fidelio-coder/MultiThreadServer 

Monday, December 31, 2012

Multi-threaded Socket Programming in Java (Part I - Server-Side)


The idea behind this post to create a minimalist Client/Server application that can be run within a network. There are many valuable posts about the same topic, but most of them tend to be long and it is hard to get the actual meat in a rather shorter time.

Let's first briefly go over some network programming buzzwords:

  • Port: Type of software constructor which is used as a communication endpoint at Server-Side. Ports are either process-specific or application-specific and are mainly used in Transport Layer protocols such as TCP/IP. 
  • Socket : one end-point of a two-way communication link between two programs running on the network. A socket is bound to a specific port number.

Single-Threaded Server:

In the below code, what you need to do is to simply Create a ServerSocket object with the port number. Afterwards, the server instance listens on a port for a connection request from a client and accepts it right after that. Notice that the reason it is a single-thread server processor is that if two clients request for a connection at the same-time, the second client will not be processed unless the server is done with the first client's request.


import java.io.IOException;
import java.net.ServerSocket;
public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

    try {
        serverSocket = new ServerSocket(8081);
    }
    catch (IOException e){
            System.out.println("Could not listen on port 8081!");
            System.exit(-1);
        }
    
    Socket clientSocket = null;
    try {
        clientSocket = serverSocket.accept();
    } 
    catch (IOException e) {
        System.out.println("Accept failed: 8081");
        System.exit(-1);
    }
  }
}

Multi-threaded Server

As I said earlier, the single-threaded server is not gonna work is almost all cases. With all of computers having dual/triple core servers, a programmer needs to be able to use that opportunity to deliver faster solutions. Java makes concurrent programming really easy by the abstraction layers it has created inside the language libraries.

Let us start with the simplest situation possible. In the multi-threaded case, server will listen to a client request and as soon as it gets the request, starts a Thread and process it. For that, we need to replace the following lines:


Socket clientSocket = null;
    try {
        clientSocket = serverSocket.accept();
    }

With this:

while (true)
    {
        new MultiServerThread(serverSocket.accept()).start();
    }


In here, the MultiServerThread class will handle most of the Server's work. This class will inherent Thread as its super class. As you may know, while implementing Thread, you will do most of your work in the run method as below:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MultiServerThread extends Thread {

    Socket socket;

    public MultiServerThread(Socket socket) {
        super("MultiServerThread");
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                            socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            //Implement Server Protocol and Methods in Here
            }

            out.close();
            in.close();
            socket.close();

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

As you can see in the code, you can instantiate Bufferedreader to read the Client's request and process that later. Also, you need to instantiate PrintWriter object with the OutputStream of the Socket to write the message back to client. Note that you should close the Streams as it can exploit your program to a Memory leak.

The second part of this entry can be found here: Multi-Threaded Socket Programming in Java (Part II- Client)

Friday, December 21, 2012

Abstract Factory Pattern in Java

I was searching the other day for this pattern and while there are many websites referring to the pattern, they mostly fall into long discussions of this pattern. What I will do is that I make it as brief as possible.
We all know that our desire for coding is to have full flexibility to change components without re-writing many parts of code. So in any service-oriented scenario, what we mainly trying to do is to keep the client "as dumb as possible". So let us cut right to it.

The minimum requirement for Abstract Factory Pattern is to have a client class, one interface and (at least) two classes that implement that interface. This means that those two have their methods in common. If that is not the case for you, you are looking at the wrong pattern. Abstract Factory Pattern needs to be applied to help you instantiate a group of similar classes. Like in our example, we have IT consultant and Software Developer classes:


public class ITConsultant implements EmployeeInterface {

    private final String name;

    public ITConsultant (final String name)
    {
        this.name = name;
    }

    @Override
    public void introduceYourself()
    {
        System.out.println("Hei, I am " + name + " and I am an IT Consultant, cool huh?");
    }

    public String getName() {
        return name;
    }
}
public class SoftwareDeveloper implements EmployeeInterface {

    private final String name;

    public SoftwareDeveloper (final String name)
    {
        this.name = name;
    }

    @Override
    public void introduceYourself()
    {
        System.out.println("Hei, I am " + name + " and I am a Software Developer, cool huh?");
    }

    public String getName() {
        return name;
    }

}
See how similar they are? Because they both are implementing the EmployeeInterface:
public interface EmployeeInterface {
    public void introduceYourself();
}
Before going to the last step, I just want to point that sometimes even thinking about this pattern, gives me the idea that some of my classes can really implement a single-interface. So thinking about design patterns make your mind up. Now, if the client wants to instantiate an instance of, for example ITConsultant class, you can simply do this:
public class BadPractice {
    public static void main(String [] args)
    {
        SoftwareDeveloper amir = new SoftwareDeveloper("Amir");
        amir.introduceYourself();
    }
}
Why bad practice? Because your client code is hard-coded with this class and changes make you to re-write this. Now is the time for Abstract Factory Pattern! This is an example of a factory class:
class EmployeeFactory {
    public static EmployeeInterface createEmployee(final String name, final String seed )
    {
        if (seed.equals("SWD"))
            return new SoftwareDeveloper(name);
        else if (seed.equals("ITC"))
            return new ITConsultant(name);
        else
            throw new IllegalArgumentException("Your seed is not compatible to any of classes");
    }
}
Notice that the method of the factory should be static. Also we pass name and a seed to the factory so that we can decide which type of instance to return. The name parameter will be passed as name for the constructor of SoftwareDeveloper and ITConsultant classes. Now the last part of the work is to create our dumbo client. Client does not know anything about the details and gets decoupled:
public class GoodPractice {

    public static void main(String [] args)
    {
        EmployeeInterface amir = EmployeeFactory.createEmployee("Amir", "SWD");
        amir.introduceYourself();
    }
}
The output is now:
Hei, I am Amir and I am a Software Developer, cool huh?
as we expected! And that was it.

Thursday, August 30, 2012

Interview Question: Determine Whether a Text includes all ASCII characters

import java.util.Arrays;

import java.util.Scanner;

import java.io.UnsupportedEncodingException;





public class ASCII {



 /**

  * @param args

  * @throws UnsupportedEncodingException 

  */

 static String text = "";

 static boolean[] counter = new boolean[256];



 public static void main(String[] args) throws UnsupportedEncodingException {



  while (text == "") { 

   System.out.println("Enter Your Text and Press ENTER:");

   text = readText();

  }



  byte[] result = text.getBytes("US-ASCII");

  long[] intResult = new long[result.length];

  long value = 0;

  //Converting Byte Array to its Integer equivalence

  for (int i = 0; i < result.length; i++)

  {

     value = (value << 8) + (result[i] & 0xff);

     intResult[i]= value;

     value=0;

  }

  long[] sortResult = sortArray(intResult);



  if (hasAllASCIIChars(sortResult))

   System.out.println("Text has all ASCII characters");

  else

   System.out.println("Text does not have all ASCII characters");

 }



 



 /**

  * 

  * @param sortedArray: sorted array of ASCII Codes of characters (Long)

  * @return

  */

 private static boolean hasAllASCIIChars(long[] sortedArray) {



  for (int i = 0; i< sortedArray.length - 1; i++) 

   if (!counter[(int)sortedArray[i]])

    counter[(int)sortedArray[i]] = false;



  for (boolean bool : counter)

   if (bool == false)

    return false;

  return true;  

 }



 public static String readText() {

  Scanner sc = new  Scanner(System.in);

  if (sc.hasNext()) {

   return sc.nextLine();

  }

  else {

   return "";

  }

 }



 



 public static long[] sortArray(long[] array) {

  Arrays.sort(array);

  return array;

 }

}

Thursday, July 26, 2012

JMS (with) Spring and Apache ActiveMQ

0. Introduction

If you have worked with Java EE or you are willing to work with it, you probably have heard about Apache Active MQ. Since, for some reason, nearly each and every blog post that I have read on JMS and Spring (Including Spring In Action (Third Edition) and Just Spring (First Edition)) are using ActiveMQ. ActiveMQ is also recommended to be used while developing Java EE applications with Spring Framework.

So let us briefly explore what are advantages and disadvantages of using ApacheMQ.

First question that comes to mind is why it is so popular. apparently, you have variety of options as the following list proposes:
source: Wikipedia, http://en.wikipedia.org/wiki/Java_Message_Service#Provider_implementations


ActiveMQ seems to be quiet a popular option. As Aron Mulder mentioned in SpringSource webinar (Webinar Slides): it is open-source and community-based (as compared to JBoss MQ), its performance in being able to run standalone, or equally inside another process, application server, or Java EE application, its support for nearly everything JMS requires, and lastly its various extensions that integrates well into other products. Apart from what was mentioned in the Webinar, a key benefit of using ActiveMQ with Spring is that, Spring introduced  DefaultMessageListenerContainer object from API 2.0 and with that you only need to define an onMessage method where you can easily enable batch processing.


On disadvantages side, ActiveMQ can decrease performance, if you are not using a connection pool. As JmsTemplate asks for a connection per message and then closes it, therefore can put a huge processing load on the server.