Thursday, 27 December 2012

SGA (System Global Area) - Oracle

SGA is shared location for oracle database instance. This memory will be shared or used by multiple processes running in that instance. This shared location is divided into multiple areas and each area will be used for different purpose.
Here are those areas,

1. Large pool:-
This holds information about UGA (User Global Area). This holds information related with user sessions.

2. dictionary cache:-
It holds information about data dictionary.

3. Java pool:-
It will be used for parsing java statements.

4. Shared pool:-
It holds information about commonly used SQL statements.

5. redo buffer:-
It holds info about committed transactions but not yes written to online log.

6. buffer cache:-
Holds data blocks from tables.

Method injection in spring framework - JAVA

Spring framework provides one of the good mechanism of method injection. Method injection means changing methods from class. Means on call of that particular method we can execute another method which is not in that class. We generally use this mechanism when we have some licensed code and we are not running with authority to change code but we are in need to change just one particular method.

Here I am giving short demo with my eclipse IDE. You can download this IDE from http://downloads.myeclipseide.com/downloads/products/eworkbench/indigo/installers/myeclipse-10.7-offline-installer-windows.exe here.


Now start the IDE and keep all default settings.
1. Create simple java project.


2. Now right click on project go to "my eclipse" option and in that select "add Spring capabilities".
Select 2.0 version of spring framework and finish it.


3. Now open your project and you will see applicationContext.xml file under "src" folder.


4. Open that file and past following code into that,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id = "emp" class = "testpkg.Employee">
        <replaced-method name = "empSal" replacer="employeeReplacer"/>
    </bean>
   
    <bean id= "employeeReplacer" class = "testpkg.EmployeeReplacer"/>
</beans>

5. Now create new package called "testpkg".

6. In that package create class called "Employee" and past following code,

package testpkg;
public class Employee {
    public String empSal() {
        return "bonus";
    }
}

7. Now create class "EmployeeReplacer" and past following code in it,

package testpkg;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class EmployeeReplacer implements MethodReplacer{
    @Override
    public Object reimplement(Object arg0, Method arg1, Object[] arg2)
            throws Throwable {
        // TODO Auto-generated method stub
        return "extra bonus";
    }
}

8. Now create "Main" class in the same package and  past following code in it,

package testpkg;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee ms = (Employee) ctx.getBean("emp");
        String str = ms.empSal();
        System.out.println("This is return : " + str);
    }
}

Now if you are executing this code then in normal situation it must print "This is return : bonus".
But because of spring method injection now it will print "This is return : extra bonus". In this way we are executing some other method on behalf of class method.

Daemon Thread - Java

The major difference between normal thread and daemon thread is that JVM always waits for normal thread to finish, but JVM will never wait for daemon thread to terminate. Means ones normal threads in program are finishing execution the JVM will terminate without caring how many daemon threads are executing.
Here I am giving one simple example proving above mechanism,


class Main implements Runnable
{
    Thread normal, daemon;
    public static void main(String args[])
    {
        Main m = new Main();
        m.checkOut();
    }
   
    public void checkOut()
    {
        try
        {
            normal = new Thread(this);
           
            daemon = new Thread(this);
            daemon.setDaemon(true);
           
            normal.start();
            daemon.start();
        }
        catch(Exception e)
        {
            System.out.print("\nException : " + e);
        }
    }
   
    public void run()
    {
        try
        {
            synchronized (this) {
                System.out.print("\nThis is thread : " + 1);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 2);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 3);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 4);
            }
        }
        catch(Exception e)
        {
            System.out.print("\nException : " + e);
        }
    }
}


In output you can see that as soon as normal thread is finishing execution the JVM is exiting without waiting for daemon thread to complete.

In java by default thread is not daemon thread. We can use "setDaemon()" method to make our normal thread daemon. Here we have to remember that setDaemon() method must be called before call to start() method otherwise it will throw an exception IllegalThreadStateException.


Generally we can use this daemon thread for background processing purpose. Marking thread as daemon means it will be killed safely when JVM will exit. Practically we can use this daemon thread for background timers, keeping watch on something throughout our program execution etc.

Apart from this behavior daemon thread works similar to normal thread. We can use all normal thread methods with daemon thread.

Tuesday, 11 December 2012

Variable arguments - Java

This is one of the new feature in JDK5. varargs allows you to pass variable number of arguments to function. You can no argument, one arguments or any number of arguments to function using this feature. Remember one thing that vararg must be that last argument to function and we can use only one vararg for  one function. We can use varargs anywhere except last argument. You can even pass array to varargs.
Here I am giving one simple example,

class Test
{
    private void printThis(int... a)
    {
        for(int i = 0; i < a.length; i++)
            System.out.print("\nArgs : " + a[i]);
        System.out.print("\n\n=======================");
    }
   
    public static void main(String args[])
    {
        int[] ary = new int[10];
        for(int i = 0; i < 10; i++)
            ary[i] = i;
       
       
        Test t = new Test();
        t.printThis();
        t.printThis(1, 2, 3);
        t.printThis(1, 2, 3, 4, 5, 6, 7, 8);
        t.printThis(ary);
    }
}


We can use this when we don't know exact number of arguments.

Generics - Java

Generics are mainly used for creating type safe collections and for avoiding code repetition. It also helps us to make our code more readable. We can use generic methods as well as generic classes. This is one of the new feature in JDK5.
Here I am giving few examples of generics in java..

Avoiding code repetition:
public class Test
{                   
    public static <E extends Comparable<E>> E max( E x, E y, E z)
    {
        E max = x;
        if(max.compareTo(y) < 0)
        {
            max = y;
        }
        if(max.compareTo(z) < 0)
        {
            max = z;
        }
        return max;
    }
    public static void main( String args[])
    {
        System.out.print("\nMax : " + max(1, 2, 3));
        System.out.print("\nMax : " + max(1.0, 2.3, 3.6));
        System.out.print("\nMax : " + max("Abc", "Pqr", "Xyz"));
    }
}


Here you can see that we are using same method to compare integers, floats and strings. In this way generics avoid code repetition an this is making our code more redable.


Type safe collections:
 import java.util.ArrayList;
public class Test
{                   
    ArrayList<String> al;
    public Test()
    {
        al = new ArrayList<String>();
        al.add("Test 1");
        //al.add(1); This will create compile time error.
        al.add("Test2");
        System.out.print("Array list is : " + al);
    }
    public static void main(String args[])
    {
        new Test();      
    }
}


Here in the above code you can see that we are using ArrayList and we are making it type safe. Here our ArrayList will be able to store only strings. If you are trying to add integer then it will create compile time error.


Generic classes:
class Test<E>
{
    private <E extends Comparable<E>>void maxTest(E x, E y)
    {
        E max = x;
        if(max.compareTo(y) < 0)
            max = y;
        System.out.print("\nMax is : " + max);
    }
    public static void main(String args[])
    {
        Test<String> t1 = new Test<String>();
        t1.maxTest(1, 2);
      
        Test<String> t2 = new Test<String>();
        t2.maxTest(1.2, 2.7);
      
        Test<String> t3 = new Test<String>();
        t3.maxTest("A", "B");
    }
}


In this way we can write generic classes.

Here we can say that generics is mainly used for type safe collections, avoiding code repetition and making code more readable.

Wednesday, 5 December 2012

Accessing Machine Info : JAVA

We can access much machine information in java. Here I am giving some of those.
1. Getting OS current user:
System.getProperty("user.name");

2. Getting OS name:
System.getProperty("os.name");

3. Getting OS arch:
System.getProperty("os.arch");

4. Getting OS version:
System.getProperty("os.version");

5. Getting host name and IP address of machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
localMachine.getHostName();
localMachine.getHostAddress();

6. Getting processor of machine:
System.getenv("PROCESSOR_IDENTIFIER");

7. Getting architecture of processor:
System.getenv("PROCESSOR_ARCHITECTURE");

8. Number of processors:
System.getenv("NUMBER_OF_PROCESSORS");

9. Getting screen dimentions:
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
dim.width  &  dim.height

10. Available drives:
File roots[] = File.listRoots();
for(int i = 0; i < roots.length; i++)
{
   System.out.print("Drive  :  " + roots[i].toString() + "  ::  Total space : " + roots[i].getTotalSpace() / 1024  / 1024 / 1024 + " GB  ::  Free space : " + roots[i].getFreeSpace() / 1024 / 1024 / 1024 + " GB");
 }//for i

I have tried these things on JDK6.0

Thursday, 29 November 2012

Logger class in java

For big applications log is very important thing. Using these logs we can detect cause of problem. We can determine the place where problem occurred. For big applications it is necessary to store that log in one of the file. In order to facilitate this java provides Logger class.

This logger class is very easy to use. It allow you to create files in different formats like xml files, simple files etc. This logger class stores lot of information like time stamp, class name, method name and severity of problem.

Here I am giving very simple example one for simple file and another for xml file.

Create simple log file: 
Try to execute following code and you will get log file.

Code:
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Test
{
    FileHandler fileHandler;
    Logger logger;
   
    public Test()
    {
        try
        {
            fileHandler = new FileHandler("test.log");
            logger = Logger.getLogger("log_file");
            logger.addHandler(fileHandler);
            fileHandler.setFormatter(new SimpleFormatter());
        }
        catch(Exception e)
        {
            System.out.print("Exception : " + e);
        }
    }
   
    public static void main(String[] args)
    {
        Test t = new Test();
        t.testingMethod();
        t.anotherMethod();
    }
 
    private void testingMethod()
    {
        try
        {
            logger.warning("See what is happening.");
            logger.info("See again");
            logger.severe("It is problem");
        }
        catch(Exception e)
        {
            System.out.print("Exception : " + e);
        }
    }
   
    private void anotherMethod()
    {
        try
        {
            logger.addHandler(fileHandler);
            fileHandler.setFormatter(new SimpleFormatter());
          
            logger.warning("Test");
            logger.info("Test");
            logger.severe("Test");
        }
        catch(Exception e)
        {
            System.out.print("Exception : " + e);
        }
    }
}



Using this mechanism you can add logs to your applications.

Wednesday, 28 November 2012

Split panel in JAVA

Split panel in java is mainly used to create dynamic dividers or sections on your frame. You can either add vertical or horizontal split. In one split panel you can add only two components. You can add one split panel in another one.

Here I am giving one very simple example of split panel.

Code:
import java.awt.Button;

import javax.swing.JFrame;
import javax.swing.JSplitPane;

class Test
{
    JFrame frm = new JFrame();
    public Test()
    {
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new Button("B2"), new Button("B2"));
      
        splitPane.setOneTouchExpandable(true);
        splitPane.setDividerLocation(150);

        frm.add(splitPane);

        frm.setSize(500,500);
        frm.setVisible(true);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String args[])
    {
        new Test();
    }
}


Here you can see that I have added two buttons in split panel. Run this program and you will see that you can resize any section as much as you want. Even you can hide one section.

Wednesday, 21 November 2012

Maven

Maven is one of the very useful tool for project development. Major goals of maven are as given below:

1. Build tool

2. Project management tool

We can use this maven tool when we are developing big projects with frameworks. When we are going for big projects then we face following common problems:

1. Multiple jars:
When we use frameworks like spring, struts etc. the we have to import multiple jar files. These jar files are nothing bu supporting files for our framework. In order to import these jar files we must know what jar files we have to import and how to bundle them.
This problem can be solved using maven tool. Maven fetches all related jar files from online repository or may be locally if you are doing this second time. For maven you just have to specify the project model that you want like spring, struts etc.

2. Jar dependencies:
It is related problem as above. When we import jar file then these jar files have some dependencies on each other. So we have to take care that we are importing these files in sequence.
This problem is also solved by the maven.

3. Project structure:
Nearly every frame work need some folder structure for project. Like main project files will be separate from test project files.
This is also done by maven. Maven creates directory structure according to our framework.

4. Build life cycle:
Maven takes care of build life cycle. This build life cycle contains number of phases like validate, compile, test, package and install. Some times when you have to make your code available to others the deploying that on repository comes into picture.

Maven fetches all jar file from its online repository. Maven maintains its local repository separately. Maven always looks into local directory before going for online. If you are doing some process for second time then maven will take files from local repository.

Now I am assuming that you have maven installed on your machine.
I will be adding post for installation as well.
In order to test maven installation you can type maven on command prompt.

Here I am explaining about creating sample project using maven on windows 7 platform.

1. Now create one separate folder for maven test project.
2. Go to that folder from command prompt.
3. Execute command "maven genapp".
4. Now it will ask you about project template. You can start with default so type default over there.
5. It will ask for id which is  top level component in your project.
6. It will ask for Application name and package name.
7. After completing this process check out your maven project folder it will be running with lot many things. Here is project.xml is important file open that file check out details.
8. Now execute "maven eclipse". It will create eclipse project for you.
9. Open eclipse and go to windows=>preferences in new window go to java=>build path=> class path variable. Here add new variable named "MAVEN_REPO" and give pathe of maven repository folder.
10. Now import this project to your eclipse from file=>import option.
11. Run it and you will get all .class file in your target folder.

If you want to clean every thing except java code execute "maven clean" command.

You can find out more details at http://maven.apache.org/  
I will try to add one video tutorial for this one for better understanding.

Thursday, 25 October 2012

Semaphore

Semaphore provides simple and effective way of controlling multiple threads trying to access same resource. This concepts was invented by dutch scientist in 1965. Semaphore can be used as deadlock handling mechanism for single resource. There are two main types of semaphore,

1. Counting semaphore :
Here semaphore represents arbitrary number of resource unit. Like 10,20 etc.

2. Binary semaphore :
Binary semaphore holds only two values 0 or 1. Means available/ not-available or locked /unlocked. This binary semaphore works nearly as Mutex.

Here is one simple example of explaining semaphore concept,
Consider internet cafe where 10 seat are available to be used by customer and there is one gate keeper. Now when customer wants to occupy seat in the cafe then first he/she has to take permission from gate keeper. If gate keeper is giving permission then and only then he/she can occupy seat. Again if customer wants to leave any seat then after leaving that seat customer has to inform gate keeper that he/she just released one seat.
Here gate keeper is simply maintaining count of number of seats ready to use. If count is more than 0 then gatekeeper will allow customer to occupy seat and if count is 0 then gate keeper will not allow you to occupy the seat.
This explains the semaphore concept where seats are number of resources, customers means processes and gate keeper means semaphore. Semaphore neer maintains which resources are empty but it only maintains number of resources ready to use.

Even if we are using semaphore the dead lock may occur because of multiple resource problem. This problem can be explained using dining philosophers problem.

Tuesday, 23 October 2012

Exceptions - Java

Exception handling mechanism in java shows one major base class called Throwable. This Throwable class shows two major branches called Exception and Error.

Exception : 
Exception is abnormal condition occurred at run time. We programmers can handle these exceptions in our code using try-catch block. Example of exception is NullPointerException, FileNotFoundException etc.

Error :
Error are abnormal conditions which are not supposed to be handled by programmer. These are serious ones and we can't handle these in our program. Example of error is OutOfMemoryError, StackOerflow etc.

Again there are two types of exceptions. Checked exceptions and unchecked exception. Checked exception are those which compiler forces us to add. Like IOException. And unchecked exceptions are those which are under RunTimeException class or under Error class.

We already know how to handle exception using try-catch block. Here I am trying to explain how to handle exception between different methods. Here is simple example of that,

Code :
import java.io.IOException;

class Main
{
    public void test() throws IOException {
       
    }
   
    public void test1() throws IOException {
        test();
    }
   
    public void test2() {
        test1(); // It will create problem.
       
        try {
            test1();
        } catch(IOException e) {
           
        }
    }
    public static void main(String args[])
    {
       
    }
}

Let's examine the above code carefully. Here method test is throwing IOException so this exception will be handled by the method who is calling to test() method. Here that method is test1(); But test method is also throwing the same exception so at this point responsibility of handling that exception will be of method who is calling to test1(); So in the above code IOException throws by test() method is handled in test2() method using try-catch block.

Anonymous Inne Classes - Java

Anonymous inner classes are little confusing in java. Remember one thing about these classes that, anonymous inner classes can either implement one interface or extend one class at a time only. These classes can never extend and implement class and interface but only one at a time.
Here I am presenting few things about anonymous inner classes with examples.

Anonymous inner class extending class :
Here is a code where anonymous class is sub class of one of super class,
Code :
class Test {
     public void cool() {
          System.out.print("This is original.");
     }
}

class Main {
     public static void main(String args[]) {
          Test t = new Test() {
               public void cool() {
                    System.out.print("This is duplicate.");
               }
          };
          t.cool();
     }
}

This code will output "This is duplicate.". In this way we can use anonymous inner classes for overriding one or more methods of super class.

Anonymous inner class implementing interface :
Here is code presenting this concept,
Code :
interface Test {
     public void ohh();
}

class Main {
     public static void main(String args[]) {
          Test t = new Test() {
               public void ohh() {
                    System.out.print("Hahahaha");
               }
          };
          t.ohh();
     }

This code will print "Hahahaha". Here anonymous inner class is implementing our Test interface.

Anonymous inner class as argument :
Here is code for this one,
Code :
----------
----------
button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEent ae) {

     }
});
---------
---------

Enjoy it.....

Monday, 22 October 2012

Inner Classes - Java

In java inner classes are interesting. Here I am trying to present few things about inner classes. There are different types of inner classes are present in java,
     1. Regular inner classes
     2. Static inner classes (Nested classes)
     3. Method-local inner classes
Let's see these types one by one,

Regular inner classes : 
Regular inner classes means non-static inner classes, which are declared in top level class only. Here is example of regular inner class,

Code :
class TestOuter {
     private int x = 10;
     public static void main(String args[])  {
           TestOuter to = new TestOuter();
           TestOuter.TestInner ti = to.new TestInner();
           ti.testInnerMethod();   
     }

     public void outerNonStatic() {
           TestInner ti = new TestInner();
           ti.testInnerMethod();
     }

     class TestInner {
           public oid testInnerMethod() {
               System.out.print("X : " + x); //Totally valid
          }
          //Static members are not allowed in regular inner class.
         // Interfaces are no allowed here.
     }
}

From this example we can define following rules,
     1. Regular inner class can access private members of outer class.
     2. Regular inner classes can not declare any static member like static variable or method.
     3. We can directly create instance of inner class from non static method of outer class.
     4. We can create instance of inner class from static method of outer class via instance of outer class, because static method can never use this reference.
     5. We can not declare any interface in regular inner class.

Static inner classes :
Static inner classes are nested classes. Static word says that inner class is static member of outer class and can be accessed as other static members without creating instance. Here is example of static inner classes,

Code:
class Main
{
    int x =10;
    public static void main(String args[])
    {
        Test t = new Test(); // It works fine.
        t.testMethod();
        // This also works fine.
        Main.Test t = new Main.Test();
        t.testMethod();
    }
   
    public void outerNonStatic() {
        Test t = new Test();
        t.testMethod();
    }
   
    static class Test {
        public void testMethod() {
            System.out.print("X : " + x); //It will not compile.
        }
        interface TestingInt {
           
        }
    }
}

From this we can define following rules,
     1. Nested class can not access non static members of outer class.
     2. We can create instance of static class without reference of outer class. Even in static method.
     3. In static inner class we can declare any interface as well. This proves that static inner class works like top level class.

Method local inner classes:
Method local inner classes are those are defined in method. Here is simple example of method local inner classes,

Code :
class Main
{
    private int x =10;   
    public void testing() {
        Test t1 = new Test(); //It will not compile.       
       
        int a = 20;
        final int b = 30;
        class Test {
            public void testing() {
                System.out.print("X : " + x);
                System.out.print("A : " + a);// It will not compile
                System.out.print("B : " + b);               
            }
        }
       
        Test t = new Test();
        t.testing();
    }
}

From this we can define following rules,
     1. Method local inner classes can't access any variable of method except final.
     2. Object can be created only after class declaration.
     3. Can access private variables of top level class.

There are still many things to study about inner classes.

Tuesday, 18 September 2012

Use XML to reduce access time - Android

I was working with language translation in phone gap. In that case I was in need of 120 labels for translation. Out of 120, 60 are English and remaining are of other language. I was inserting all values in database ones on the very first start of application, because of that it was taking much time to start for first time. After that when I was using those labels in my app, there was much delay. Means all elements on page like button, text boxes were coming first and then labels. Because of that buttons were remaining empty first and then after some time text was appearing on that.

In order to solve this problem I am using XML database for fast access. Now I created simple XML file as given below,

english_translation_test.xml

<xml>
    <lbl1>Label - 1</ lbl1 >
    <lbl2>Label - 2</ lbl2 >
    <lbl3>Label - 3</ lbl3 >
</xml>

In this way I designed simple XML file, one for English and another for different language. I placed this file at place www => xml => english_translation_test.xml
In order to access this file I am using following code. In this code remember one thing that path must be relative to www folder. Path is in red color.


$.get('xml/english_translation_test.xml ', function(rawXml) {
getPlainXml(rawXml);
});

function  getPlainXml(xml)
{
        $('#label_1').html($(xml).find("lbl1").text());

$('#label_2').html($(xml).find("lbl2").text());

$('#label_3').html($(xml).find("lbl3").text());
}

Now in this case if language is different then use another language that's it. And you will get fast access to all your labels. You may need this process while code optimization and performance issues.

Background jerk problem because of keypad - Phone gap

In our phone gap application many times we encounter the problem of background. In this problem background image moves up when soft keypad comes up. In some cases all elements on screen like buttons, text fields moves up more than necessary.
In order to keep your screen and background fix you can use following solutions,

1. For keeping your elements on screen fix, you can use "overflow: hidden;" in your css for that element. You can apply this css to the div in which all elements are present.

2. By using above solution elements on screen will become fix but background image may move up. In order to fix background as well as elements you have to add just one line code to your activity tag present in manifest file. 

Code:
 <activity
            android:windowSoftInputMode="adjustPan"
            android:name=".Test"
            android:label="Test"
            android:configChanges="orientation|keyboardHidden" >
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
 </activity>
Here you have to add line in red color. You can try different options of that property.

Monday, 10 September 2012

SQL injection attack

SQL injection attack is one of the old attack. I found it interesting so giving short description on it. It is mainly related with web sites. This attack is because of few user input unchecked conditions. This is also called as blind attack where attacker is not running with any knowledge of database. Here I am giving few examples.

1. General attack:
 If you have to enter just one field in text box like password then here is attack.
Generally we know that whatever text we are going to enter in text box will appear in WHERE clause of SQL.
Ex. Password : test123
In this case query will something look like.
SELECT * FROM member WHERE password = 'test123'
Now see how can we attack using some SQL like input. Instead of entering only password think about following input,
Password : test123' OR 'X' = 'X
Now query will formed something like this,
SELECT * FROM member WHERE password = 'test123' OR 'X' = 'X'
where red and bold text is user input which is valid for text field but actually should not.

2. Finding some user:
Now consider case where we know email address. And whatever that data we are entering into text field is going to SELECT clause like,
SELECT * FROM members WHERE eaddr = 'Our_input'
Now in this case think about input,
email@xyz.com' OR full_name LIKE '%je%
Then query will be,
SELECT * FROM members WHERE eaddr = 'email@xyz.com' OR full_name LIKE '%je%'
Here it is assumed that field name is known. After that you can refine LIKE clause with % to get exact user.

In this way you can guess different attack tricks. But now a days every web site handle these kind of attacks.
Enjoy this....

Friday, 7 September 2012

Tools For Developers

Here I am giving list of useful tools for development. All these tools are free. You can download these tools easily from internet. Here I am giving short description, you read in details.

1. Firebug:
Firebug is one of the add-on which comes with mozilla firefox browser. Just go to "Tools" option of browser. In that select "Add-on". And search "firebug". Select the one which is having symbol like given below.
Using this you can easily develop css for your web page and can debug with scripts like java script.

2. Colorzilla:
This is another add-on with mozilla firefox. In the same way go to "Tools" then "Add-on". Now search colorzilla. Select one which is having symbol like given below.
You can use this add-on for getting hex code of color of any component on web page.

3. Measure it:
You have to search this add-on at the same place. With symbol like this,

You can use this for measuring height and width of components on web page. You can use this only for web pages opened in mozilla firefox.

4. Jing:
You can use this tool for taking screen shots and measuring any component on your computer screen. When you will start this tool it will give you pointer to measure and taking screen shots. Just search this tool on google.

5. SQLite database browser:
This tool will help you to browse through the SQlLite database. I have used this tool for phone gap development, where I used to take database file out from eclipse and open it in SQLite database browser for analysis.

6. Beyond Compare:
Beyond compare is a tool for comparing different versions of files, folders. It is very useful when number of people are working on the same project. You can go for google search for this. Symbol is like this,



7. Team box:
Team box is one of the online project management tool for simple projects. You will find this tool at http://teambox.com/. This is good for small team, small project. It allows you to create tasks and then you can have conversation for that task.

8. Rally dev:
This is another online project management software. It is designed for handling complex projects with big teams. You can find details at http://rallydev.com/. It provides more facilities to user from design to testing.

9. JDeveloper:
http://www.oracle.com/technetwork/developer-tools/jdev/overview/index.html
Check out this link for more details. It is one of new tool by oracle for java.

Enjoy these tools.

Wednesday, 5 September 2012

Android - PHP server connectivity

In android php server connectivity is very easy task. Here I am giving android code which will communicate with php script on wamp server. At first let's have a look at android client code.

1. Android Client:
At first you have to create array list with name value pair. Here is code for that,

Code:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name1", "value1"));
nameValuePairs.add(new BasicNameValuePair("name2", "value2"));

In this way you can put any number of name value pairs. You can access these values at server side means in php script in $_REQUEST array by there name. Means "value1" can be accessed using $_REQUEST['name1'].
Now we can send this array list to server as given below.

Code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ip_address_of_server/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is1 = entity.getContent();
byte[]b = new byte[200];
is1.read(b);
String responce= new String(b);

In response you will get return value from server. If your response from server is in JSON format then you can parse that as given below,

Code:

JSONObject jo=new JSONObject(responce);
String res = jo.get("result");

Where "result" is name that you are returning from server.

2. Server Part:
At server you have to write php script. Here is sample code,

Code:
test.php

<?php
$done = array('result' => 'success', 'value1' => $_REQUEST['name1']);
echo json_encode($done);
?>

This script will return value related with "name1".

At android client in "result" you will get "success" message and in "value1" you will get respected value.



Tuesday, 4 September 2012

Database problem in phonegap

In phone gap many times you can see that database operations are not working properly. In many cases I found that we are redirecting to some other page just after the database operation. Here is block of code,

insertData(data1, data2);
window.location = "abc.html";

And here is insertData function,


function insertDatas(data1, data2) {
        //Here I am assuming db is initialized properly.
db.transaction(insertHere, errorDataTable, successDataTable);
    function insertHere(tx) {
        var query = "insert into dataTable values('" + data1 + "','" + data2 + "')";
        tx.executeSql(query);
    }
    function errorDataTable(err){
          alert("Error : " + err);
    }
    function successDataTable() {
          alert("Success");
    }
}

Now here sometimes it may happen that, values are going to database. At place you may have update query In case of update values may not updated in database.

In order to fix this problem safe way to code in phonegap is to commit database after your operations. Here is code block with commit statement which is doing the same functionality as above but safely,

insertData(data1, data2);
//After this statement instead of redirecting call commit,

db.transaction(commit, errorCommit, successCommit);
 function commit(tx){
        tx.executeSql("COMMIT",[], commited, errorCommit);
 }
         
 function commited() {
        console.log('commit successful..');
        window.location = "abc.html";
}
         
function errorCommit() {
}
function successCommit() {
         console.log('commit successful.. redirecting');
        window.location = "abc.html"
}

So in phonegap always it is safe to commit your database. I have faced this problem with update statement.

Saturday, 1 September 2012

Maintain Your Data & Alerts

This blog is specially for the people who want to maintain there data in sophisticated manner and want to have alerts for specific thing on the web. Here I am giving few easy and free ways to maintain your data and alerts. You can use these services easily. For every facility you will need google log in.

1. Alerts:
At the top of google page select "More" option. In this select "Even more" option. It take you to the new page. Here you have to find "Alert" option. Click that "Alert" option. Again it will take you to new form. First test box will be of "Search query" in that text box simple add about what you want to get alerts. Suppose I want alerts on java technology the my search query will be "Java technology". Select remaining option as you wish. Finally click "Create new alert". It also provides you facility to manage your alerts properly. Alerts will be given to you via email.

2. Docs:
You will find this option in "Even more" page as given above. Here you will be able to maintain your documents, presentations and spreadsheets. It will allow you share link with specific people and will allow your group to edit that document in synchronized manner. It allows you to maintain these documents properly.

3. Books:
You will find this option in "Even more" page as given above. Here you will be able to maintain your online library. It will allow you to create your own book library. Ones you are running with your library you can add book to it easily. While browsing books on google books at top it will give you option of adding books to your library. In learn more section you will get detailed information.

4. Reader:
You will find this option in "More" tab on google page. It will allow you to keep track of particular blog or something like that. On the main page of reader it will show you option of "Sbscribe". Click that and add url in specified format. Ex. "tech-world-brij.blogspot.in". Now on update of it, you will get notification.

5. Panoramio:
You will find this option in "Even more" page. Here you will be able to explore photos of world. It allows user to upload photos with location. It will provide you facility to share your photos with your friends. You get all details on the same page.

6. Groups:
You will find this option in "Even more" page. It will allow you to create your own discussion groups. You will be able to set access level to your group. It is interesting one. See it's details.

I am going to add more things shortly.....

Friday, 31 August 2012

Google Tips & Tricks

Here I am giving few google tips & tricks. Few are funny and few are useful for developers.

1. zerg rush:
Just go to google.com and type "zerg rush" in google search and press enter. Now you have to protect your page from enemies. Try this it is so funny.


2. do a barrel roll:
In google search just type "do a barrel roll" and press enter.


3. gravity:
In google search type "gravity" and press "I'm Feeling Lucky" button.


4. Web History:
If you are logged in through gmail account and browsing on the web, then you can retrieve all your history. Google maintains your search history for you. In the right upper corner there is one button called option. Click this button and go to web history. Here it will ask you for login, after login it will give you all your history.


5. See visited pages by you:
Write keyword in search bar for which you want to see visited pages. Now in the left side panel at the bottom you will see "The web" option in that click "More search tools". In that you will find option of "Visited pages". Click that option and you will get visited pages.


6. Create open source project with google:
Go to "More" option present at top of your google page. In that click "Even more". Here at the bottom of page you will find option of "Code". Click this option and you will all information about creating open source projects.

I will try to add more.

Thursday, 30 August 2012

G-mail Tips & Tricks


In this post I am giving few Gmail tips and tricks. These tips and tricks can be used by general user of g-mail  for maintaining his/her emails properly and customizing layout properly. It may be used by developers as well. So here is first trick for developers,


1. If you want to test application which dose not allow to send or receive emails from same email address then you can use following trick, If your email address is abc@gmail.com and you are sending emails to abc+1@gmail.com, abc+2@gmail.com and so on then all emails will be forwarded to abc@gmail.com only. Instead of +1, +2 you can use +a, +b... and so on.

2.  Click settings button which is present at right upper corner. Then drop down menu will be displayed, in that menu again select "Settings". In that select "Labs" tab. Here are all crazy stuffs of g-mail. Here I am giving few of them,
1. SMS in chat:
It will allow you to send text messages (SMS) in chat.
2. Extra Emoji:
Here you will get extra smilly icons to use.
3. Unread message icon:
  It will show your unread messages at top just near to page title.
4. Google calender:
Very useful for saving important events with phone sync facility.
        5. Voice player:
                It will allow you to play voice mails.
In this way there are many facilities are provided in this "Labs" tab. You can check out all of them. Every feature is interesting.

3. Under the same "Settings" menu you have "Themes" option using which you can change theme of your email account. Try out these themes.

4. If you are switching from one account to another account then g-mail provides you facility to redirect all your mails to new account. You will find this option under settings in "Accounts and import". In this tab find out option "Import mail and contacts". In learn more section of this option you will get detailed information.

5. If you want to forward email coming from specific account then under "Settings" menu in "Forwarding and POP/IMAP" tab you will find that option. Under learn more section details are given.

6. You can create filter with different options for specific email addresses. For this under "Settings" menu select "Filter" tab. In that at the bottom there is option "Create a new filter". On click of this option you will get one form. fill up that form and move forward and filter will be created. Here you can do following things with mail from specific account.
     a. Directly add to archive by skipping inbox.
     b. Mark as read.
     c. Star it.
     d. You can apply specific label.
     e. You can directly forward it to specific email address.
     f. Even you can directly delete that email.
     g. And few more...

These are few interesting tips and tricks I will try to add more......Enjoy it.

Wednesday, 29 August 2012

Writing Plugins For Phonegap In Android


Note: Here it is assumed that you have properly running Phone gap project.
Writing plugins is very easy for android in phonegap. Here are simple four steps to write plugins.


1.  Create TestingPlugin.java class in src folder of your eclipse project.
Replace that file with following code,
Code:
package src.com.testing; 
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
public class TestingPlugin extends Plugin { 
      @Override
      public PluginResult execute(String action, JSONArray data, String callbackId) {
            try {
                  return new PluginResult(PluginResult.Status.OK, "Process successful");
            } catch(Exception e) {
                  return new PluginResult(PluginResult.Status.ERROR, "Process fail");
            }
      }

} 
Remember one thing that, method from plugin class can return PluginResult only.


2. Now in your www folder create one html file and use following code,
Code:
<!DOCTYPE HTML>
<html>
<head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="stylesheets/jquery.mobile-1.1.0.min.css" />
      <script src="scripts/jquery-1.7.1.min.js"></script>
      <script src="scripts/TestingPlugin.js"></script>
      <script src="scripts/jquery.mobile-1.1.0.min.js"></script>
      <script type="text/javascript" charset="utf-8" src="scripts/cordova-2.0.0.js"></script>
      <script type="text/javascript">
      function onBodyLoad()
      {          
            document.addEventListener("deviceready", onDeviceReady, false);
      }
      function onDeviceReady() {
            navigator.notification.alert("Testing")
      }
    function callNativePlugin( returnSuccess ) {
        TestingPlugin.callNativeFunction( success, fail, returnSuccess );
    }
    function success (result) {
       alert("SUCCESS: \r\n"+result );
    }
    function fail (error) {
       alert("ERROR: \r\n"+error );
    }
    </script>
    </head>
      <body onload="onBodyLoad()">
            <h1>Testing</h1> 
            <button onclick="callNativePlugin('Your_parameters');">Invoke plugin</button>
      </body>
</html>

Here include all necessary scripts carefully. Important script is highlighted here. It is necessary for calling plugin function.


3. Now in "www -> scripts" folder create TestingPlugin.js file and use following code.
Code:
var TestingPlugin = {
    callNativeFunction: function (success, fail, resultType) {
      return cordova.exec(success, fail, "src.com.testingplugin.TestingPlugin", "nativeAction", [resultType]);
    }
};



4.  Now open "res -> xml -> plugins.xml" file and past following line of code under <plugins></plugins> tag,
Code:
<plugin name=”src.com.testingplugin.TestingPlugin” value=” src.com.testingplugin.TestingPlugin”/>


5. And here you are ready to go. Here for every facility you have to write one class. 

Enjoy plugins....