I love to make things automate. Recently I have created www.algorithmsdemos.com. For this website, I have to style the code in C, Java, JavaScript. After Styling 30 programs, I felt to make this automate. I am using http://markup.su/highlighter/  to convert programs into beautiful markup. I have clearly observed how this website working. It is using one service at URL markup.su/api/highlighter. By using this service I have created one eclipse plugin convert program into beautiful markup.

Setup 

  1. Download above project and import to your workspace
  2. Run the project as eclipse plugin project. Now you can see new eclipse window with new workspace
  3. Create a sample dynamic web project and create a Java or HTML document. Write C or Java or JavaScript code in that document
  4. Open Project Explorer or Package Explorer and right click on that document and go to Sysntax Hilighter sub menu and then click on C or Java or JavaScript or HTML



If you want to create more options for this plugin, download this project and work on top of it. Here I will give some important code snippets to make a plugin like this.

Identify File From Package Explorer or Project Explorer

This code is to know the selected file by user in Package Explorer or Project Explorer.
IWorkbench workbench = PlatformUI.getWorkbench();
ISelectionService  is = workbench.getActiveWorkbenchWindow().getSelectionService();
IStructuredSelection structured = (IStructuredSelection) is
.getSelection("org.eclipse.jdt.ui.PackageExplorer");
IFile file = null;
if (structured == null)
{
    structured = (IStructuredSelection) is
    .getSelection("org.eclipse.ui.navigator.ProjectExplorer");
    file = (IFile) structured.getFirstElement();
}
IPath path = file.getLocation();
// Do something with path.

Sending Post Request to Markup Service

public static String hilight(String code, String lang) throws IOException {
     String url = "http://markup.su/api/highlighter";
     String USER_AGENT = "Mozilla/5.0";
     
     URL obj = new URL(url);
     HttpURLConnection con = (HttpURLConnection) obj.openConnection();

     //add reuqest header
     con.setRequestMethod("POST");
     con.setRequestProperty("User-Agent", USER_AGENT);
     con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

     //add parameters
     StringBuilder sb = new StringBuilder();
     sb.append(URLEncoder.encode("source", "UTF-8")).append('=').append(URLEncoder.encode(code, "UTF-8"));
     sb.append("&"+URLEncoder.encode("language", "UTF-8")).append('=').append(URLEncoder.encode(lang, "UTF-8"));
     sb.append("&"+URLEncoder.encode("theme", "UTF-8")).append('=').append(URLEncoder.encode("Dawn", "UTF-8"));
     
     String urlParameters = sb.toString();

     
     // Send post request
     con.setDoOutput(true);
     DataOutputStream wr = new DataOutputStream(con.getOutputStream());
     wr.writeBytes(urlParameters);
     wr.flush();
     wr.close();

     int responseCode = con.getResponseCode();
     System.out.println("\nSending 'POST' request to URL : " + url);
     System.out.println("Post parameters : " + urlParameters);
     System.out.println("Response Code : " + responseCode);

     BufferedReader in = new BufferedReader(
             new InputStreamReader(con.getInputStream()));
     String inputLine;

     StringBuilder resp = new StringBuilder();
     
     while ((inputLine = in.readLine()) != null) {
         resp.append(inputLine);
     }
     in.close();
      
     System.out.println(resp.toString());
     
     //return syntax hilighted response
     return resp.toString();
 }
I am looking forward to develop this plugin with more features. I will also post them soon.
Read More
Microsoft is providing Bing maps API. To access this API, you need to register the application and get the key. See official documentation here.

Program Flow

  1. Form Get request to Bing Maps API server
  2. Get Response 
  3. Convert Response to Java Pojo Classes
  4. Use those Pojo classes for your own logic
Find the project at below link and execute BingMapDistance.java file.

Get the key 

Register your application here, and get the key.

Form URL

http://dev.virtualearth.net/REST/v1/Routes?wp.1=Cambridge, UK&wp.2=Church St, Newcastle-under-Lyme, UK&key=Your-Applicattion-Key

Parameters

  1. wp.1 - Give starting location address
  2. wp.2 - Give ending location address
  3. key - Give your application key
  4. o - Output format (xml, json)

Java Code

String from = "lynnwood";
String to ="seattle";
String key = "Paste your application key here";
URL url = new URL("http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0="+from+"&wp.1="+to+"&avoid=minimizeTolls&key="+key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println("*********** JSON Response ***********");
System.out.println(outputString);
System.out.println("*********** POJO Classes ***********");
DistancePojo capRes = new Gson().fromJson(outputString, DistancePojo.class);
System.out.println(capRes);
System.out.println("*********** Distance ***********");
System.out.println(capRes.getResourceSets()[0].getResources()[0].getTravelDistance() + " km");
Read More
Google is providing Distance Matrix Web Service for finding distances between places. You can find the documentation of that REST service here. In this tutorial I am going to explain how to use that service using java.

Program Flow

  1. Form Get request to Google server
  2. Get Response 
  3. Convert Response to Java Pojo Classes
  4. Use those Pojo classes for your own logic
Find the project at below link and execute GmapDistance.java file.

Get Url

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling

Parameters

  1. origins — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values
  2. destinations — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values
  3. key — Your application's API key. This key identifies your application for purposes of quota management
  4. mode — specifies the mode of transport to use when calculating directions (driving (default), walking, bicycling)

Java Code

URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
     outputString += line;
}
System.out.println(outputString);
Read More
Recently I have created demo at http://www.algorithmdemos.com/trees/binary-Search-Tree.html to explain how Binary Search Tree works. Initially to draw binary search tree, I have used equal distance between nodes, Then I have seen overlapping of nodes as shown in below diagram.
Every node position will be based on its parent node position. If parent node is at (300, 0)  then its child positions will be (250, 50) and (350, 50). Here X coordinate incremented or decremented by 50 and Y coordinate incremented by 50. Because of this approach I got overlapping problem as shown in above diagram. ( Node 6, 10 overlapping in the above diagram).

In Balanced Binary Tree, nodes will increase in exponential way along with height. So we can decide X -coordinate of  Tree Node using exponential decay. X coordinate factor will be decreased in exponential way
HeightNumber of NodesExponent (2 (height - 1) = number of nodes)X coordinate factor
110NA
221xfactor X (1/2)1
342xfactor X (1/2)2
483xfactor X (1/2)3

Observe the below diagram. Here I have taken X - factor as 300. The nodes were not overlapped because of exponential decay in distance.
Read More
Google launched new reCaptcha for effective detection of robots. Every day hackers decrypting captchas. It became difficult for organizations to get protection from bots. Google has given solution to this problem with new reCaptcha. In this article, I am going to explain the implementation of reCaptcha with Java

How reCaptcha Works

  1. Developer has to register their website for Google recaptcha. Then developer will get application key.
  2. Developer has to integrate reCaptcha with registered website.
  3. Whenever user clicks on "I am not a robot, Google reCaptcha script will generate input value with name g-recaptcha-response
  4. Whenever user submits the form, The website server receives code with parameter recaptcha-response.
  5. Now developer has to verify the code at server side by sending one get request to google recaptcha server with application secret key.

Libraries

Get Google GSON Java Library to handle JSON responses.

Get reCaptcha Key

Click here to register your website and get key for your web application
Get key
Here Site key is open, any one can see. Site key will be used in the script of HTML page. Secret key is for only application developer and it is for contacting google server side validation.

HTML Code

Add google reCaptcha script

<script src='https://www.google.com/recaptcha/api.js'></script>

Add reCaptcha DIV

Google script will add input field to this div
<div class="g-recaptcha" data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

Observe below HTML code

In this below HTML google reCaptcha DIV was enclosed by form. Whenever user clicks on submit button reCaptcha input field will be submitted along with form input fields.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google New reCaptcha using Java</title>
</head>
<script src='https://www.google.com/recaptcha/api.js'></script>
<style type='text/css'>
.field {
    padding: 0 0 10px 0;
}

.label {
    padding: 3px 0;
    font-weight: bold;
}
</style>

<body>
    <div style="text-align: center">
        <h1>Google reCaptcha using Java</h1>
    </div>
    <div style="width: 400px; margin: auto">
        <form action="HandleRecaptcha">
            <h3>Registration Form</h3>
            <div class="field">
                <div class="label">Enter Name</div>
                <input value="" name="name" />
            </div>

            <div class="field">
                <div class="label">Enter Email</div>
                <input name="email" />
            </div>

            <div class="g-recaptcha"
                data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

            <div class="field">
                <input type="submit" value="submit" />
            </div>

        </form>
    </div>
</body>
</html>

Java Code

CaptchaResponse.java

Pojo class to handle JSON Response
public class CaptchaResponse {
    public boolean success;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}

HandleRecaptcha.java

Once user clicks on submit button, form data will be submitted to Server. Now get g-recaptcha-response parameter value. 
String recap = request.getParameter("g-recaptcha-response");
Now verify the g-recaptcha-response with Google server using your application secret key.
URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println(outputString);
Now convert the response into Java Object and verify whether the input is from robot or human
CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
if(capRes.isSuccess()) {
    // your logic - Human
} else {
    // your logic - Robot
}
Complete servlet code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

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

import com.google.gson.Gson;

public class HandleRecaptcha extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String secretParameter="Your Application Secret Code Here";
       
    public HandleRecaptcha() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Get input parameter values (form data)
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String recap = request.getParameter("g-recaptcha-response");
        
        // Send get request to Google reCaptcha server with secret key  
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        String line, outputString = "";
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            outputString += line;
        }
        System.out.println(outputString);
        
        // Convert response into Object
        CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        
        // Verify whether the input from Human or Robot 
        if(capRes.isSuccess()) {
            // Input by Human
            request.setAttribute("verified", "true");   
        } else {
            // Input by Robot
            request.setAttribute("verified", "false");
        }
        request.getRequestDispatcher("/response.jsp").forward(request, response);
    }

}
Read More
In this article, I am going to explain how to search excel sheet using java. To implement this program you need to download Apache POI library and have it in your build path (copy POI jars to lib folder).
There is no direct method to search excel sheet using java. You need to follow the below flow.

Flow of the program


  1. Get Excel files
  2. Get Work Book of the excel files
  3. Get sheets of the workbook 
  4. Iterate rows
  5. Iterate columns
  6. Compare column value based on its type
  7. Return all filtered rows

Java Code to Search Excel Sheet

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class SearchExcel {
    public static void main(String[] args) {
        try {
            // excel files
            FileInputStream excellFile = new FileInputStream(new File(
                    "C:\\excel1.xlsx"));
            
            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(excellFile);
            
            // Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
            
            // add sheet2 to sheet1
            ArrayList<Row> rows = searchSheet("Srinivas", sheet);
            System.out.println("filtered rows : \n"+rows);
            excellFile.close();

            System.out
                    .println("Files were searched successfulyy ");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
        
    public static ArrayList<Row> searchSheet(String searchText, XSSFSheet sheet) {
        // This parameter is for appending sheet rows to mergedSheet in the end
        
        Double doubleValue = null;
        Boolean booleanValue = null;
        ArrayList<Row> filteredRows = new ArrayList<Row>();

        //Get double value if searchText is double
        try {
            doubleValue = Double.parseDouble(searchText);
        } catch(Exception e) {  
        }
        
        //Get boolean value if searchText is boolean
        try {
            booleanValue = Boolean.parseBoolean(searchText);
        } catch(Exception e) {  
        }
        
        //Iterate rows
        for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {

            XSSFRow row = sheet.getRow(j);
           
            //Iterate columns
            for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                XSSFCell cell = row.getCell(k);
            
               //Search value based on cell type
               switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if(doubleValue != null && doubleValue.doubleValue() == cell.getNumericCellValue()) {
                        filteredRows.add(row);
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    if(searchText != null && searchText.equals(cell.getStringCellValue())) {
                        filteredRows.add(row);
                    }
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    if(booleanValue != null && booleanValue.booleanValue() == cell.getBooleanCellValue()) {
                        filteredRows.add(row);
                    }
                    break;
                default:
                    if(searchText != null && searchText.equals(cell.getStringCellValue())) {
                        filteredRows.add(row);
                    }
                    break;
                }
            }
        }
        return filteredRows;
    }

}
Read More
In this article, I am going explain the simple way to make GUI with Eclipse editor. Eclipse have some wonderful plugins to decrease GUI coders effort. You need to install WindowBuilder plugin with some toolkits.

Install plugin

Goto Menu > Help > Install New Software > Click on 'Work with' drop down and select appropriate URL based on your eclipse version

example :

Helios - http://download.eclipse.org/releases/helios
Indigo - http://download.eclipse.org/releases/indigo
Juno - http://download.eclipse.org/releases/juno
Kepler - http://download.eclipse.org/releases/kepler

Now Eclipse will filter all plugins under this release. Expand 'General Purpose Tools'. Select all WindowBuilder items and Swing Designer and SWT items. Cick on finish.

These plugins will be installed.

Create New Application Window java  class file

Create new project and create new package.
Right click on that package > New Other > Select Application Window under Swing Designer > Click Next and give some name > Click Finish

Working with GUI components

Open the created Java file
Switch it to design view
There you can see lot of GUI components ready to use. If you want to add any component, just select that and add it to present panel.
You can generated event handlers functions by right clicking on components >Add Event Handler > required action

Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts