Thursday, May 17, 2012

Memory Level

--> heap memory: collected by the garbage collector.
--> local variables (stack memory): collected automatically when methods exit.
--> immortal memory: never collected.
-->scoped memory: available for collection when the associated reference count equals zero.

Wednesday, May 2, 2012

Typing artificially


import java.awt.Robot;
import java.awt.event.KeyEvent;

public class TypingArtificially
{
public static void main(String args[])
{
    try
    {
    Runtime.getRuntime().exec("notepad.exe");
    Thread.sleep(2000);
    Robot r=new Robot();
    r.keyPress(KeyEvent.VK_T);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_H);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_I);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_S);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_SPACE);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_I);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_S);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_SPACE);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_F);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_U);
    Thread.sleep(500);
    r.keyPress(KeyEvent.VK_N);
  
    }
    catch(Exception e)
    {
      
    }
}
}

Task manager


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TaskManager
{
public static void main(String args[])
{
    try {
        String line;
        Process p = Runtime.getRuntime().exec("tasklist.exe");
        BufferedReader input =
                new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println(line); //<-- Parse data here.
        }
        input.close();

    } catch (Exception err) {
        err.printStackTrace();
    }
}
}

Screen capture with java

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ScreenCapture {
public static void main(String args[])
{
    try
    {
     Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
     Robot robot = new Robot();
     BufferedImage img = robot.createScreenCapture(new Rectangle(size));
     File save_path=new File("screen.bmp");
     ImageIO.write(img, "JPG", save_path);
    }
    catch(Exception e)
    {
      
    }
}
}

Clip Bord content display through java

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class ClipBoard
{
public static void main(String args[])
{
     Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

        try {
            if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                String text = (String)t.getTransferData(DataFlavor.stringFlavor);
            System.out.println("Current ClipBoard data is:\n"+text);
            text="I changed clipboard text";
                StringSelection ss = new StringSelection(text);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
                System.out.println("Changed ClipBoard data is:\n"+text);
            }
        }
        catch(Exception e)
        {
          
        }
}
}

file downloading from net through java code


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AutoDownload
{
    public static void main(String args[]) throws IOException
    {
        System.out.println("Enter the url to download from =>");
          BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
          String site = input.readLine();
          System.out.println("Enter filename =>");
          BufferedReader input1 = new BufferedReader(new InputStreamReader(System.in));
          String filename = input.readLine();
    java.io.BufferedInputStream in = new java.io.BufferedInputStream(new     
    java.net.URL(site).openStream());
    java.io.FileOutputStream fos = new java.io.FileOutputStream(filename);
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
    byte[] data = new byte[1024];
    int i=0;
    while((i=in.read(data,0,1024))>=0)
    {
    bout.write(data,0,i);
    }
    bout.close();
    in.close();
    }
}

core java practice imp points

Arrays.sort() ; ---> object[]
Collections.sort()-->list
s = new TreeSet(s);  --->sortedset

we can use like this.

Collection c=new ArrayList();


1) if we r storing some integer objects and some  Sting objects into array if we  r  trying to apply sorting then it wil give class cast exception.
2)string object ni object reference ki pas cheya vachu kani object instance ni string refarenceki pass cheyalem we must cast it explicitly.
3) treeset ki pas chesina elements bydefault sorted order inascending.
4) we can cal a static method in non static method directly without object instance.
5) super class lo and child  class lo same methods vuna super class reference ni child class ga cast chesina child reference numchi methods cal cheste adi child class methods ne cal chestumdi if it is not available then it go for  super .but where as in the constructor point of view it is reverse.
6)try block lo declare chesina variable catch block scope loki radu.
7)inner class instantiation method  in outer class .
             Line.Point p = new Line.Point();
8)child class lo superclass constructor values veryfirst line of child class constructor cal cheyali if super class dosant  declared default constructor we canot cal default constructor in child class.
9) enum type object ki switch default value suport cheyadu.
10)enums ni function out side declare cheyali.
11)subclass refarence ni parent class ki pass cheyavachu kani parent class refarence ni child class ki pass cheyalem.
12) Global and static variable need not be initialized before use but if u specify final then u must intialize. Default value of global and
static int variable is zero. Default value of boolean variable is false. Remember local
variable must be initialized before use.
a) method argument's add(int x,int y) vunna we can pass x value short then internally it follows autoboxing but static method
lo non static method  direct ga vadalaem , But non static method lo veroka method ni cal cheyavachu.
2) primitive int value bydefault 0 for either static variable or non static variable and boolean bydefault false
int k; --> 0
boolean istrue; --> false
static int p; --> 0

3) Global and static variable need not be initialized before use but if u specify final then u must intialize.. Default value of global and static int variable is zero. Default value of boolean variable is false. Remember local
   variable must be initialized before use.we canot assign a value to final variable second time.
4) $7 is valid identifier. Identifiers must start with a letter, a currency character ($), or
underscore ( _ ). Identifiers cannot start with a number. You can't use a Java keyword as
an identifier. do is a Java keyword.

5) class Animal (super class ) class Cat (child class) and class Test if we pass cat refarence to animal animal in differenct package and default class class then  , Cat class won't compile because its superclass, Animal, has default access and is in a different package. Only public superclass can be accessible for different package.

6)If you create object of subclass with reference of super class like ( A a = new B();) then
subclass method and super class variable will be executed.

7) (6Q) As an enum cannot be instantiated using the new operator, the constructors cannot be
called explicitly. You have to do like Test t = BREAKFAST;  dont use like Test t=new BREAKFAST

8)First execute static block, then statement block then constructor.
9)By placing a zero in front of the number is an integer in octal form. 010 is in octal form
so its value is 8.

10) int or smaller expressions always resulting in an int. So compiler complain about Type
mismatch: cannot convert from int to byte for b = b+7; But b += 7; // No problem
because +=, -=, *=, and /= will all put in an implicit cast. b += 7 is same as b = (byte)b+7
so compiler not complain.

    byte b=8;
    b+=8; // as b = (byte)b+8
    b=b+7; //wrong

11) Java pass reference as value. passing the object reference, and not the actual object itself.
Simply reassigning to the parameter used to pass the value into the method will do
nothing, because the parameter is essentially a local variable.



12) Primitive widening uses the smallest method argument possible. (For Example if you
pass short value to a method but method with short argument is not available then
compiler choose method with int argument). But in this case compiler will prefer the
older style before it chooses the newer style, to keep existing code more robust. var-args
method is looser than widen.

13) no of repetetion words program
public class Test {
    public static void main(String args[]) {
        String text = "hi this is english is as so is ";
        //String[] words = new String[] {"aaa", "bbb", "ccc", "aaa","aaa","AAA"};
        String[] words = text.split(" ");
        Map<String, Integer> m = new TreeMap<String, Integer>();
        for (String word : words) {
            Integer freq = m.get(word);
            System.out.println("-freq-->" + freq + "-word-->" + word);
            m.put(word, freq == null ? 1 : freq + 1);
        }
        System.out.println(m);
    }
}

14) javac -d classes src/Test.java
   in the above command  from  src folder we are moving class file to classes

15) superclass method with throws exeception  ni subclass lo  Overridden cheste adi child class lo must ga exception handle cheyali
ex: public int doIt(String str, Integer... data)throws Exception{


it throws like --> Unhandled exception type Exception.

16) doubt

    for(int i = 1; i < 4; i++)
for(int j = 2; j < 4; j++)
if(i < j)
assert i!=j : i;

17)  n struts  html:form use cheste path ki .do avsaram ledu adenormal form ayite .do vadali.

18) From J2SE 5.0 onwards. return type in the overriding method can be same or subtype of
the declared return type of the overridden (superclass) method.

19) You can not override private method , private method is not availabe in subclass .
        and a class have show mwthod and b class also show method but b extends a then if i cla the show method method form b object then it will cla from b class ;

  20) The overriding method can throw any unchecked (runtime) exception, regardless of
exception thrown by overridden method. NullPointerException is RuntimeException so
compiler not complain.

   parent lo Filenotfound
   child lo NulllPointer



ex :  A a=new B();
   a.show();


21) in interface if we use the method in this fo((B)b).test2(); is proper cast. test2() method is in class B so need to cast b then only
test2() is accessible. (B)b.test2(); is not proper cast without the second set of parentheses,
the compiler thinks it is an incomplete statement.rmat then

protected String getName();
Illegal modifier for the interface method InfA.getName(); only public and abstract are
permitted

22) if there is already a constructor in ur class (public D(int i,int j)), the compiler won't supply a default constructor. If you want a no-argument constructor to overload the witharguments version you already have, you have to define it by yourself. The constructor D() is undefined in class D. If you define explicit constructor then default constructor will not be available. You have to define explicitly like public D(){ } then the above code will
work. If no constructor into your class , a default constructor will be automatically
generated by the compiler.

23) ((B)b).test2(); is proper cast. test2() method is in class B so need to cast b then only
test2() is accessible. (B)b.test2(); is not proper cast without the second set of parentheses,
the compiler thinks it is an incomplete statement.

24) x *= 3 + 7; is same as x = x * (3 +7) = 5 * (10) = 50 because expression on the right is
always placed inside parentheses.
 Foo fo=(Alpha)(Beta)(Delta)x;
Foo -->interface
Alpha -->super class
Beta --> child class
Delta --> child class
11)String jstr=json==null?"":json.toString();
12) 34 pending

25) An array is always an instance of Object
26)  If the left hand operand is not a String then + operator treat as plus BUT if left hand
operand is a String then + perform String concatenation.

int a =5 , b=6, c =7;
System.out.println("Value is "+ b +c);
System.out.println(a + b +c);
System.out.println("String "+(b+c));

27) On the time of deserialization , the Serializable object not create new object. So
constructor of class B does not called. A is not Serializable object so constructor is called.

28)if  Class A does not implements Serializable interface. So throws NotSerializableException
on trying to Serialize a non Serializable object.

29)static variables are not serialaizable

Tuesday, May 1, 2012

logging in Java

 
         

logging in Java


basic java logging level e.g. DEBUG, INFO, WARN and ERROR.

DEBUG is the lowest restricted java logging level and we should write everything we need to debug an application, this java logging mode should only be used on Development and Testing environment and must not be used in production environment.

INFO is more restricted than DEBUG java logging level and we should log messages which are informative purpose like Server has been started, Incoming messages, outgoing messages etc in INFO level logging in java.

WARN is more restricted than INFO java logging level and used to log warning sort of messages e.g. Connection lost between client and server. Database connection lost, Socket reaching to its limit. These messages and java logging level are almost important because you can setup alert on these logging messages in java

ERROR is the more restricted java logging level than WARN and used to log Errors and Exception, you can also setup alert on this java logging level and alert monitoring team to react on this messages. ERROR is serious for logging in Java and you should always print it.

FATAL java logging level designates very severe error events that will presumably lead the application to abort. After this mostly your application crashes and stopped.

OFF java logging level has the highest possible rank and is intended to turn off logging in Java.

These java logging levels are based on log4j logging level and little bit different than java.util.logging API

I agree java.util.logging API is also very powerful but I find log4j more intuitive and easy to use than java.util.

Another flexibility of log4j is that you can change logging level of your java application without restarting your java application
Log4j also provides flexibility to set logging level based on per class in its configuration file log4j.xml.

logging in Java affects performance
Java logging severely affects performance of your application. Its quite common sense that more you log, more you perform file IO which slows down your application.

So always log DEBUG messages inside isDebugEnabled () block as shown in below example of debug mode in java.

if(logger.isDebugEnabled()){
logger.debug("java logging level is DEBUG Enabled");


Uses either WARN ERROR or FINER, FINEST java logging level in production environment.

1) Use isDebugEnabled() for putting debug log in Java , it will save lot of string concatenation

2) Carefully choose which kind of message should go to which level for logging in Java

If you log too much information your performance will be affected

Use either log4j or java.util.logging for logging in Java, I would recommend log4j because I have used it a lot and found it very flexible.

By using log4j.xml you can have different logger configuration for different java classes as well. You can have some classes in INFO mode, some in WARN mode or ERROR mode.

Another important point to remember is format of java logging, this you specify in logger. Properties file in case of java.util.logging API for logging to use which java logging Formatter. Don’t forget to include Thread Name and fully qualified java class Name while printing logs because it would be impossible to find sequence of events if your code is executed by multiple threads without having thread name on it. In my opinion this is the most important tips you consider for logging in Java.

By carefully choosing format of  java logging at logger level and format of writing log you can have generate reports from your java log files.

while writing message for logging in Java try to use some kind of prefix to indicate which part of your code is printing log e.g. client side , Database site or session side, later you can use this prefix to do a "grep" or "find" in Unix and have related logs at once place.

For example you can put all Database level log with a prefix "DB_LOG:" and put all session level log with prefix "SESSION_LOG:”

If a given logger is not assigned a level, then it inherits one from its closest ancestor. That’s why we always assign log level to root logger in configuration file log4j.rootLogger=DEBUG.

Both no logging and excessive logging is bad so carefully planned what to log and on which level you log that messages so that you can run fast in production environment and at same time able to identify any issue in QA and TEST environment.

I found that for improving logging its important you look through your log and monitor your log by yourself and tune it wherever necessary.

if you are using SLFJ for logging in java use parametrized version of various log methods they are faster as compared to normal method.


General Info

   How to improve concentration
1. Memory
    Remembering names after the first introduction
    Recalling the location of objects
    Keeping track of several ideas at the same time
    Learning new subjects quickly and accurately

2) Attention
    Improving productivity and precision at work or home
    Concentrating while learning something new
    Maintaining focus on important tasks all day
    Avoiding distractions

3) Speed
    Decision-making in time-sensitive situations
    Adapting to changing environments
    Reacting quickly
    Speeding up cognitive processes

4)  Flexibility
    Thinking outside the box
    Avoiding errors
    Multi-tasking quickly and efficiently
    Communicating clearly

5. Problem Solving
    Calculating figures in your head
    Determining the best course of action
    Dissecting complex arguments
    Making quick and accurate estimations