Pages

Java- extract / unzip a zip file - working code example

How to Extract / unzip a zip file in Java - complete source code example .
import java.io.*;
import java.util.zip.*;

public class UnzipTest {
    public static void unzipFile(File f) throws ZipException, IOException {

        ZipInputStream zin = new ZipInputStream(new FileInputStream(f));
        System.out.println(f.getAbsoluteFile());

        String workingDir = f.getPath() + File.separator + "unziped";

        byte buffer[] = new byte[4096];
        int bytesRead;

Java: using recursion to read a folder and its content in tree format sub-folders/files in tree format

Java CODE: Using recursion to read a folder and its content - sub-folders/files in tree format.

public class TreeTest {
      public static void main(String[] args) {
            showDir(1, new File("D:\\test"));
      }

      static void showDir(int indent, File file) {
            for (int i = 0; i < indent; i++)
                  System.out.print(' ');
            System.out.println(file.getName());
            if (file.isDirectory()) {
                  File[] files = file.listFiles();
                  for (int i = 0; i < files.length; i++)
                        showDir(indent + 4, files[i]);
            }
      }
}

Java : Generate JTree from XML dynamically - code example

In this post, i am going to describe how to generate JTree in swing according to an XML document dynamically.


Used XML File : catalog.xml

Java : Html form parser return map of (name,value) pair of input attribute


Simple HTML Form Parser which parses the given string of HTML and returns Map of  (name,value) pair of form's input attribute.


CODE : MyHtmlFormParser class

Java : Counting frequency of word in a string using Map

Use a Map to map Map<String,Integer> the words with frequency.

String SPACE =" ";
String [] words = input.split(SPACE);
Map<String,Integer> frequency = new HashMap<String,Integer>();
for (String word:words){
    Integer f = frequency.get(word);
    frequency.put(word,f+1);
}

Then you can find out for a particular word with:
frequency.get(word);

Java: ping an URL from java application - code example

The code to ping a URL from java application is as follows :


public static void pingUrl(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
urlConn.connect();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
 


With response time:

public static void pingUrlWithResponseTime(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
final long startTime = System.currentTimeMillis();
urlConn.connect();
final long endTime = System.currentTimeMillis();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Time (ms) : " + (endTime - startTime));
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}

Android: Killing a running process with processid(pid) and package name

After analysis of source code of Android's package manager application, i found forceStopPackage method is used by system image to kill the processes- which uses android.Manifest.permission.FORCE_STOP_PACKAGES permission.  But problem is that this permission is granted only for system level application.

Android: Code for detecting if specific application or service running

For checking a application is running or not :
public static boolean isThisApplicationRunning(final Context context, final String appPackage) {
 if (appPackage == null) {
  return false;
 }
 final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
 final List<RunningAppProcessInfo> runningAppProcesses = manager.getRunningAppProcesses();
 for (final RunningAppProcessInfo app : runningAppProcesses) {
  if (appPackage.equals(app.processName)) {
   return true;
  }
 }
 return false;
}



For checking a service is running or not :
public static boolean isThisServiceRunning( final Context context, final String servicePackageName) {
 final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
 for (final RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  if (servicePackageName.equals(service.service.getClassName())) {
   return true;
  }
 }
 return false;
}



Required Permission :
 <uses-permission android:name="android.permission.GET_TASKS" />

Android code for reading phone contacts detail

Here is code for reading all phone contacts(phone number,  email etc with their type) stored in android phone programmatically.

Android Reading Call Log from Phone Programmatically

Here is the code to read all call log data (MISSED, OUTGOING, INCOMING) from android phone programmatically.

Permission in AndroidManifest.xml:
Add the READ_CONTACTS permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />

Code :

Calling JavaScript Function from Android and Handling Result

In this tutorial I am going to describe JavaScriptInterface  for Calling Android Function from JavaScript i.e., JavaScript Binding to Android.

Setting up WebView
First add JavaScriptInterface to webView as follows. Here "MyAndroid" will be used later to call functions in JavaScriptInterface later.

google adsense payment in nepal - western union quick cash

Google recommend  Electronic Fund Transfer (EFT)   as a faster and more reliable form of payment. But, EFT are currently only available to a limited number of countries. Which doesn't include Nepal. So we have the only good option : Western Union Quick Cash.

Receiving payments by Western Union Quick Cash:

Western Union Quick Cash is a payment method that allows you to receive your AdSense payments in cash using the worldwide Western Union money transfer service. Payments will be available for pick up at your local Western Union Agent the day after they are sent according to our normal payment schedule.
Your Western Union Quick Cash payment will be made in US dollars. Conversion rates will be calculated according to the rate used by the Western Union Agent on the day you pick up your payment.

Steps :

1) Setup Google Adsense payment to Western Union Quick Cash:


  1. Sign in to your account at www.google.com/adsense.
  2. Visit the Home tab and click Account settings in the left hand panel.
  3. Click 'edit payment method' under the 'Payment settings' header.
  4. Select the Western Union Quick Cash radio button.
  5. Click Continue.
  6. Click Save changes to save your payment type.

2) Picking up WU payment

In order to pick up your payment by Western Union Quick Cash, please complete the following steps:
  1. Find a Western Union Agent located in the country where your payments are sent.
  2. Call the Western Union Agent to confirm that they offer the Quick Cash service.
  3. Bring the following information with you:

    - a valid government-issued photo ID (Passport, Driver's license, National ID etc)
    - sender's information: To determine which sender's information you should bring to your WU branch, please check the 'details' link on the payment line of your Payments page.
    • Google Inc. 1600 Amphitheatre Parkway, Mountain View, California 94043, USA. Phone Number:  650-253-4000     
    - amount of your payment, which you can find on your Payment History page
    - your unique MTCN (Money Transfer Control Number) which you can find by clicking on the 'details' link next to the Payment Issued line on your Payment History page
Hurrahs ------- Lets have a party ... 

java find path of current executing jar

Best solution : 
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
You can use your own class name instead of 'Test'