Friday 30 November 2012

Java Collections Interfaces Hierarchy


Collection Hierarchy

After knowing the meaning and purpose of Collections framework, let us know the basic interfaces, derived classes and their properties. Java data structures are nothing but subclasses of Collection and Map interfaces. Following hierarchy gives all the interfaces of Collections framework.


Fig: Basic interfaces of collections framework

Map and SortedMap form a separate hierarchy and not connected with Collection interface. Bu still, they are part of collections framework. It is done so to get interoperability with collections and legacy classes. Observe, interfaces Map and SortedMap are not derived from Collection interface. Collection being at the top of the hierarchy, it gives generic methods for all the derived classes.
Note: Framework name is collections and the interface name is Collection. Do not get confused; later, we get one more class called Collections.
Description of fundamental interfaces
A table is given showing the core interfaces with their implemented classes with brief description.
Interface Brief Description Derived Classes
Collection It forms the root interface and comes with methods that define basic operations and makes all DS as one unit (called by a common name) Majority of all DS come under this interface
Set Subclasses of this interface have a common feature of not allowing duplicate elements HashSet, LinkedHashSet
SortedSet Subclasses of this interface come with a common feature of printing the elements in ascending order implicitly. Earlier feature derived from Set is allowing only unique elements TreeSet
List Subclasses allow duplicate elements LinkedList, ArrayList, Vector
Map Allows the subclasses to store key/value pairs. Does not allow duplicate keys. HashMap, LinkedHashMap, Hashtable
SortedMap Prints elements in ascending order of keys. A feature derived from Map is it does not allow duplicate keys. TreeMap

Table: Description of Main interfaces

The elements of List can be accessed with their index numbers.
Collection classes store elements of single entities, but Map stores key/value pairs; to store a value, a key must be supplied along. SortedSet and SortedMap print their stored elements in ascending order (known as natural order) by default. The order can be customized explicitly using Comparator interface.
Following figure displays the main interfaces with relation to their derived classes.

As it can be observed, there comes some abstract classes in between interfaces and concrete classes (DS classes). They add some extra features to subclasses other than inherited from interfaces.
Following table gives the properties of derived classes.
Data Structure Interface Duplicates Methods available DS that inherits
HashSet Set Unique elements equals(), hashCode() Hashtable
LinkedHashSet Set Unique elements equals(), hashCode() Hashtable, doubly-linked list
TreeSet SortedSet Unique elements equals(), compareTo() Balanced Tree
ArrayList List Duplicates allowed equals() Resizable array
LinkedList List Duplicate allowed equals() Linked list
Vector List Duplicates allowed equals() Resizable array
HashMap Map Unique keys equals() and hashCode() Hash table
LinkedHashMap Map Unique keys equals() and hashCode() Hash table and doubly-linked list
Hashtable Map Unique keys equals(), hashCode() Hash table
TreeMap SortedMap Unique keys equals(), compareTo() Tree Map

Figure: Collections Features

There are two distinct hierarchies monitored by Collection and Map. Map is also placed in collections framework to have interoperability.
Basic Features of Main Interfaces
Core collection interfaces are the base to Java Collections framework. They include the interfaces Collection, Set, List, Queue and Map on which all the data structures are built.
  1. Collection is the root interface for all the hierarchy (except Map).
  2. Set interface unique feature is that it does not accept duplicate elements. That is, no two elements will be the same.
  3. SortedSet interface is derived from Set interface and adds one more feature that the elements are arranged in sorted order by default.
  4. List interface permits duplicate elements.
  5. Queue interface holds elements and returns in FIFO order.
  6. Map adds the elements in key/value pairs. Duplicate keys are not allowed, but duplicate values are allowed. One key can map one value only.
  7. SortedMap interface is a particular case of Map. Keys are sorted by default

Making HTTP requests(Calling Servlets in GWT)


import com.google.gwt.http.client.*;
...
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
  Request request = builder.sendRequest(null, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
       // Couldn't connect to server (could be timeout, SOP violation, etc.)     
    }

    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
          // Process the response in response.getText()
      } else {
        // Handle the error.  Can get the status text from response.getStatusText()
      }
    }       
  });
} catch (RequestException e) {
  // Couldn't connect to server        
}

SQL Injection


The platform affected can be:
  • Language: SQL
  • Platform: Any (requires interaction with a SQL database)
SQL Injection has become a common issue with database-driven web sites. The flaw is easily detected, and easily exploited, and as such, any site or software package with even a minimal user base is likely to be subject to an attempted attack of this kind.
Essentially, the attack is accomplished by placing a meta character into data input to then place SQL commands in the control plane, which did not exist there before. This flaw depends on the fact that SQL makes no real distinction between the control and data planes.

Examples

Example 1

In SQL:
select id, firstname, lastname from authors
If one provided:
Firstname: evil'ex
Lastname: Newman
the query string becomes:
select id, firstname, lastname from authors where forename = 'evil'ex' and surname ='newman'
which the database attempts to run as 
Incorrect syntax near il' as the database tried to execute evil. 
A safe version of the above SQL statement could be coded in Java as:
String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");
// FIXME: do your own validation to detect attacks
String query = "SELECT id, firstname, lastname FROM authors WHERE forename = ? and surname = ?";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, firstname );
pstmt.setString( 2, lastname );
try
{
 ResultSet results = pstmt.execute( );
}

Example 2

The following C# code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user.
 ...
 string userName = ctx.getAuthenticatedUserName();
 string query = "SELECT * FROM items WHERE owner = "'" 
     + userName + "' AND itemname = '"  
     + ItemName.Text + "'";
 sda = new SqlDataAdapter(query, conn);
 DataTable dt = new DataTable();
 sda.Fill(dt);
 ...
The query that this code intends to execute follows:
 SELECT * FROM items
 WHERE owner = 
 AND itemname = ;
However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string "name' OR 'a'='a" for itemName, then the query becomes the following:
 SELECT * FROM items
 WHERE owner = 'wiley'
 AND itemname = 'name' OR 'a'='a';
The addition of the OR 'a'='a' condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
 SELECT * FROM items;
This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the items table, regardless of their specified owner.

Example 3

This example examines the effects of a different malicious value passed to the query constructed and executed in Example 1. If an attacker with the user name hacker enters the string "hacker'); DELETE FROM items; --" for itemName, then the query becomes the following two queries:
 SELECT * FROM items 
 WHERE owner = 'hacker'
 AND itemname = 'name';

 DELETE FROM items;

 --'
Many database servers, including Microsoft® SQL Server 2000, allow multiple SQL statements separated by semicolons to be executed at once. While this attack string results in an error in Oracle and other database servers that do not allow the batch-execution of statements separated by semicolons, in databases that do allow batch execution, this type of attack allows the attacker to execute arbitrary commands against the database.
Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder of the statement is to be treated as a comment and not executed. In this case the comment character serves to remove the trailing single-quote left over from the modified query. In a database where comments are not allowed to be used in this way, the general attack could still be made effective using a trick similar to the one shown in Example 1. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a", the following three valid statements will be created:
 SELECT * FROM items 
 WHERE owner = 'hacker'
 AND itemname = 'name';

 DELETE FROM items;

 SELECT * FROM items WHERE 'a'='a';
One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. Whitelisting can be a very effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:
  • Target fields that are not quoted
  • Find ways to bypass the need for certain escaped meta-characters
  • Use stored procedures to hide the injected meta-characters
Manually escaping characters in input to SQL queries can help, but it will not make your application secure from SQL injection attacks.
Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to protect against many others. For example, the following PL/SQL procedure is vulnerable to the same SQL injection attack shown in the first example.
 procedure get_item (
  itm_cv IN OUT ItmCurTyp,
  usr in varchar2,
  itm in varchar2)
 is
  open itm_cv for ' SELECT * FROM items WHERE ' ||
    'owner = '''|| usr || 
    ' AND itemname = ''' || itm || '''';
 end get_item;
Stored procedures typically help prevent SQL injection attacks by limiting the types of statements that can be passed to their parameters. However, there are many ways around the limitations and many interesting statements that can still be passed to stored procedures. Again, stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks.

Thursday 29 November 2012

gwt-jsonmaker


Features:

1. Converts Java Beans into json string and vice versa. Java Beans can have objects of other beans as well.
2. Support for all the collections classes like ArrayList, HashMap, HashSet, Vectors etc. and Arrays.
3. Support for Date objects i.e. they can be used directly in the beans
4. Support for annotations
a. @Transient: To not include a field during serialization
b. @Required: To ensure that json contains a field before it can be converted to an object
c. @Notnull: To ensure that if a field is null, serialization stops with an exception
d. @PropName: To provide alias for a property during serialization
5. Can serialize/de-serialize native supported types and their collections out of the box i.e. without the need of creation of Jsonizer interfaces.Details
Projects using Jsonmaker
Getting Started:
1. add the following line in your [project].gwt.xml file
    <inherits name="org.jsonmaker.gwt.Gwt_jsonmaker" />
2. Make a bean class e.g. Person
3. Make an interface with same name as bean class and 'Jsonizer' appended to it e.g. PersonJsonizer. Make it extend the Jsonizer interface. This interface can be made in the bean as well.
4.To jsonize a bean, create an instance of its Jsonizer using GWT.create() method and call asString method on it
5. To de-jsonize a json string of a bean, use JsonizerParser.parse(jsonizer_instance, jsonString).
Below is the example code block The Person bean without jsonizer declaration in its body
// a Person bean class.
class Person{
  ...
  public String getName(){...}
  public void setName(String name){...}
  ...
  public int getAge(){...}
  public void setAge(int age){...}
}
and jsonizer implemented in separate java file
/**
 * If you want to jsonize it, you need to implement an extension of 
 * Jsonizer interface using bean name suffixed with the 'Jsonizer' keyword.
 */
public interface PersonJsonizer extends Jsonizer{}
The jsonizer can alternatively be defined within Person class
// a Person bean class.
class Person{
  ...
  public String getName(){...}
  public void setName(String name){...}
  ...
  public int getAge(){...}
  public void setAge(int age){...}
  public interface PersonJsonizer extends Jsonizer{}
}
Let the jsonizing and de-jsonizing begin
//Create a Person Object
Person p = new Person();
p.setName("Andres");
p.setAge(28);
//Create a PersonJsonizer instance
PersonJsonzier pj = (PersonJsonizer)GWT.create(PersonJsonizer.class);
//Jsonize
String json = pj.asString(p);
// A JSON String with Person properties
//json = '{'name':'Andres','age':28}';
// Create the Person Jsonizer
PersonJsonizer jsonizer = (PersonJsonizer)GWT.create(PersonJsonizer.class);
try{
  // Translate the JSON String to a Person bean
  Person p = (Person)JsonizerParser.parse(jsonizer, json);
}catch(JsonizerException e){
  Window.alert('JSON Translation Error!');
}

Tuesday 27 November 2012

Android Spinner (Drop Down List) Example

1. List of Items in Spinner

Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).
File : res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">MyAndroidApp</string>
    <string name="country_prompt">Choose a country</string>
 
    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>
 
</resources>

2. Spinner (DropDown List)

Open “res/layout/main.xml” file, add two spinner components and a button.
  1. In “spinner1″, the “android:entries” represents the selection items in spinner.
  2. In “spinner2″, the selection items will be defined in code later.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />
 
</LinearLayout>

3. Code Code

Read the code and also code’s comment, it should be self-explanatory.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MyAndroidAppActivity extends Activity {
 
  private Spinner spinner1, spinner2;
  private Button btnSubmit;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 
 addItemsOnSpinner2();
 addListenerOnButton();
 addListenerOnSpinnerItemSelection();
  }
 
  // add items into spinner dynamically
  public void addItemsOnSpinner2() {
 
 spinner2 = (Spinner) findViewById(R.id.spinner2);
 List<String> list = new ArrayList<String>();
 list.add("list 1");
 list.add("list 2");
 list.add("list 3");
 ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
  android.R.layout.simple_spinner_item, list);
 dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spinner2.setAdapter(dataAdapter);
  }
 
  public void addListenerOnSpinnerItemSelection() {
 spinner1 = (Spinner) findViewById(R.id.spinner1);
 spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }
 
  // get the selected dropdown list value
  public void addListenerOnButton() {
 
 spinner1 = (Spinner) findViewById(R.id.spinner1);
 spinner2 = (Spinner) findViewById(R.id.spinner2);
 btnSubmit = (Button) findViewById(R.id.btnSubmit);
 
 btnSubmit.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View v) {
 
     Toast.makeText(MyAndroidAppActivity.this,
  "OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
   Toast.LENGTH_SHORT).show();
   }
 
 });
  }
}
File : CustomOnItemSelectedListener.java
package com.mkyong.android;
 
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
 
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
 
  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
 Toast.makeText(parent.getContext(), 
  "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
  Toast.LENGTH_SHORT).show();
  }
 
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
 // TODO Auto-generated method stub
  }
 
}

Spinner sample program in Android

Spinner sample program in Android

This sample android program shows you how to use Spinner  in Android. In this program a list is shown as a dropdown box. When you click on the list, the selected item is shown on the text view. You can use this ArrayAdapter widget and the Spinner object together with the  onListItemClick() method to determine the selected index and process accordingly.
The ArrayAdapterDemo2.java file is as follows:

package com.javasamples;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class ArrayAdapterDemo2 extends Activity implements
  AdapterView.OnItemSelectedListener {
 TextView selection;
 String[] items = { "this", "is", "a", "really", 
   "really2", "really3",
   "really4", "really5", "silly", "list" };

 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);
  selection = (TextView) findViewById(R.id.selection);

  Spinner spin = (Spinner) findViewById(R.id.spinner);
  spin.setOnItemSelectedListener(this);

  ArrayAdapter aa = new ArrayAdapter(
    this,
    android.R.layout.simple_spinner_item, 
    items);

  aa.setDropDownViewResource(
     android.R.layout.simple_spinner_dropdown_item);
  spin.setAdapter(aa);
 }

 public void onItemSelected(AdapterView<?> parent, View v, int position,
   long id) {
  selection.setText(items[position]);
 }

 public void onNothingSelected(AdapterView<?> parent) {
  selection.setText("");
 }
}//class

Sunday 25 November 2012

SQL Injection

SQL Injection

As the name implies, SQL injection vulnerabilities allow an attacker to inject (or execute) SQL commands within an application. It is one of the most wide spread and dangerous application vulnerability. The CLASP project provides a good overview of SQL injection.

Example of SQL injection

The following Java servlet code, used to perform a login function, illustrates the vulnerability by accepting user input without performing adequate input validation or escaping meta-characters:
conn = pool.getConnection( );
String sql = "select * from user where username='" + username +"' and password='" + password + "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
loggedIn = true;
 out.println("Successfully logged in");
} else {
 out.println("Username and/or password not recognized");
}
It is possible for attackers to provide a username containing SQL meta-characters that subvert the intended function of the SQL statement. For example, by providing a username of:
admin' OR '1'='1
and a blank password, the generated SQL statement becomes:
select * from user where username='admin' OR '1'='1' and password=' '
This allows an attacker to log in to the site without supplying a password, since the ‘OR’ expression is always true. Using the same technique attackers can inject other SQL commands which could extract, modify or delete data within the database.

Wednesday 7 November 2012

md5 hash for password string in GWT(Encryption in GWT)


MD5 hash for password string in GWT(Encryption in GWT

add  <inherits name='com.googlecode.gwt.crypto.Crypto'/> in xml file
add gwt-crypto-2.3.0-20110518.123759-2.jar jar file in project
String getSHA1for(String text) {
  SHA1Digest sd = new SHA1Digest();
  byte[] bs = text.getBytes();
  sd.update(bs, 0, bs.length);
  byte[] result = new byte[20];
  sd.doFinal(result, 0);
  return byteArrayToHexString(result);
}

String byteArrayToHexString(final byte[] b) {
  final StringBuffer sb = new StringBuffer(b.length * 2);
  for (int i = 0, len = b.length; i < len; i++) {
    int v = b[i] & 0xff;
    if (v < 16) sb.append('0');
    sb.append(Integer.toHexString(v));
  }
  return sb.toString();
}