Thursday, December 23, 2010
simple method to convert date to timestamp in java
Timestamp currentTimeStamp = new Timestamp(date.getTime());
return currentTimeStamp;
}
Monday, November 22, 2010
PMD and CPD For Eclipse
PMD
From http://pmd.sourceforge.net/
PMD scans Java source code and looks for potential problems like:
- Possible bugs - empty try/catch/finally/switch statements
- Dead code - unused local variables, parameters and private methods
- Suboptimal code - wasteful String/StringBuffer usage
- Oercomplicated expressions - unnecessary if statements, for loops that could be while loops
- Duplicate code - copied/pasted code means copied/pasted bugs
CPD
From http://pmd.sourceforge.net/cpd.html
Duplicate code can be hard to find, especially in a large project. But PMD's Copy/Paste Detector (CPD) can find it for you! CPD has been through three major incarnations:
- First we wrote it using a variant of Michael Wise's Greedy String Tiling algorithm (our variant is described here)
- Then it was completely rewritten by Brian Ewins using the Burrows-Wheeler transform
- Finally, it was rewritten by Steve Hawkins to use the Karp-Rabin string matching algorithm
XmlToHtmlConverter
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
public class XmlToHtmlConverter {
public static void main(String[] args) {
try {
String xmlFile = "src/xml/xml.xml";
String xsltFile = "src/xslt/xslt.xsl";
String outFile = "src/html/html.html";
Source xmlSource = new StreamSource(xmlFile);
Source xsltSource = new StreamSource(xsltFile);
Result ouput = new StreamResult(new FileOutputStream(outFile));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
transformer.transform(xmlSource, ouput);
System.out.println("Html got generated");
} catch (Exception e) {
e.printStackTrace();
}
}
}
http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog
from this URL download the xml and xsl and try to give input to the above java file..
you will be getting the corresponding html.
Thursday, October 28, 2010
Wednesday, October 27, 2010
Can we count Total Number of lines and packages in our eclipse project
update your eclipse with the following url ....after doing this restart your eclipse..
http://metrics.sourceforge.net/update
For more information............checkout this....
http://metrics.sourceforge.net/
Sunday, October 24, 2010
Error message(Could not validate document )while building the project
Monday, October 11, 2010
Syntax to run the batch file in UNIX BOX
Lets say I have a file called startProcess.sh in my unix box.
we should run the above file like sh startProcess.sh thats all our process is started.
suppose some one has the file with the file name as stopProcess.fg in their unix box
so he can run the above file like sh stopProcess.fg
along with this if you want to create a backup we have to use mv soucefile backupfilename thats all
Friday, October 8, 2010
AJAX Tutorial for Java Programmers
- Java. You should be comfortable in the Java programming language.
- HTML. You should know HTML, and be familiar with HTML attributes and styles.
For More Details Check Out :- http://www.jaxtut.com/
JSP Tutorial for Java Programmers
- HTML. You should be able to put together HTML pages.
- Java. You should be able to program in Java.
Friday, October 1, 2010
What is Fit?
Fit lets customers and analysts write “executable” acceptance tests using simple HTML tables.
Developers write “fixtures” to link the test cases with the actual system itself.
Fit compares these test cases, written using HTML tables, with actual values, returned by the system, and highlights the results with colors and annotations.
More info is available here...
http://fitnesse.org/.FitNesse.UserGuide
Tuesday, September 28, 2010
A fundamental question about JPA
The answer is that JPA is not a new technology; rather, it has collected the best ideas from existing persistence technologies like Hibernate, TopLink, and JDO. The result is a standardized specification that helps you build a persistence layer that is independent of any particular persistence provider.
Monday, September 20, 2010
Issue while starting the server in a debug mode for webapplication.
We may get debug launching error while trying to start our server in a debug mode for web application in Web Logic 8.1 or 10.3.
There Could be a Problem with our port number
We have to Make sure that whether we are using correct port number in our eclipse or not. In order to check that go to the startWebLogic.cmd file under the bin dir of your weblogic8.1 or 10.3. There you will find one property called SAVE_JAVA_OPTIONS under this there is a attribute called address. For example in my local mechine I have address=1044. So I have to use 1044 in my eclipse as well.
Thursday, September 16, 2010
Refer the cheat sheet while creating Relations in Hibernate
Monday, September 6, 2010
Have you ever thought the RDBMS is the cause of making your application more scalable
Checkout:- http://www.mongodb.org/
Can we write constructors in servlets ?
A nice comparison between enterprise messaging providers. expand
We chose a simple set of performance benchmarks to measure throughput with the most common messaging use cases, from lightweight publish/subscribe messaging to persistent point-to-point messaging.
Checkout:- https://community.jboss.org/wiki/HornetQ-thePerformanceLeaderinEnterpriseMessaging
Recommand to check LOGGER.isDebugEnabled when writing log statements....
Example:- LOGGER.isDebugEnabled or LOGGER.isInfoEnabled
Logger hierarchy ( DEBUG INFO WARN ERROR FATAL )
Let say we have few logger statements in our project.
Example:
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
Assume that your logger level is set to INFO then we should only see the message those are
Sample info message
Sample warn message
Sample error message
Sample fatal message
It works fine but it will evaluate logger.debug("Sample debug message"); statement even though it won't print because our logger level is info.
If you take memory and time factor into the consideration then use like this....
if(LOGGER.isDebugEnabled){
logger.debug("Sample debug message");
}
...........then it won't evaluate logger.debug("Sample debug message"); statement. It will check the condition and terminates because as per our discussion currently INFO is Enabled.
If you got any WARN LIKE Please initialize the log4j system properly
Example: If Tomcat 6, drop it in Tomcat's lib folder and it will apply for all web apps.
Checkout:- http://www.coderanch.com/t/458568/Application-Frameworks/Application-Frameworks/log-j-WARN-Please-initialize
Wednesday, September 1, 2010
Simple method for checking the valid String
if (value != null && value.trim().length() > 0)
return true;
return false;
}
Simple method for checking the valid collection
if (collection != null && collection.size() > 0)
return true;
return false;
}
Wednesday, August 18, 2010
Different message types in JMS
http://publib.boulder.ibm.com/infocenter/wmbhelp/v7r0m0/index.jsp?topic=/com.ibm.etools.mft.doc/ac24862_.htm
RemoveCharacters from a given string
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
public static void main(String[] args) {
removeChar r = new removeChar();
System.out.println(r.getOnlyNumerics("USDOT549189"));
}
}
Monday, July 26, 2010
Data from a given website and use it in our application
http://web-harvest.sourceforge.net/
Refer the cheat sheet while creating Relations in Hibernate..... expand »
Tuesday, May 18, 2010
Open Source Web Frameworks in Java
Have a look into those..............
http://java-source.net/open-source/web-frameworks
Wednesday, April 28, 2010
Are we happy enough ???
Yesterday, I was on the way back to home after work, and the FM radio went off for few seconds. I thought, I should have an iPod. Then suddenly I realized that I have not used my iPod in last 6 months. And then… more things, Handy cam in last 2 years, Digital Camera in last 2 months, DVD player in last 1 month and many more. Now I can say that I bought that Handy cam just out of impulse, I have used it twice only in last 4 years.
So, what’s wrong and where? When I look at myself or my friends I can see it everywhere. We are not happy with what we have but all are stressed and not happy for the things we don’t have. You have a Santro, but you want City… You have a City, but you want Skoda. Just after buying a new phone, we need another one. Better laptop, bigger TV, faster car, bigger house, more money… .I mean, these examples are endless. The point is, does it actually worth? Do we ever think if we actually need those things before we want them?
After this, I was forced to think what I need and what I don’t. May be I didn’t need this Handy cam or the iPod or that DVD player. When I see my father back at home. He has a simple BPL colour TV, he doesn’t need 32″ Sony LCD wall mount. He has a cell phone worth Rs 2,500. Whenever I ask him to change the phone, he always says… “Its a phone, I need this just for calls.” And believe me; he is much happier in life than me with those limited resources and simple gadgets. The very basic reason why he is happy with so little is that he doesn’t want things in life to make it luxurious, but he wants only those things which are making his life easier. It’s a very fine line between these two, but after looking my father’s life style closely, I got the point. He needs a cell phone but not the iPhone. He needs a TV but not the 32″ plasma. He needs a car but not an expensive one.
Initially I had lot of questions.
I am earning good, still I am not happy…...why ?
I have all luxuries, still I am stressed.... ....... why ?
I had a great weekend, still I am feeling tired...... why?
I met lot of people, I thought over it again and again, I still don’t know if I got the answers, but certainly figured out few things. I realize that one thing which is keeping me stressed is the “stay connected” syndrome. I realized that, at home also I am logged in on messengers, checking mails, using social networks, and on the top of that, the windows mobile is not letting me disconnected. On the weekend itself, trying to avoid unwanted calls… and that is keeping my mind always full of stress. I realized that I am spending far lesser money than what I earn, even then I am always worried about money and more money. I realized that I am saving enough money I would ever need, whenever needed. Still I am stressed about job and salary and spends.
May be, many people will call this approach “not progressive attitude”, but I want my life back. Ultimately it’s a single life, a day gone is a day gone. I believe if I am not happy tonight, I’ll never be happy tomorrow morning. I finally realized that meeting friends, spending quality time with your loved one’s; spending time with yourself is the most important thing. If on Sunday you are alone and you don’t have anybody to talk with, then all that luxuries life, all that money is wasted. May be cutting down your requirements, re-calculating your future goal in the light of today’s happiness is a worthwhile thing to do. May be selling off your Santro and buying Honda City on EMIs is not a good idea. I believe putting your happiness ahead of money is the choice we need to make.
I think, a lot can be said and done but what we need the most is re-evaluation of the value of happiness and time we are giving to our life and people associated with it.
Anyone interested in reading the latest features and enhancements in MS SQL Server 2008 R2 , please download the free e-book from
Tuesday, April 27, 2010
The Java Memory Architecture
http://blog.codecentric.de/en/2010/01/java-outofmemoryerror-1-akt-das-java-memory-modell-stellt-sich-vor/
Java OutOfMemoryError
http://blog.codecentric.de/en/2010/01/java-outofmemoryerror-eine-tragodie-in-sieben-akten/
Google Chat on Mobile Phone
Can we do a google chat , yahoo chat , and many more by using only GPRS ?....
we can say yes to the above question by looking into this Nimbuzz application...
step:1 open google in u r phone
step:2 type Nimbuzz and go for the search.
step:3 select u r mobile type like w810i..
step:4 get the jar Ex: director.jar
step:5 intsall and then start the application.
Simply Singleton
Provide a global point of access to the object.
public class SimpleSingleton {
private static SimpleSingleton instance = null;
protected SimpleSingleton() {
// Exists only to defeat instantiation.
}
public static SimpleSingleton getInstance() {
if (instance == null) {
instance = new SimpleSingleton();
}
return instance;
}
}
Take a look into the above class which is having a protected constructor and a public method getInstance().
There are several interesting points concerning the SimpleSingleton class. First, SimpleSingleton employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance()
method is called for the first time. This technique ensures that singleton instances are created only when needed.
Second, notice that SimpleSingleton implements a protected constructor so clients cannot instantiate SimpleSingleton instances; however, you may be surprised to discover that the following code is perfectly legal:
public class SimpleSingletontest extends TestCase {
public void testsing() {
SimpleSingleton instance = SimpleSingleton.getInstance();
SimpleSingleton anotherInstance = new SimpleSingleton();
Assert.assertEquals(true, instance == anotherInstance);
}
}
So, the first problem is lazy instantiation inorder to aviod that make few changes to SimpleSingleton...
public class SimpleSingleton {
private static SimpleSingleton instance = new SimpleSingleton();;
protected SimpleSingleton() {
// Exists only to defeat instantiation.
}
public static SimpleSingleton getInstance() {
return instance;
}
}
The second one is if we are declaring constructor as protected. There may be chanece of getting two objects. So we are violating the singleton pattern so make the constructor as private...
public class SimpleSingleton {
private static SimpleSingleton instance = new SimpleSingleton();;
private SimpleSingleton() {
// Exists only to defeat instantiation.
}
public static SimpleSingleton getInstance() {
return instance;
}
}
A third interesting point about SimpleSingleton , if SimpleSingleton implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances
In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.
public class SimpleSingleton implements Serializable {
// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return getInstance();
}
}
Note: The readResolve() method was added defaultly from java 1.5 (no need to write separately).
• Finally, and perhaps most important, Example 1's SimpleSingleton class is not thread-safe. If two threads—we'll call them Thread 1 and Thread 2—call SimpleSingleton.getInstance() at the same time, two SimpleSingleton instances can be created if Thread 1 is preempted just after it enters the if block and control is subsequently given to Thread 2
public class Singleton {
private static Singleton singleton = null;
private static boolean firstThread = true;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
System.out.println(" time "+ System.currentTimeMillis());
if (singleton == null) {
simulateRandomActivity();
singleton = new Singleton();
}
System.out.println("created singleton: " + singleton);
return singleton;
}
private static void simulateRandomActivity() {
try {
if (firstThread) {
firstThread = false;
System.out.println("sleeping...");
// This nap should give the second threadenough time
// to get by the first thread.
Thread.currentThread().sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Sleep interrupted");
}
}
}
Following is the test class to test Singleton
import junit.framework.Assert;
import junit.framework.TestCase;
public class SingletonTest extends TestCase {
private static Singleton singleton = null;
public SingletonTest(String name) {
super(name);
}
public void setUp() {
singleton = null;
}
public void testUnique() throws InterruptedException {
// Both threads call Singleton.getInstance().
Thread threadOne = new Thread(new SingletonTestRunnable()),
threadTwo = new Thread(new SingletonTestRunnable());
threadOne.start();
threadTwo.start();
threadOne.join();
threadTwo.join();
}
private static class SingletonTestRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
// Get a reference to the singleton.
Singleton s = Singleton.getInstance();
// Protect singleton member variable from multithreaded access.
synchronized(SingletonTest.class) {
if(singleton == null) // If local reference is null...
singleton = s; // ...set it to the singleton
}
// Local reference must be equal to the one and only instance of Singleton; otherwise, we have two
// Singleton instances.
System.out.println("Thread finished");
Assert.assertEquals(true, s == singleton);
}
}
}
If u test this output is:
Thread started
time 1272456665200
sleeping...
Thread started
time 1272456665200
created singleton: Singletonwithmultythreading.Singleton@471e30
Thread finished
created singleton: Singletonwithmultythreading.Singleton@10ef90c
Thread finished
junit.framework.AssertionFailedError: expected:
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:149)
at junit.framework.Assert.assertEquals(Assert.java:155)
at Singletonwithmultythreading.SingletonTest$SingletonTestRunnable.run(SingletonTest.java:38)
at java.lang.Thread.run(Thread.java:534)
so inorder to avoid that add the synchronized to the getInstance() method. So that it will hold the first object once the first object lefts the method second object can cal that method.
package Singletonwithmultythreading;
public class Singleton {
private static Singleton singleton = null;
private static boolean firstThread = true;
protected Singleton() {
// Exists only to defeat instantiation.
}
public synchronized static Singleton getInstance() {
System.out.println(" time "+ System.currentTimeMillis());
if (singleton == null) {
simulateRandomActivity();
singleton = new Singleton();
}
System.out.println("created singleton: " + singleton);
return singleton;
}
private static void simulateRandomActivity() {
try {
if (firstThread) {
firstThread = false;
System.out.println("sleeping...");
// This nap should give the second thread enough time
// to get by the first thread.
Thread.currentThread().sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Sleep interrupted");
}
}
}
Now if you test it will pass all with green lights by junit...
Output:-
Thread started
Thread started
time 1272457018077
sleeping...
created singleton: Singletonwithmultythreading.Singleton@471e30
time 1272457019077
created singleton: Singletonwithmultythreading.Singleton@471e30
Thread finished
Thread finished
http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html#resources