Encoding and Decoding in Java

Encoding and Decoding of String in Java using base64 is extremely easy if you are using Apache commons code open source library.
It provides convenient static utility method
  • Base64.encodeBase64(byte[]) 
  • Base64.decodeBase64(byte []) 
for converting binary data into base64 encoded binary Stream and than decoding back from encoded data in base64 encoding mechanism.
How to Encoding and Decoding in Java,Encoding and Decoding in Java,Decoding in Java,base 64 in java,base 64 encoding,base 64 decoding,base64 encoding in java,base64 decoding in java,base64 encoding and decoding in java

To encode a String with Base64 one should perform the following steps:
  1. Create a String.
  2. Get the bytes from the String, using getBytes() API method of String.
  3. Use encodeBase64(byte[] binaryData) method of org.apache.commons.codec.binary.Base64 to encode the byte array using the base64 algorithm.
  4. Store byte encoded array in String by new String(binaryData).
  5. And Print that string as encoded value.
String orig = "Author of GeekOnJava is Sawan";

        //encoding  byte array into base 64
        byte[] encoded = Base64.encodeBase64(orig.getBytes());     
      
        System.out.println("Original String: " + orig );
        String encodedString=new String(encoded);
        System.out.println("Base64 Encoded String : " + encodedString);
To decode a String with Base64 one should perform the following steps:

  1. Get encoded string.
  2. Use decodeBase64(encoded.getBytes()) method of org.apache.commons.codec.binary.Base64 to decode the byte array using the base64 algorithm.
  3. Store byte encoded array in String by new String(binaryData).
  4. And Print that string as decoded value.
 byte[] byteArray = Base64.decodeBase64(encodedString.getBytes());
        String decodedString = new String(byteArray);
         System.out.println(encodedString + " = " + decodedString);

 Note : You need to download Base64 jar file from here.
Full code given below :
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;


public class Encoding{
 /**
  * @author Sawan
  * @Reference http://geekonjava.blogspot.com
  * @param args
  * @throws IOException
  */
    public static void main(String args[]) throws IOException {
        String orig = "Author of GeekOnJava is Sawan";

        //encoding  byte array into base 64
        byte[] encoded = Base64.encodeBase64(orig.getBytes());     
      
        System.out.println("Original String: " + orig );
        String encodedString=new String(encoded);
        System.out.println("Base64 Encoded String : " + encodedString);
        
        byte[] byteArray = Base64.decodeBase64(encodedString.getBytes());
        String decodedString = new String(byteArray);
         System.out.println(encodedString + " = " + decodedString);

      
        
    }
}

Output :
Original String: Author of GeekOnJava is Sawan
Base64 Encoded String : QXV0aG9yIG9mIEdlZWtPbkphdmEgaXMgU2F3YW4=
QXV0aG9yIG9mIEdlZWtPbkphdmEgaXMgU2F3YW4= = Author of GeekOnJava is Sawan


Thank for appreciation by comments .

Convert Speech into Text in Android

Hello friends i am telling you how to convert speech into text in android. In this example you can see what  you speak it'll show on textview.
how to Convert Speech into Text in Android,Convert Speech into Text in Android,Speech into Text in Android,Text in Android,

You would see the google search apps where you can search anything by speak. Its work as given below you can be take a reference to make a new android apps where you can be add speak recognition capabilities.
MainActivity.java
package com.blogspot.geekonjava.speechtotextdemo;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 protected static final int RESULT_SPEECH = 1;

 private ImageButton btnSpeak;
 private TextView txtText;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  txtText = (TextView) findViewById(R.id.txtText);

  btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

  btnSpeak.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {

    Intent intent = new Intent(
      RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

    try {
     startActivityForResult(intent, RESULT_SPEECH);
     txtText.setText("");
    } catch (ActivityNotFoundException a) {
     Toast t = Toast.makeText(getApplicationContext(),
       "Ops! Your device doesn't support Speech to Text",
       Toast.LENGTH_SHORT);
     t.show();
    }
   }
  });

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  switch (requestCode) {
  case RESULT_SPEECH: {
   if (resultCode == RESULT_OK && null != data) {

    ArrayList<String> text = data
      .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

    txtText.setText(text.get(0));
   }
   break;
  }

  }
 }
}

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
If you want a example code them comment me i'll provide you soon.

Save Tabular PDF into TXT using java

Here i am telling you how to save your tabular form of pdf into text file as in pdf format like tabular.
Generally when we do it all the pdf format get worst and all data are compressed form where we've problem to extract the data from it.
But you can be do it with great and pleasure ways.
Before run you need to implement jar files :

  • PDFTextStream.jar
  • commons-io-2.4.jar
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package extracttextallpages;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.IOException;
import com.snowtide.pdf.VisualOutputTarget;
import com.snowtide.pdf.PDFTextStream;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class FCDemo extends JFrame
{
   JFileChooser fc = new JFileChooser();

   public FCDemo(String title)
   {
      super(title);
      setDefaultCloseOperation(EXIT_ON_CLOSE);

      JPanel pnl = new JPanel();
      pnl.setLayout(new GridLayout(2, 1));

      JButton btn = new JButton("Open PDF file");
      ActionListener al;
      al = new ActionListener()
           {
              @Override
              public void actionPerformed(ActionEvent ae)
              {
                 switch (fc.showOpenDialog(FCDemo.this))
                 {
                    case JFileChooser.APPROVE_OPTION:
                       JOptionPane.showMessageDialog(FCDemo.this, "File Saved at D:/geekonjava.txt"
                                                     ,
                                                     "FCDemo",
                                                     JOptionPane.OK_OPTION);
                     try
                     {
                       File file = new File("D:/geekonjava.txt");
        String pdfFilePath = fc.getSelectedFile().toString();
        PDFTextStream pdfts = new PDFTextStream(pdfFilePath); 
        StringBuilder text = new StringBuilder(1024);
        pdfts.pipe(new VisualOutputTarget(text));
        pdfts.close();
        System.out.printf("The text extracted from %s is:", pdfFilePath);
        System.out.println(text);
        FileUtils.writeStringToFile(file,text.toString());
                     }
                     catch(Exception e)
                     {
                         System.out.println(e);
                     }
                       
                       
                       
                       break;

                    case JFileChooser.CANCEL_OPTION:
                       JOptionPane.showMessageDialog(FCDemo.this, "Cancelled",
                                                     "FCDemo",
                                                     JOptionPane.OK_OPTION);
                       break;
                 
                    case JFileChooser.ERROR_OPTION:
                       JOptionPane.showMessageDialog(FCDemo.this, "Error",
                                                     "FCDemo",
                                                     JOptionPane.OK_OPTION);
                 }
              }
           };
      btn.addActionListener(al);
      pnl.add(btn);

      

      setContentPane(pnl);

      pack();
      setVisible(true);
   }

   public static void main(String[] args)
   {
      Runnable r = new Runnable()
                   {
                      @Override
                      public void run()
                      {
                         new FCDemo("FileChooser Demo");
                      }
                   };
      EventQueue.invokeLater(r);
   }
}

Example :

PDF format like below image
how to Save Tabular PDF into TXT using java,Save Tabular PDF into TXT using java,Tabular PDF into TXT using java,PDF into TXT using java,TXT using java,pdf to txt in java,extract data from pdf to txt in java
After converting the pdf into txt format it'll show like below image :
how to Save Tabular PDF into TXT using java,Save Tabular PDF into TXT using java,Tabular PDF into TXT using java,PDF into TXT using java,TXT using java,pdf to txt in java,extract data from pdf to txt in java


Find Geolocation on Google Map using Javascript

Hello friends i told you about how to find geolocation using javascript. After that i am giving you a new stuff for your application and in this tutorial you can see your location on google map using geolocation in javascript.
Just check out below code:

GeolocationwithGoogleMap.html
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position:</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }

function showPosition(position)
  {
  var latlon=position.coords.latitude+","+position.coords.longitude;

  var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
  +latlon+"&zoom=14&size=400x300&sensor=false";
  document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
  }

function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
</script>
</body>
</html>
Thank you for your appreciation.

Find Geolocation from JavaScript

Hello friends, today i am telling you how to find your location using javascript using geolocation.Its just a javascript which you can use in your jsp or php or asp projects.
It fullfill of your need you just need to copy the below code and run on your browser.

geolocation.html
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
  }
</script>
</body>
</html>
Thank you for your appreciation.

Get Share Count from Facebook, Twitter and Google Plus

Hello friends today i am telling you how to get share count for Facebook, Twitter and Google Plus.
The social media share count is basically the number of times a webpage was shared on a certain social media.Getting the number of share for each of the main 3 social media is done using JSON calls to the API each of those social media provide.

Get Share Count from Facebook, Twitter and Google Plus,How to Get Share Count from Facebook, Twitter and Google Plus,Share Count from Facebook, Twitter and Google Plus,Count from Facebook, Twitter and Google Plus,


Facebook Share Count 
This function will return a string with the number of time the URL was shared.
function GetFacebookShares($url) {
  $json_string = file_get_contents(‘http://graph.facebook.com/?ids=’ . $url);
  $json = json_decode($json_string, true);
  return intval( $json[$url]['shares'] );
}
Check Demo

Twitter Share Count
This function will return a string with the number tweets for a certain URL.
function GetTwitterTweets($url) {
$json_string = file_get_contents(‘http://urls.api.twitter.com/1/urls/count.json?url=’ . $url);
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
Check Demo

Google Plus Share Count
This function will return a string with the number of times the URL was shared.
function GetGooglePlusShares($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, “https://clients6.google.com/rpc”);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, ‘[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]‘);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘Content-type: application/json’));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}
Hope the above code can help you solve your problem, if you have any comment please don’t hesitate, you can use the comments below or the contact us page.

MySql dump for Countries and States

As part of a recent project, I needed to compile a list of every country and first level administrative subdivision in the world. I started with the ISO 3166-2 list, but later cleaned up certain countries that had inaccurate data. I also needed timezones for every state, so I put all of those in as well.



Read this tutorial Get Countries data in MySql, JSON and XML

Download Mysql dump for Countries and States





This the MySQL dump file contains the list of all country and state respectively,
for that just create the database and import the file

Make Speech Recognition website

Hello friends today i am telling you how to take power of speech recognition to your website and cool stuff for you.
Thats name is Annyang.
annyang plays nicely with all browsers, progressively enhancing browsers that support Speech-recognition, while leaving users with older browsers unaffected.

Facebook with Speech Recognition. you just say reply and message sent or just say to like or share a post and its get done.
You just need to add few lines of code .so its quite easy i say.
<script src="//cdnjs.cloudflare.com/ajax/libs/annyang/0.2.0/annyang.min.js"> </script> 
<script> 
if (annyang) 
 { 
  /* Let's define our first command. First the text we expect, and then the function it should call */ 
  var commands = 
  { 
   'show tps report': function() 
    { 
     $('#tpsreport').animate({bottom: '-100px'}); 
    } 
  }; 
  // Initialize annyang with our commands annyang.init(commands); 
  /* Start listening. You can call this here, or attach this call to an event, button, etc. */ 
  annyang.start(); 
 } 
</script>

Here are some sample commands that you might wanna try to get started

  • Say "Show me cute kittens!"
  • Say "Show me Arches National Park!"
  • Now go wild. Say "Show me…" and make your demands!


I hope you liked this JavaScript and Try to Implement this. please Don't forget to share because its cool :)