Saturday, August 29, 2015

Play audio file in Java

Couple of week ago I needed to implement audio tone play in a Java application and I could not able to find clear reference which developers can refer So I though to put a blog post on this. In this post I am going to show show to play audio file using Java.

Prerequisites 
  1. You should have install java in your PC and set path variable correctly (JAVA_HOME, JRE_HOME)
  2. You should have install Eclipse Java EE LUNA 4.4 IDE or any IDE you preferred (In this post I'm Using Eclipse )

Step 1 Create Java project 

As first step lets create simple Java Project using Eclipse. Go to File->New->Java Project. Give preferred name to project. I'm going to name the project as "AudioPlay". Then find some Audio file you need to play. Then create new package call "resource" inside the src directory and added the audio in to that package.

 


Step 2 Create java class to play audio 

As next step lets create the Java class to play our selected audio. To add new class go to default package and right click on it then go to New->Class. I'll give class name as "AdvancedPlayer.java". Then add following content in to that class.


import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;


public class AdvancedPlayer implements LineListener {
boolean playCompleted;
    
    /**
     * Play a audio file which pass as audioFilePath 
     * @param audioFilePath Absolute path of the audio file.
     */
    void playAudioFile(String audioFilePath) {
        File audioFile = new File(audioFilePath);
 
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
 
            AudioFormat audioFormat = audioInputStream.getFormat();
 
            DataLine.Info formatInfo = new DataLine.Info(Clip.class, audioFormat);
 
            Clip clip = (Clip) AudioSystem.getLine(formatInfo);
 
            clip.addLineListener(this);
 
            clip.open(audioInputStream);
             
            clip.start();
             
            while (!playCompleted) {
                // wait for the playback completes
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
             
            clip.close();
             
        } catch (UnsupportedAudioFileException e) {
            System.out.println("Error on not supporting file format");
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            System.out.println("Error occured due to unavailable of Audio line for playing.");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Error occured in audio play.");
            e.printStackTrace();
        }
         
    }

@Override
public void update(LineEvent event) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AdvancedPlayer player=new AdvancedPlayer();
String audioFilePath="resource/Alarm01.wav";
String absolutePath=AdvancedPlayer.class.getResource(audioFilePath).getFile().toString();
player.playAudioFile(absolutePath);
}
}
  
Then our final project will be look similar to below screenshot. Now just run the AdvancedPlayer class and you can here the audio that you have added in to resource.

Figure 2 : Project structure



Saturday, August 8, 2015

Helloworld Spring 4 MVC in Eclipse Luna

In this post I'm going to explain steps to install Spring Tools for eclipse.

Prerequisites 
  1. You should have install java in your PC and set path variable correctly (JAVA_HOME, JRE_HOME)
  2. You should have install Eclipse Java EE LUNA 4.4 IDE or later version in your PC. (If you have some other Eclipse version first check whether it supports to install Spring and if so install spring in to it using Install new software)
Step 1 Create Dynamic web project

As first step lets create simple Dynamic Web Project using Eclipse. Go to File->New->New Dynamic Web Project. Give preferred name to the project (Here I will user project name as SharedResourceWeb as Figure 1). Make sure you have selected Apache Tomcat 7 as target run time. If it's not available click on New Runtime button Then provide tomcat installation directory. Here you should provide installed JDK in JRE selection. This is really important otherwise it will give run-time errors when project deployed in to server.


Figure 1 : Create dynamic web project


Figure 2: Add new Server Runtime if TomCat 7 not available

Step 2 Convert to Maven Project




Then convert project in to maven project my right click on project and go to Configure -> Convert to Maven Project(Figure 3)



Figure 3: Convert to Maven Project
Then you will see interface similar to Figure 4 and click Finish.
Figure 4: Convert to Maven project interface

Then right click on project and go to Properties -> Project Facts as show in Figure. Then Select Dynamic Web Module and apply changers.

Then go to Java Build Path and the JRE System Library and you have to set installed JDK versionDo not user J2SE default selected one you will get run time errors if you keep default one .


Then we have to change our project structure to commence with Maven standards there for lets delete the WebContent folder on project and added new webapps folder on src->main folder as show in below.


 Then we have to remove previous WebContent folder from deploying structure and add new webapp folder in to deployment. Go to project properties -> Deployment Assembly then remove the WebContent folder.
 

Then click on add -> Folder then select webapp folder in your project. Fina details will be similar to below image.


Then lets create deployment descriptor in to the project for that right click on the project and then go to Java EE Tools -> Generate Deployment Descriptor stub.


Then you can see Eclipse will generate WEB-INF folder inside your webapp folder with web.xml file.I believe that your Eclipse has already setuped tomcat server. If you don't have the please refer my previous post it contains how to install tomcats server step by step. 

Step 3 Update POM.xml file

Then lets add our dependencies in to the project. This can be done in ways. First one will be from Eclipse interface and other one is updating POM.XML file. First I will show how to do this dependency adding in to using Eclipse interface.
First change following properties on Project properties under Maven. Then check on  Download repository index on Startup. As below image




First double click on POM.XML file and then click on dependencies as below image shows.




Then click on Add dependency section and then type "org.springframework" on input under Enter groupid artifactid or sha1 prefix of pattern (*) in loading dialog. Then select org.springframework spring.webmvc as show in below image. Then click OK.




Then lets add logging jar dependencies for that click add on dependencies section again and type slf4j-log4j then select slf4j-log4j and click OK.


Again click on add button and type log4j then select log4j log4j then click OK.
 

After that in dependency section Log4J as bundle but we need to have the jar so to change that select Log4J and click on manage. Then change the Type to Jar on dependency properties interface. Then click OK.


Then again click on Add and type jstl then select jstl jstl and click OK. As show in below image.



Then we need to add log4J property file right click on src-> main->resources and add new file call "log4J.properties" then copy and past following configurations in to that file then save it.

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 
If You are not interested about above GUI then just needed to add following bold section in to POM.xml. Here is whole POM.xml file for my project.

<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>SpringFirstWeb</groupId>
  <artifactId>SpringFirstWeb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j13</artifactId>
          <version>1.0.1</version>
      </dependency>
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>

    </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>

    </plugins>
  </build>
</project>



Step 4 Create Spring configuration file

Create springfirst-servlet.xml inside WEB-INF folder. Add below content in to that file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<mvc:annotation-driven/>
<context:component-scan base-package="spring.first.controller"></context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>


In above file we define following tags.
context:component-scan
This tag use to specify the component scan location for Spring. In this example it will scan in spring.first.controller folder and it's sub folders.

viewResolver
This bean use to define resolve view. In that prefix use to define the location where Spring framework search for views.

Step 5 Create web.xml file
Add web.xml file in to WEB-INF folder with following content.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>SpringMVCTutorial</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
    <servlet>
        <servlet-name>springfirst</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springfirst</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/helloworld.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
 
</web-app>


Step 5 Create controller for application

Lets create controller for our application. Go to folder structure and create SpringFirstHelloWorld.java controller class inside package spring.first.controller under src folder with below content.

package spring.first.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/*
 * author: Nirmal Balasooriya
 *
 */

@Controller
public class SpringFirstHelloWorld {
    @RequestMapping("/helloworld")
    public ModelAndView helloWorld() {

        String message = "<br><div style='text-align:center;'>"
                + "<h3> Hello World, Spring MVC Tutorial</h3>"
                + "This message is coming from SpringFirstHelloWorld.java "
                + "</div>"
                + ""
                + "<br><br>";
        return new ModelAndView("welcome", "message", message);
    }

}

Step 6 Create views

Lets create two views for our application. index.jsp  inside the WebContet folder and welcome.jsp inside WEB-INF/jsp folder

index.jsp should contains following content.

<html>
<head>
<title>Spring MVC</title>
<style type="text/css">
</style>
</head>
<body>
    <br>
    <div style="text-align:center">
        <div><h2>
            Spring MCV Tutorial<br>
        </h2>
        </div>
        <h3>
            <a href="helloworld.html">Click here</a>(Get message from
            Spring MVC Controller... @RequestMapping("/helloworld"))
        </h3>
    </div>
</body>
</html>


welcome.jsp with below content.

<html>
<head>
<title>Hello World Spring MVC
    Example</title></head>
<body>${message}

    <br>
    <br>
    <div style="font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px; text-align:center;">

        Spring MCV Tutorial by <a href="http://nirmalbalasooriya.blogspot.com/">nirmalbalasooriya.blogspot.com</a>.
            <p>Click here for this tutorial <a
            href="
http://nirmalbalasooriya.blogspot.com/2015/08/install-spring-tools-in-eclipse-luna.html"
            target="_blank">here</a></p>       
    </div>
</body>
</html>


After all above steps you can see project structure similar to Figure 5

Figure 5: Final project structure

Then right click on project and go to Run As -> Run on server . Then you will be able to access MVC Spring project you created from URL similar to http://localhost:8888/SpringFirstWeb/

From this URL you will able to access interface similar to Figure 6.

Figure 6: initial page of the project you created

You can download the entire project on following GitHub location https://github.com/NirmalBalasooriya/SpringWeb. I will add some advanced features of Spring framework in upcoming posts.