Wednesday, June 27, 2012

Secure a Private Folder and Hide it in Windows

Dear reader,

Today I found a link to:
1) Secure a folder using a password and hide it. It won't be visible in "Show Hidden files 
   and Folder" option in Folder settings.
2) Convert a folder as "Recycle Bin", "Internet Explorer" kind of icons and secure it
   using password so that no one can see the content.

This is quite simple, just using notepad. Tested in Windows environment.

These stuffs you might be knowing as these are hacking techniques, however I am pasting the 
link of these two stuffs.

This below one is written by my college batchmate, branchmate:
http://www.cyberpetals.in/2012/06/how-to-secure-folder-using-notepad.html


This below one, I got by googling:
http://pakwing.com/tips-and-tricks/cmd-tips-and-tricks/convert-any-folder-into-my-computer-recycle-bin-internet-explorer-or-control-panel


----------------END-----------------

Friday, June 8, 2012

Reflection and VarArgs in Java

Dear reader,

This article is an extention of my earlier article "Reflection in Java", which can be seen at below link:
http://deepakmodi2006.blogspot.in/2012/04/reflection-in-java.html

Here I am writing about:
1) Complete example and use of "Vararg" (Variable Arguments Array) in Java. "Vararg" is used to hold
   an array of objects with un-defined size. Please see the example below, I have made it very very simple.
2) Reflection and use in calling Setter, Getter method in Java. This I have faced in my application as
   using reflection we had to set some parameters and use the same object to fetch the data using Getter.
3) A more generic program to display all setter and getter methods of a class.
   
==============================================================          
//VarArg example with output
public class VarArgsExample {  
    public static void main(String[] args) throws Exception {  
        String[] greetings = { "Hello", "Deepak" };  

        //No warning  
        Object[] objects = greetings;  

        //No warning  
        arrayTest(greetings);  

        //No warning  
        varargTest(objects);

        //No warning
        varargTest(new Object[]{}); 

        //Warning: The argument of type String[] should explicitly be cast to Object[] for the 
        //invocation of the varargs method varargTest(Object...)   
        varargTest(greetings);    

        //No warning
        varargTest();
        
        //Warning: The argument of type null should explicitly be cast to Object[] for the 
        //invocation of the varargs method varargTest(Object...)
        varargTest(null);
    }  

    public static Object[] arrayTest(Object[] p) {  
        return p;  
    }  
    public static Object[] varargTest(Object... p) {  
        System.out.println(p.length);
        return p;  
    }  
}  

//Output:
2
0
2
0
Exception in thread "main" java.lang.NullPointerException
    at VarArgsExample.varargTest(VarArgsExample.java:33)
    at VarArgsExample.main(VarArgsExample.java:26)
==============================================================  

//Reflection and Setter/Getter method:
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SetterGetterReflection {
    private String firstName;
    private String middleName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    //Main method to execute the program
    public static void main(String[] args) throws Exception {
        SetterGetterReflection myObject=new SetterGetterReflection();          

        Class myclass = myObject.getClass();

        //Invoking setter method using reflection
        Method setterMethod = myclass.getMethod("setFirstName", java.lang.String.class);
        setterMethod.invoke(myObject, new Object[] {"Deepak"});

        setterMethod = myclass.getMethod("setLastName", java.lang.String.class);
        setterMethod.invoke(myObject, new Object[] {"Modi"});
        
        //Values are set using Reflection setter method
        System.out.println("FirstName: "+myObject.getFirstName());
        System.out.println("LastName: "+myObject.getLastName());
        
        //Now fetching getter method
        Method getterMethod = myclass.getMethod("getFirstName",  new Class[]{});
        String fName = getterMethod.invoke((Object) myObject, new Object[]{}).toString();
        
        getterMethod = myclass.getMethod("getLastName",  new Class[]{});
        String lName = getterMethod.invoke((Object) myObject, new Object[]{}).toString();
        System.out.println("FirstName: "+fName+", LastName: "+lName);
        
        
        Field fields[]=myObject.getClass().getDeclaredFields();  //All fields including private
        //Field fields[]=myObject.getClass().getFields();  //Only public declared fields
        String fieldNames[]=new String[fields.length];
        
        for(int i=0;i<fields.length;i++){
            fieldNames[i]=fields[i].getName();
        }

        for(String f:fieldNames){
            System.out.println("FieldName: "+f);
        }
        
        SetterGetterReflection myAnotherObject=new SetterGetterReflection();          
        String setterMethodNames[]=myAnotherObject.getAllSetterMethodNames(fieldNames);
        for(String s:setterMethodNames){
            System.out.println("Setter Method name: "+s);
            //Now use reflection to invoke methods
        }
                 
        String getterMethodNames[]=myAnotherObject.getAllGetterMethodNames(fieldNames);
        for(String s:getterMethodNames){
            System.out.println("Getter Method name: "+s);
            //Now use reflection to invoke methods
        }
        
    }
    public String[] getAllSetterMethodNames(String[] fieldNames){
        String mNames[]=new String[fieldNames.length];
        
        for(int i=0;i<fieldNames.length;i++) {
            String mName=fieldNames[i];
            mName=mName.replace(mName.charAt(0), Character.toUpperCase(mName.charAt(0)));
            mNames[i]="set"+mName;
        }
        return mNames;
    }
    public String[] getAllGetterMethodNames(String[] fieldNames){
        String mNames[]=new String[fieldNames.length];
        
        for(int i=0;i<fieldNames.length;i++) {
            String mName=fieldNames[i];
            mName=mName.replace(mName.charAt(0), Character.toUpperCase(mName.charAt(0)));
            mNames[i]="get"+mName;
        }
        return mNames;
    }
}

//Output:
FirstName: Deepak
LastName: Modi
FirstName: Deepak, LastName: Modi
FieldName: firstName
FieldName: middleName
FieldName: lastName
Setter Method name: setFirstName
Setter Method name: setMiddleNaMe
Setter Method name: setLastName
Getter Method name: getFirstName
Getter Method name: getMiddleNaMe
Getter Method name: getLastName

==============================================================  
//Program to display setter and getter methods of a class:
import java.lang.reflect.Method;

public class FindSetterGetter {
    private String firstName;
    private String middleName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public static void main(String[] args) {
        printGettersSetters(FindSetterGetter.class);
    }
    public static void printGettersSetters(Class aClass){
        Method[] methods = aClass.getMethods();

        for(Method method : methods){
            if(isGetter(method)) System.out.println("getter: " + method);
            if(isSetter(method)) System.out.println("setter: " + method);
        }
    }

    public static boolean isGetter(Method method){
        if(!method.getName().startsWith("get"))      return false;
        if(method.getParameterTypes().length != 0)   return false;  
        if(void.class.equals(method.getReturnType())) return false;
        return true;
    }

    public static boolean isSetter(Method method){
        if(!method.getName().startsWith("set")) return false;
        if(method.getParameterTypes().length != 1) return false;
        return true;
    }
}

//Output:
getter: public java.lang.String FindSetterGetter.getFirstName()
setter: public void FindSetterGetter.setFirstName(java.lang.String)
getter: public java.lang.String FindSetterGetter.getMiddleName()
setter: public void FindSetterGetter.setMiddleName(java.lang.String)
getter: public java.lang.String FindSetterGetter.getLastName()
setter: public void FindSetterGetter.setLastName(java.lang.String)
getter: public final native java.lang.Class java.lang.Object.getClass()

==============================================================  

Tuesday, June 5, 2012

Conversion of a Map into XML and Vice-versa in Java

Dear reader,
I am writing an article today on how to convert a Map to XML and Vice-versa in Java.
I have tried to put nested Map examples too, which is serialized in a String Key,Value pair. Third party libraries are from 
XStream team, which are very popular in Industry for the same.
I hope you will find it useful. Some tweaking may be required to suit your purpose but the below mentioned all
examples are tested by me and runs fine. So enjoy reading and experimenting from where I have left here...

Contents:
1) Plain Java code to convert a Map to an XML.
2) Java code using Third party libraries to convert into XML and Vice-Versa.
3) Again using same Third party libraries as point-2 above but a complex converter.
4) Nested Map contents and conversion into XML.
5) Reference link.
6) Required Jars for third party libraries.


1) Plain Java code to convert a Map to an XML
   First I am writing a very simple program to convert a Map to an XML as below:

import java.util.HashMap;
import java.util.Map;

public class MagicAPI {
    public static void main(String[] args) {
        Map<String,String> mp=new HashMap<String,String>();

        //Map contains: EmpId,Name
        mp.put("197","Deepak kumar modi");
        mp.put("198","Sweep panorama");
        mp.put("199","HD Video");
        //System.out.println(mp);

        String xml = covertToXML(mp,"root");
        System.out.println("Result of converted map to xml:");
        System.out.println(xml);
    }
    public static String covertToXML(Map<String, String> map, String root) {
        StringBuilder sb = new StringBuilder("<");
        sb.append(root);
        sb.append(">");

        for (Map.Entry<String, String> e : map.entrySet()) {
            sb.append("<");
            sb.append(e.getKey());
            sb.append(">");

            sb.append(e.getValue());
            sb.append("</");
            sb.append(e.getKey());
            sb.append(">");
        }

        sb.append("</");
        sb.append(root);
        sb.append(">");

        return sb.toString();
    }
}
//Output: 
Result of converted map to xml:
<root><198>Sweep panorama</198><199>HD Video</199><197>Deepak kumar modi</197></root>


2) Java code using Third party libraries to convert into XML and Vice-Versa
//Two POJOs are required for this example, so please find below two simple classes:

//Person.java
public class Person {
    private String firstname;
    private String lastname;
    private PhoneNumber phone;
    private PhoneNumber fax;
    public Person(String fn,String ln){
        setFirstname(fn);
        setLastname(ln);
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public PhoneNumber getPhone() {
        return phone;
    }
    public void setPhone(PhoneNumber phone) {
        this.phone = phone;
    }
    public PhoneNumber getFax() {
        return fax;
    }
    public void setFax(PhoneNumber fax) {
        this.fax = fax;
    }
    public String toString(){
        StringBuffer sb=new StringBuffer();
        sb.append(getFirstname()).append(",");
        sb.append(getLastname()).append(",");
        //sb.append(getPhone().getCode()).append(",");
        //sb.append(getPhone().getNumber()).append(",");
        return sb.toString();
    }
}

//PhoneNumber.java
public class PhoneNumber {
    private int code;
    private String number;
    public PhoneNumber(int i, String string) {
        setCode(i);
        setNumber(string);
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
}

//Main program: SimpleConverter.java, please check at the end for these supportive jar files.

import java.io.File;
import java.io.FileOutputStream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class SimpleConverter {
    public static void main(String[] args) throws Exception {
        Person me = new Person("Deepak", "Modi");
        me.setPhone(new PhoneNumber(91, "991647****"));
        me.setFax(new PhoneNumber(80, "23658***"));
        XStream xstream = new XStream(new DomDriver());  //This will parse like a complete xml
        //XStream xstream = new XStream(new StaxDriver());   //This will parse into a String format, however this is also xml
        
        xstream.alias("person", Person.class);
        xstream.alias("phonenumber", PhoneNumber.class);
        String xml = xstream.toXML(me);
        System.out.println("Newly generated xml..");
        System.out.println(xml);
        FileOutputStream fos=new FileOutputStream(new File("person.xml"));
        fos.write(xml.getBytes());
        System.out.println("\n...XML file generation is done too, check your directory..");
        
        System.out.println("Now we will read from XML, check below output: toString() method in Person class...");
        Person duplicateMe = (Person)xstream.fromXML(xml);
        System.out.println("Output: "+duplicateMe);
    }
}
//Output, along with below content a "person.xml" will be created too:
Newly generated xml..
<person>
  <firstname>Deepak</firstname>
  <lastname>Modi</lastname>
  <phone>
    <code>91</code>
    <number>991647****</number>
  </phone>
  <fax>
    <code>80</code>
    <number>23658***</number>
  </fax>
</person>

...XML file generation is done too, check your directory..
Now we will read from XML, check below output: toString() method in Person class...
Output: Deepak,Modi,


3) Again using same Third party libraries as point-2 above but a complex converter
//MapToXmlConverter.java

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class MapToXmlConverter {
    public static void main(String[] args) throws Exception {
        Map<String,String> mp=new HashMap<String,String>();

        //Map contains: EmpId,Name
        mp.put("197","Deepak kumar modi");
        mp.put("198","Sweep panorama");
        mp.put("199","HD Video");
        mp.put("200","My Motorola Mobile");
        //System.out.println(mp);

        XStream magicApi = new XStream();
        magicApi.alias("root", Map.class);
        magicApi.registerConverter(new MapEntryConverter());

        String xml = magicApi.toXML(mp);
        System.out.println("Result of newly formed Xml:");
        System.out.println(xml);
    }
    
    public static class MapEntryConverter implements Converter {
        public boolean canConvert(Class clazz) {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet()) {
                Entry entry = (Entry) obj;
                writer.startNode(entry.getKey().toString());
                writer.setValue(entry.getValue().toString());
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Map<String, String> map = new HashMap<String, String>();
            while(reader.hasMoreChildren()) {
                reader.moveDown();
                map.put(reader.getNodeName(), reader.getValue());
                reader.moveUp();
            }
            return map;
        }
    }
}
//Output:
Result of newly formed Xml:
<root>
  <198>Sweep panorama</198>
  <199>HD Video</199>
  <200>My Motorola Mobile</200>
  <197>Deepak kumar modi</197>
</root>


4) Nested Map contents and conversion into XML
//NestedMapToXmlConverter.java
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class NestedMapToXmlConverter {
    public NestedMapToXmlConverter(){
        System.out.println("Constructor invoked..");
    }
    public static void main(String[] args) {
        Map mp=new HashMap();
        Map nestedMap=new HashMap();
        Map nestedNestedMap=new HashMap();

        //Map contains: EmpId,Name
        mp.put("197","Deepak kumar modi");
        mp.put("198","Sweep panorama");
        mp.put("199","HD Video");
        mp.put("200","My Motorola Mobile");
        //System.out.println(mp);

        //nestedMap contains: FirstName, LastName
        nestedMap.put("Deepak", "Modi");
        nestedMap.put("Sweep", "panorama");
        
        //NestedNestedMap contains: FN,Name
        nestedNestedMap.put("FN", "DEEPAK");
        nestedNestedMap.put("Object", new NestedMapToXmlConverter());
        
        nestedMap.put("NestedNestedMap", nestedNestedMap);
        
        mp.put("NestedMap", nestedMap);
        
        XStream magicApi = new XStream();
        magicApi.alias("root", Map.class);
        magicApi.registerConverter(new MapEntryConverter());

        String xml = magicApi.toXML(mp);
        System.out.println("Result of newly formed XML:");
        System.out.println(xml);

    }
    
    public static class MapEntryConverter implements Converter {
        public boolean canConvert(Class clazz) {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet()) {
                Entry entry = (Entry) obj;
                //System.out.println(entry.getValue().toString());
                writer.startNode(entry.getKey().toString());
                writer.setValue(entry.getValue().toString());
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Map<String, String> map = new HashMap<String, String>();
            while(reader.hasMoreChildren()) {
                reader.moveDown();
                map.put(reader.getNodeName(), reader.getValue());
                reader.moveUp();
            }
            return map;
        }
    }
}
//Output;
Constructor invoked..
Result of newly formed XML:
<root>
  <198>Sweep panorama</198>
  <199>HD Video</199>
  <200>My Motorola Mobile</200>
  <NestedMap>{Sweep=panorama, NestedNestedMap={FN=DEEPAK, Object=NestedMapToXmlConverter@182f0db}, Deepak=Modi}</NestedMap>
  <197>Deepak kumar modi</197>
</root>


5) For reference please check: http://xstream.codehaus.org/converter-tutorial.html

6) Required Jars for third party libraries: These below jars can be downloaded from Internet.
xstream-1.4.2.jar
kxml2-2.3.0.jar

----------------------------------------END-----------------------------------------