Thursday, November 22, 2012

What is OpenID?

OpenID is a decentralized authentication protocol that makes it easy for people to sign up and access web accounts.

Yahoo, Google and facebook are all OpenID providers, so simply implementing it on your site will be enough for your users to be able to login using them

OpenID allows you to use an existing account to sign in to multiple websites, without needing to create new passwords.

You may choose to associate information with your OpenID that can be shared with the websites you visit, such as a name or email address. With OpenID, you control how much of that information is shared with the websites you visit.

With OpenID, your password is only given to your identity provider, and that provider then confirms your identity to the websites you visit. Other than your provider, no website ever sees your password, so you don’t need to worry about an unscrupulous or insecure website compromising your identity.

Source: http://openid.net/get-an-openid/what-is-openid/

Spring security 3 - OpenId Login with Google Provider also posible


Wednesday, June 6, 2012

Crystal Report Memory problem

how to ensure proper cleanup of reports
 
It is particularly important if your application comes under load.Reports left open take up resources, which, if left unchecked, can starve your app of resources, leading to performance degradation, report request denial, and out of memory problems.And one more thing is it will block the database resources also.
Destroy every  ReportSource
Every time a ReportClientDocument opens a report rpt file,the reference count for that report instance is incremented.  Every time an unique ReportSource is retrieved from the ReportClientDocument, the count is incremented.Every time a ReportClientDocument is closed, the reference count is decremented.  Every time a ReportSource is destroyed, the count is decremented.If ReportClientDocument or ReportSource is not cleaned up, then the instance will remain live and taking up resources until timeout garbage collects the object.
One important consideration is the following: even if you invoke ReportClientDocument.close(), that report may still not be closed. 
Here's a simple test: 
 (1) open a report with a ReportClientDocument.
(2) retrieve a ReportSource using the method ReportClientDocument.getReportSource().
(3) invoke the ReportClientDocument.close() method for that instance.
 (4) test the value of ReportClientDocument.isOpen() - you'll see that it's true!.
(5) pass the ReportSource object to the CrystalReportViewer, and invoke CrystalReportViewer.dispose().
(6) now check ReportClientDocument.isOpen() again - you'll see that it's false, i.e., that the instance  has been cleaned up.
Another consideration:   the only way to dispose the ReportSource is to pass it to a viewer object 
Invoking viewer dispose() will in turn invoke the proper dispose method for the ReportSource.
 
we will prove this in one more way
before opening of report in application open the sql editor and run the below query  
 
SHOW FULL PROCESSLIST
 
IT DISPLAYS NO OF PROCESS ID'S  
 
after that open the report and again run the above query one more process id created even after closing of the report process id not decreasing 
that is why with crystal reports code we are facing some memory problems. So better to use crviewer.dispose() .
        

Browser event firing when closing the browser ?.

<script>   
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
alert("action");
                   }
      }
      function unhook() {
         alert("2");
        hook=false;
      }
</script>

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

Thursday, April 26, 2012

Comparison between the three flash servers Flash Media Server, Wowza and Red5

                            Java video streaming Servers

Briefing:Today I was evaluating the difference between Wowza , Flash Media server and Red5. So decided to write this comparison matrix . This comparison versus all of these three flash servers contain the main features that are uncommon with each other . I have not mentioned the features that are common to all of them . I have tried my best to put correct info but still if you find some thing missing or incorrect then just feel free to send me message using this form . I will keep on adding new points ...

Comparison table

Feature
Flash Media Server(FMIS 4.5)
Wowza Media
Server 3
Red5
Protocols supported

RTMP
RTMPT
RTMPS
RTMPE
RTMPTE
RTMFP
RTMP
RTMPT
RTMPS
RTMPE
RTMPTE

RTMP
RTMPT
RTMPS
RTMPE
RTMPTE
Developer edition 10 Connections (Free) 10 Connections (Free) Free
Pricing $4500 $995
(30 day Trial also available)
Daily License (5$)
Monthly License (55$)
Free(Open Source)
Supported Platforms Microsoft® Windows Server® 2003 with Service Pack 2 or Windows Server 2008
Linux® Red Hat® 4 or 5.2
Runs as a 32-bit software on both 32- and 64-bit operating systems.
Windows
Mac OS X
Linux
Solaris
Unix
64-bit Support on all
IPv6 Support
Windows
Debian/Ubuntu
Mac OSX
WAR
Gentoo


Audio / Video Streaming (live and on-demand) FLV
H.264

FLV
MP3
AAC, LC-AAC, HE-AAC
Speex
FLV
H.264

FLV
MP3
AAC, LC-AAC, HE-AAC
Speex
(On Demmand)
FLV
MP3
F4V
MP4
AAC
M4A

(Live)
Sorenson
VP6
h.264
Nelly Moser
MP3
Speex
AAC
NSV
Multi Client/ Multi Protocol Streaming Flash (RTMP / HTTP)
iPhone/iPad (HTTP Streaming)
Flash (RTMP)
iPhone/iPad (HTTP Streaming)
Silverlight (Smooth Streaming)
QucikTime/3GPP (RTSP/RTP)
IPTV (MPEG-TS)
Flash (RTMP)
Recording H.264/AAC to FLV container
MPEG-4
H.264/AAC to FLV container
H.264/AAC to MP4 (Quicktime) container
FLV Only
Inbound Live Encoder Support RTMP (Flash & H.264/AAC) RTMP (Flash & H.264/AAC)
RTSP / RTP / MPEG-TS
(H.264/AAC: unicast, multicast, TCP, UDP)
ICY (MP3/AAC: SHOUTcast/ icecast)

Action Method Format 3 (AMF3) AMF3(Uni-directional ) AMF3(Bi-directional ) AMF3
Server Side AS2 Java Java


Jar file to exe conversion tools?.

For window OS here i am listing all the tool for converting jar files to exe Executable.
These tools are also used for deployment purpose or setup maker.

1. Excelsior JET

2. JSmooth
6. IzPack

7. JExecreater

8. ExeJ

9. Executer

10. Jar2Exe

11. Advace Installer

12. JExePack

13. Xenoage

14. NativeJ

 15. JNC
 

Wednesday, April 25, 2012

How to execute your jar file by double clicking on it ?

Any jar package for executing will need a file named MANIFEST.MF which located in META-INF directory in that package. In that file you can tell VM where to find main method of your program to start execution.netbeans by default will generate an executable jar file (I mean JVM executable package and not binary exe file!) when you build your project as Desktop Application.If  you copy only that jar file out side of build directory then this application will not work then the error like could not find main class the program will exit.we can make our normal jar files as executable jars just by add proper manifest file with main class some thing like below.

   Suppose if  you are working with DB application you can specify database driver jar in manifest class-path attribute.


 
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.x.x 
Created-By: 1.x.x (Sun Microsystems Inc.)
Class-Path: mysql-connector-java-5.0.6-bin.jar    
X-COMMENT: Main-Class will be added automatically by build 
Main-Class: path.to.main.class