Send Voice Call From Java Using Plivo API

Today I am telling you how send voice call from java and my previous tutorial is Send SMS from Java Using Plivo API.

After reading my previous post you can be analysed that how much simple to send sms from java using api.
Isn't it and same for voice call is simple. How is it i am telling you and check my another one tutorial for better understanding : Get Plivo API For Send SMS and Voice Call

Now its time to implement in our java code for Voice Call.
package plivo.helper;

import java.util.LinkedHashMap;
import com.plivo.helper.api.client.RestAPI;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.api.response.call.Call;

public class CallNumber {

        /**
         * @param args
         */
        public static void main(String[] args) {
          String authId = "Your Given Auth Id";
             String authToken = "Your Given Auth Token";
                RestAPI restAPI = new RestAPI(authId, authToken, "v1");
                
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                params.put("from", "Your Plivo Number");
                params.put("to", "Your Destination number for voice call");
                params.put("answer_url", "http://dl.dropbox.com/u/54579287/Docs/speak.xml");

                Call response;
                try {

                        response = restAPI.makeCall(params);
                        System.out.println(response.apiId);
                } 
                catch (PlivoException e) {
                        System.out.println(e.getMessage());
                }

        }

}

Happy coding my geekonjava coders and geekers !!!!!

Send SMS from Java Using Plivo API

Today  i am telling you about Plivo API which give you send sms from java. You can be send sms with free register and for testing purpose you can be use in your application.

Just Check out below step :
Step 1:
Get Authentication code and Authentication ID From Plivo
Step 2:
After doing successfully first step then we can be go ahead and now we get your phone number,auth code and auth id .
Step 3:
Now its time to implement these 3 item in our application for send sms using java.
import java.util.LinkedHashMap;

import com.plivo.helper.api.client.*;

import com.plivo.helper.api.response.message.MessageResponse;
import com.plivo.helper.exception.PlivoException;

public class SendMessage {

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                String authId = "Your Auth ID";
                String authToken = "Your Auth Code";
                String src = "Your Phone Number";
                String dst = "Number where you want to send SMS";
                
                RestAPI api = new RestAPI(authId, authToken, "v1");
                
                LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
                parameters.put("src", src);
                parameters.put("dst", dst);
                parameters.put("text", "Your Message should be here ");
                parameters.put("url", "http://server/message/notification/");
                
                try {
                        MessageResponse msgResponse = api.sendMessage(parameters);
                        System.out.println(msgResponse.apiId);
                        if (msgResponse.serverCode == 202) {
                                System.out.println(msgResponse.messageUuids.get(0).toString());
                        } else {
                                System.out.println(msgResponse.error); 
                        }
                } catch (PlivoException e) {
                        System.out.println(e.getLocalizedMessage());
                }
        }
        
}
Step 4:
That's it now enjoy your geek on java coding and keep commenting !!!!!

Get Plivo API For Send SMS and Voice Call

Hello Java Geeker i already knows that you want to send sms or call from your Java Application and today i solve your problem.
Solution is Plivo API and i am telling how to get this api for integrate in your application.

Step 1:
First of all you need to register your free account on Plivo.Com.
Step 2:
After register you need to activate your account by click on activation code on your email .
Step 3:
Now after activation  you need to login and when you'll login then a popup open for Unlock your free phone number which given below image.


Step 4:
After that you'll get confirmation call on that phone number and they'll give you confirmation code which you need to write.
Step 5:
When you confirm your phone number then you'll get plivo number(this is your phone number which used in your application).


Step 6:
Now Click on Dashboard on top menu and see the right side you'll get Auth Code and Auth Id which will use in our application .





New ways to open file in Java


Here i am telling you about new way to open file in java 7. It is latest feature which used try with resource.
It comes in Java 7.
 In Java, normally we open a file in a try block, and close the file in the finally block, see following :
try{
  //open file or resources
}catch(IOException){
  //handle exception
}finally{
  //close file or resources
}
Since JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try(open file or resource here){
 //...
}
//after try block, file will close automatically.
Classic way to read a file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example1 {
 
 public static void main(String[] args) {
 
  BufferedReader br = null;
 
  try {
 
   String line;
 
   br = new BufferedReader(new FileReader("C:\\testing.txt"));
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null)br.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 
 }
}
In JDK7, finally is no longer required. The file will be closed automatically after try block.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.System.out;//other feature of java 7
 
public class Example2 {
 
 public static void main(String[] args) {
 
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
  {
 
   String line;
 
   while ((line = br.readLine()) != null) {
    out.println(line);//other feature of java 7

   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } 
 
 }
}
Enjoy Java 7 and Happy coding !!!

Double Brace Initialization in ArrayList Java

Today i am telling you a different way of initializing collections and objects in Java. Some of people actually knows about it or have used it in their code.

The technique is called Double Brace Initialization technique in Java.
Let us see first how we will initialize an ArrayList in Java by “normal” way :
List<String> countries = new ArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");
Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.
Now check the Double Brace Initialization of the same code:
List<String> countries = new ArrayList<String>() {{
 add("India");
 add("Switzerland");
 add("Italy");
 add("France");
 add("Germany");
}};
Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. 

Static Import - New Way to Import in Java

Static import is a new feature comes in Java 5.0. In order to access static members, it is necessary to qualify references with the class they came from.

For example, one must say:
double r = Math.cos(Math.PI * theta);
or
System.out.println("Blah blah blah GeekOnJava");
Full Example :
import static java.lang.System.out;

public class Test
{
 public static void main(String arr[])
 {
 out.println("Sawan");
 }
}
So whats the advantage of using above technique? 
Only advantage that I see is readability of the code. Instead of writing name of static class, one can directly write the method or member variable name.
Also keep one thing in mind here. Ambiguous static import is not allowed. i.e.
If you have imported java.lang.Math.PI and you want to import mypackage.Someclass.PI, the compiler will throw an error. Thus you can import only one member PI.

How to Change Tomcat port numbers in server.xml file

By default, Tomcat is listening on the port number 8080 (for HTTP Connector) and 8009 (for AJP Connector), as shown in the following screenshot of Tomcat’s console when the server is started:






Sometimes, one needs to change these default port numbers because of conflict with other applications or just for convenience, e.g. change HTTP port number from 8080 to 80 in order to type the URL without specifying the number.
It’s very easy to change the port numbers in Tomcat, by doing the following steps:
  • Make sure the server is stopped, or shutdown it if it is running.
  • Open the server.xml file which can be found under TOMCAT_INSTALL_DIR\conf  directory:
  • If we want to change the HTTP port number, search for the following lines: 
<Connector port="8080" protocol="HTTP/1.1"
    connectionTimeout="20000"
              redirectPort="8443" />
  • Now change the port 8080 to 80: 
<Connector port="80" protocol="HTTP/1.1"
    connectionTimeout="20000"
              redirectPort="8443" />

Save the server.xml file (make sure you have write permission) and restart Tomcat. Now, we can see the HTTP port number gets changed in the console: 


Free JSP/Java hosting

 So many Java developer have question about free JSP,Servlet,Java hosting. After visiting so many site i found one perfect solution that works fine for my application. I'll give you step by step procedure to publish your site for demo. You'll find so many free hosting site but they will give you free hosting for month after you pay but for demo we need not pay from now.
http://free.hostingjava.it
  • Register your self for free account. Fill required information to register. You must agree both conditions to processed further. I recommend you not to upload sensitive and personal database on website. This is for testing purpose only. Check out the below image for reference.


  • Open Mysql from left side link and login with username and password of your account.
  • Open your database from left side panel. Admin panel of MySql shown in below image.
Now i am telling you how to Inserting data for sample application.
  • Get database connection link. Its available on website when you logged in user Tips and Hints section. It differ from user by user.
/*
* Its differ user by user.
* Get it from website itself.
*/
javax.sql.DataSource ds=
(javax.sql.DataSource)new javax.naming.InitialContext(). lookup("java:comp/env/jdbc/javaQuery"); 
ds.getConnection();

Sample code to access database.
<%
import java.sql.*;
 try {
      Class.forName("com.mysql.jdbc.Driver");
      javax.sql.DataSource ds=(javax.sql.DataSource) new javax.naming.InitialContext().lookup("java:comp/env/jdbc/javaQuery");
      Connection con = ds.getConnection();
      PreparedStatement stmt = con.prepareStatement("select * from javaQueryDEMO limit 0,1");
      ResultSet rs = stmt.executeQuery();
      if (rs.next()) {
 out.print(rs.getString(1));
      }
      con.close();
     } catch (Exception e) {
       e.printStackTrace();
 }
%

At last i am telling you How to upload file on website
  • You must have FTP software to upload files.
  •  FTP URL : ftp://javaQuery@free.hostingjava.it/ change this URL with your username or you can get it from admin panel of the website.
  • Username and password is same as register on website.
  • Upload appropriate file on web directory. 


How to Read and Write Excel File(.xls) using Java

Java is a powerful programming language with an array of features. “Write once, run anywhere” is truly a testament to the JVM (Java Virtual Machine) which allows Java code to function cross platform. Without getting into the details, today, we are going to use Java to read and write Excel (.xls) files, using a small library called JExcelAPI.
The JExcelAPI is an open source library which allows you to read, write and do a lot of cool stuff with Java and Excel. Today, we are going to show you the code that you can use to read and write data in Excel format (.xls), using Java of course.
 Let’s get started.:
Setting up on Eclipse
  • Before starting to code, we need to set up the working environment on the popular IDE Eclipse. You can download it by clicking the link here: Eclipse
  • Once you have installed the Eclipse onto your computer (most Java programmers already have), you need to create a new Java Project, as shown by the image below.

  • Once you have created a new Java Project, you need to download the JExcelAPI library package by clicking this link
  • Clicking this link will start the download process automatically. Unpack the .zip file and copy the file jxl.jar from there into your workspace. 
  • It helps to create a new folder in your workspace folder alongside src/. Name it lib/. Paste the jxl.jar in there. Now, open Eclipse and make sure jxl.jar is hooked to the build path. 
  • Eclipse lets you do this manually by right clicking the .jar file and following the options from there on. It should be a breeze from here on, as you’re ready to code.


Reading Excel (.xls) files
JExcelAPI can be used to read and write Excel files. The supported format is .xls. JExcelAPI can read an Excel spreadsheet from a file stored on the local filesystem. It even works from input streams. 
The code below is used to read an Excel file placed in a new folder of the Eclipse workspace folder i.e. in the same place as the src/ folder or root. 
It is better to keep your .xls files in a new folder called resources/, like we have in the example code as shown below.
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;

public class ReadExcel {

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

  Workbook workbook = Workbook.getWorkbook(new File("resources/sample.xls"));
  Sheet sheet = workbook.getSheet(0);

  Cell A = sheet.getCell(0,0);
  Cell B = sheet.getCell(1,0);
  Cell C = sheet.getCell(2,0);

  String stringA = A.getContents();
  String stringB = B.getContents();
  String stringC = C.getContents();

  System.out.println(stringA);
  System.out.println(stringB);
  System.out.println(stringC);

 }

}

Writing Excel (.xls) file
JExcelAPI is not just about reading data from Excel Spreadsheets. You can use it to create .xls or Excel files too. The code below demonstrates how you can use a few lines of Java code to create an .xls file, without any formatting (even though its possible but its beyond the scope of this tutorial).
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;

public class WriteExcel {

 public static void main(String[] args) throws IOException, BiffException, RowsExceededException, WriteException {

  WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));
  WritableSheet sheet = workbook.createSheet("First Sheet", 0);

  Label label = new Label(0, 0, "Mr Geek Ltd");
  sheet.addCell(label);

  Number number = new Number(1, 0, 1.618);
  sheet.addCell(number);

  Label label1 = new Label(2, 0, "Ali Gajani");
  sheet.addCell(label1);

  workbook.write();
  workbook.close();

  System.out.println("File output complete");

 }

}

If you have any questions regarding this tutorial, do not hesitate to drop a comment below.

How to Read Excel File Data In Java Using Apache POI

Today i am telling you about how to read and write excel file in java using Apache POI. Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc. The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered.



Requirement :
  • Java JDK 1.5 or above
  • Apache POI library v3.8 or above (download)
  • Eclipse 3.2 above (optional)
First of all you need to Add Apache POI dependency to your project by include POI jar file.If your project uses Maven as dependency management, add following in your Pom.xml file.
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
If you are not using Maven then you can directly add required JAR files in your classpath.
  1. Download poi-2.5.1.jar(or in this case 3.8) jar file.
  2. Include this file in your projects class path.
  3. Create new java project in eclipse with auto generated main function.
After that we'll to read an excel file, Apache POI provides certain easy-to-use APIs. In below sample code we use different classes from POI library to read content of cell from excel file.
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
             
//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);
 
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
 
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
 
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
Notice how each class in POI library starts with HSSF prefix! e.g. HSSFWorkbook, HSSFSheet etc. HSSF stands for Horrible SpreadSheet Format!
 I’m not kidding.. It really is.
Similar to HSSF, POI has different prefix for other file formats too:

  • HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
  • XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
  • HPSF (Horrible Property Set Format) – reads “Document Summary” information from Microsoft Office files.
  • HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
  • HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
  • HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
  • HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
  • HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files
  • DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.
Isn't cool it is and now go ahead with our tutorial . Its time to tell you how to work with .xlsx files.
 The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with newer xls format viz .xlsx, you need to see newer POI classes like:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));
             
//Get the workbook instance for XLS file 
XSSFWorkbook workbook = new XSSFWorkbook (file);
 
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
 
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
 
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();

Use XSSFWorkbook and XSSFSheet class in all of the below examples in order to make them work with .xlsx files.
Consider a sample excel file:
test.xls
We will read above xls file using Apache POI and prints the data.
try {
     
    FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
     
    //Get the workbook instance for XLS file 
    HSSFWorkbook workbook = new HSSFWorkbook(file);
 
    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);
     
    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();
         
        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {
             
            Cell cell = cellIterator.next();
             
            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    break;
            }
        }
        System.out.println("");
    }
    file.close();
    FileOutputStream out = 
        new FileOutputStream(new File("C:\\test.xls"));
    workbook.write(out);
    out.close();
     
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Output :
Emp Id      Name        Salary    
1.0           John              2000000.0    
2.0           Dean            420000.0      
3.0           Sam             280000.0      

4.0           Cass            6000000.0