Sunday, October 7, 2012

Java program to save a given URL into a file

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Program to save web page in a file
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class SaveWebPage {

 /**
  * @param args
  */
 public static void main(String[] args) {
  if (args.length != 2) {
   System.out.println("Please provide valid arguments");
   return;
  }

  try {
   URL url = new URL(args[0]);
   BufferedReader br = new BufferedReader(new InputStreamReader(
     url.openStream()));
   BufferedWriter bw = new BufferedWriter(new FileWriter(args[1]));

   String input = "";
   while ((input = br.readLine()) != null) {
    bw.write(input);
    bw.newLine();
   }

   bw.close();
   br.close();
   System.out.println("Web page written successfully.");
  } catch (MalformedURLException e) {
   System.out.println("Error occured : " + e.getMessage());
  } catch (IOException e) {
   System.out.println("Error occured : " + e.getMessage());
  }
 }

}

Run this program as follows :

sahir@sahir-laptop:~/networklab$ javac SaveWebPage.java
sahir@sahir-laptop:~/networklab$ java SaveWebPage http://www.kotiasolutions.com/services.html services.txt
Web page written successfully.
sahir@sahir-laptop:~/networklab$

Java program to print parts of given URL

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Program to print all the parts of the given url
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class URLParts {

 /**
  * @param args
  */
 public static void main(String[] args) {
  if (args.length != 1) {
   System.out.println("Please provide valid arguments");
   return;
  }
  try {
   URL url = new URL(args[0]);
   System.out.println("====== Given URL is : " + args[0] + " ======");
   System.out.println("Protocol : " + url.getProtocol());

   // if port not specified as part of url, getting default port
   int port = url.getPort() == -1 ? url.getDefaultPort() : url
     .getPort();
   System.out.println("Port : "
 + port);
   System.out.println("Host : " + url.getHost());
   System.out.println("Path : " + url.getPath());
   System.out.println("File Name : " + url.getFile());
   System.out.println("Query : " + url.getQuery());
  } catch (MalformedURLException e) {
   System.out.println(e.getMessage());
  }

 }

}

Run this program as follows :

sahir@sahir-laptop:~/networklab$ javac URLParts.java
sahir@sahir-laptop:~/networklab$ java URLParts http://www.kotiasolutions.com/services.html?service=web
====== Given URL is : http://www.kotiasolutions.com/services.html?service=web ======
Protocol : http
Port : 80
Host : www.kotiasolutions.com
Path : /services.html
File Name : /services.html?service=web
Query : service=web
sahir@sahir-laptop:~/networklab$


Simple nslookup java clone

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Program to perform simple functionality of NSLookUp (simple nslookup clone)
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class NSLookup {

 /**
  * @param args
  */
 public static void main(String[] args) {
  if (args.length != 1) {
   System.out.println("Please provide valid arguments");
   return;
  }

  try {
   InetAddress ipaddress = InetAddress.getByName(args[0]);
   System.out.println("Name : " + ipaddress.getHostName());
   System.out.println("Address : " + ipaddress.getHostAddress());
  } catch (UnknownHostException e) {
   System.out.println("Error occured : " + e.getMessage());
  }
 }

}

Run this program as follows:

sahir@sahir-laptop:~/networklab$ javac NSLookup.java
sahir@sahir-laptop:~/networklab$ java NSLookup google.com
Name : google.com
Address : 74.125.236.163
sahir@sahir-laptop:~/networklab$ java NSLookup 74.125.236.163
Name : maa03s16-in-f3.1e100.net
Address : 74.125.236.163
sahir@sahir-laptop:~/networklab$

Java program to find the whether given IP is IPv4 or IPv6

import java.util.regex.Pattern;

/**
 * Program to find whether given ip is IPv4 or IPv6 address
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class IPType {

 private static final String IPv4 = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
 private static final String IPv6 = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";

 /**
  * @param args
  */
 public static void main(String[] args) {
  if (args.length != 1) {
   System.out.println("Please provide IP address as argument");
   return;
  }
  String ipaddress = args[0];
  
  Pattern ipv4 = Pattern.compile(IPv4);
  Pattern ipv6 = Pattern.compile(IPv6);
  if (ipv4.matcher(ipaddress).matches()) {
   System.out.println("Given IP Address : " + ipaddress + " is IPv4");
   return;
  } else if (ipv6.matcher(ipaddress).matches()) {
   System.out.println("Given IP Address : " + ipaddress + " is IPv6");
   return;
  } else {
   System.out.println("Given string is an invalid IP address");
  }
 }

}

Run this program as follows :

sahir@sahir-laptop:~/networklab$ javac IPType.java
sahir@sahir-laptop:~/networklab$ java IPType 192.168.1.1
Given IP Address : 192.168.1.1 is IPv4
sahir@sahir-laptop:~/networklab$ java IPType 0000:ffff:1234:4567:0000:4321:4567:ffff
Given IP Address : 0000:ffff:1234:4567:0000:4321:4567:ffff is IPv6
sahir@sahir-laptop:~/networklab$

Java program to find all IP addresses of given Host

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Program to print all ip addresses of given domain
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class FindIP {

 /**
  * @param args
  */
 public static void main(String[] args) {
  if (args.length != 1) {
   System.out.println("Please provide a valid input");
   return;
  }
  try {
   InetAddress[] ipaddresses = InetAddress.getAllByName(args[0]);

   for (InetAddress ip : ipaddresses)
    System.out.println(ip.getHostAddress());
  } catch (UnknownHostException e) {
   System.out.println("Error occured : " + e.getMessage());
  }
 }

}

Run the program as follows:

sahir@sahir-laptop:~/networklab$ javac FindIP.java
sahir@sahir-laptop:~/networklab$ java FindIP google.com
74.125.236.163
74.125.236.164
74.125.236.165
74.125.236.166
74.125.236.167
74.125.236.168
74.125.236.169
74.125.236.174
74.125.236.160
74.125.236.161
74.125.236.162
2404:6800:4007:802:0:0:0:100e
sahir@sahir-laptop:~/networklab$

Java Program to find Computer name, IP Address and list all network interfaces

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;

/**
 * Program to display current computer name, IP Address and network interfaces
 * 
 * @author sahir maredia (Kotia Solutions)
 * 
 */
public class ComputerName {

 /**
  * @param args
  */
 public static void main(String[] args) {
 try {

  InetAddress ipaddress = InetAddress.getLocalHost();
  System.out.println("Computer Host Name : "
    + ipaddress.getHostName());
  System.out.println("IP Address of Localhost : "
    + ipaddress.getHostAddress());

  // getting list of network interfaces
  Enumeration<NetworkInterface> interfaces = NetworkInterface
    .getNetworkInterfaces();

  System.out.println();
  System.out
    .println("================ Following are the available network interfaces ===============");
  System.out.println();
  if (interfaces == null) {
   System.out.println("No network interfaces found");
  } else {

   for (NetworkInterface netIf : Collections.list(interfaces)) {
    System.out.println("Display Name : "
      + netIf.getDisplayName());
    System.out.println("Name : " + netIf.getName());
    System.out.println();
   }
  }
 } catch (UnknownHostException ex) {
  System.out.println("Error Occured : " + ex.getMessage());
 } catch (SocketException e) {
  System.out.println("Error Occured : " + e.getMessage());
 }
 }

}

Run the program as follows :

sahir@sahir-laptop:~/temp/networklab$ javac ComputerName.java
sahir@sahir-laptop:~/temp/networklab$ java ComputerName
Computer Host Name : sahir-laptop
IP Address of Localhost : 127.0.1.1

================ Following are the available network interfaces ===============

Display Name : wlan0
Name : wlan0

Display Name : lo
Name : lo

sahir@sahir-laptop:~/temp/networklab$

Saturday, October 6, 2012

Add Custom Application to Ubuntu Dashboard

To add a custom application icon to Ubuntu dashboard, create a file with name AppName.desktop in ~/.local/share/applications Put Following into that file

[Desktop Entry]
Name=Application Name
Comment=Application Description
Exec=<path to executable;>
Icon=<path to application icon>
Terminal=false
Type=Application
StartupNotify=true
Keywords=<some keywords>

Friday, January 13, 2012

Monday, January 9, 2012

URL to add facebook Page Tab

http://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&display=popup&next=REDIRECT_URI

Update - We can also use this url

<a href="http://facebook.com/add.php?api_key=YOUR_APP_KEY&pages=1&page=YOUR_PAGE_ID" target="_blank">PAGE NAME</a>

Sunday, January 8, 2012

Making Admin Panel using YIi Framework

Recently, I have started coding in PHP. After coding for 2 -3 weeks, I started missing all those wild cards that frameworks provided me while coding in Java. All the basics things required in any project are taken care by those frameworks. We just need to configure and things are ready.
This magic of getting things easily made me to search for frameworks in PHP. Earlier, I have used Joomla and Code Igniter(CI). I believe Joomla is great CMS, but using it for any other purposes does not give me flexibility. Code Igniter, I used it long long ago. I came across article saying CI vs Yii vs Kohana. This comparison interested me to use Yii Framework. I found the documentation to be good and also community is good. I have started using this framework. I like the Active Record support which fills the space of hibernate framework.
First thing I started with is to create a admin panel. I got a very good link through google. It explains all and we can easily create Joomla kind of admin panel in our applications.
Link to tutorial : http://bit.ly/wCDLab

Saturday, December 31, 2011

Configure Database Server LoginModule Realm in Jboss AS 7

If we want to do a Database login for JavaEE6 application, We need to configure the DatabaseServerLoginModule of Jboss by creating a Realm. Put following lines in standalone.xml ( or domain.xml) :

 
   
    
          
               
               
               
               
               
          
     
  


Replace values with your respected values. If you are using custom database module class replace code="Database" with code="<your class name>"
Now the realm is configured into server, We need to tell our application to use this realm. This can be achieved using web.xml

 
  FORM
  MyRealm
  
   /login.jsp
   /loginerror.jsp
  
 
 
  SuperAdmin
 
 
  Admin
 
 
  Manager
 
 
  Employee
 
From lines 1 to 8 we inform the application to make use of FORM method to authenticate users with Realm MyRealm and also provide the login and error pages.
Next we need to declare the security roles in the application. We have declared 4 roles SuperAdmin, Admin, Manager and Employee from lines 9 to 20.
Now we have configured the application we will add security constraint in web.xml to our application as below.

  
   MyApplication
   /administration/*
   GET
   POST
  
  
   SuperAdmin
   Admin
  
 
 
  
   Unprotected area
   /resources/*
  
 
We added two security constraints. First is to allow only SuperAdmin and Admin to enter the admin panel. Another example is when you have protected entire site but want to allow access to resources to all.

11 Things every Software Developer should be doing in 2012.

Saturday, December 24, 2011

JPA Performance, Don't Ignore the Database

http://weblogs.java.net/blog/caroljmcdonald/archive/2009/08/28/jpa-performance-dont-ignore-database-0

Friday, December 16, 2011

Install Postgresql 9.1 in Ubuntu 9.04

first install python-software-properties:
sudo apt-get install python-software-properties

now add repository and update apt.
sudo add-apt-repository ppa:pitti/postgresql
sudo apt-get update

now instal postgresql
sudo apt-get install postgresql-9.1 libpq-dev

Now change the postgres user password (still running as root):
su postgres
psql -d postgres -U postgres
alter user postgres with password 'a';
\q

To install GUI client pgsql
sudo apt-get install pgadmin3

original article: http://bit.ly/sUFCgb

How to Accomplish More by Doing Less - Tony Schwartz - Harvard Business Review

How to Accomplish More by Doing Less - Tony Schwartz - Harvard Business Review.

Enable AutoComplete commands in Pinguy OS 11.04

To enable bash completion in interactive shells do following steps:

$ sudo vi /etc/bash.bashrc


uncomment following line in it

# enable bash completion in interactive shells
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi


Restart your terminal and its done!!!

Fix GPG error:....NO_PUBKEY

In Ubuntu, when we try to update the system we sometimes get error for GPG No_PUBKEY as follows:


W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ppa.launchpad.net lucid Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY C1622487AAA521A8

This does no harm as its not a security issue but its very annoying everytime getting the same error. It happens because you don't have a suitable public key for a repository. Follow this steps to get rid of the error:


gpg --keyserver keyserver.ubuntu.com --recv 9BDB3D89CE49EC21

Which retrieves the key from ubuntu key server and then this:


gpg --export --armor 9BDB3D89CE49EC21 | sudo apt-key add -

Which adds the key to apt trusted keys. This will solve you problem.

The solution can be found here & here.

Tuesday, December 13, 2011

Real Java Geeks


Code hard! And get out of your cubicles! Video created for the Community Keynote at JavaOne Brasil.