Saturday, August 27, 2011

How to align the value in a text box using javascript?

How to align the value in a text box using javascript?

I found various methods to do it on google, but only one of them worked for me. Hence I decided to write a post on this.

<html>
<head>
<script>
	function mytest3() {
            // This works in both IE and chrome.
            document.getElementById("y1").style.textAlign="right"; 

            // Not working.
            // document.getElementById("y1").style="text-align:right"; 

            // Following works in Chrome (But not in IE)
            // document.getElementById("y1").setAttribute("style", "text-align:right"); 

	}
</script>
</head>
<body>
	<input type="text" id="y1" name="y1" value="2" />
	<input type="button" onClick="mytest3()" value="Please click me"/>
</body>
</html>


Well, for more information why the other two options were not working.
Please have a look at the following URL under section Text Properties
http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html

Another good link to study is

http://www.webdeveloper.com/forum/showthread.php?t=81111

Well, if you like to use jquery and achive the same thing.

<html>
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
   <script type="text/javascript" src="jquery.js" language="javascript">
    </script>
    <script type="text/javascript" language="javascript"> 
		$(document).ready(function(){
			 $('#mydiv').attr("style","text-align:right");
			
		});
	
   </script>
 </head>
 <body>
	<input type="text" id="mydiv" value="2"/>
 </body>
 </html>


Another very good website for learning javascript is http://jsbin.com/#javascript,html,live

How to find nth highest salary from a table?


Code
  1. EMPNO ENAME SAL
  2. 1         A         5000
  3. 2         B         2000
  4. 3         C         10000
  5.  
  6. SELECT MIN(SAL) FROM (SELECT * FROM EMP ORDER BY SAL DESC)
  7. WHERE ROWNUM <=2

    Same as nth highest query we need to put that number instead of 2.

Sunday, August 14, 2011

Failed to create Java virtual machine

Source : http://www.techlabs4u.com/2011/08/solution-eclipse-failed-to-create-java.html

When you runt the eclipse (latest version eclipse-jee-indigo win32) , you may get the error "failed to create java virtual machine" .


This error can be solved by many ways. Assume that the eclipse is installed at the locaton d:\eclipse and Jdk is installed at the location D:\jdk1.6.0_23 

Ist Method

1. Open the ecplise.ini file which is located in the eclipse installation folder. (i.e in our example : d:\eclipse)
2. Find & Replace the line -vmargs with -vm D:\jdk1.6.0_23\bin\javaw.exe OR just remove the line -vmargs and save it . Now the problem is solved

IInd Method 

1. Create a desktop shortcut of the eclipse.exe
2. Right click on the shortcut and select properties.
3. Now the following dialog box will open. 


4. In the target textbox already d:\eclipse\eclipse.exe will be there. Now replace with D:\eclipse\eclipse.exe -vm D:\jdk1.6.0_23\bin\javaw.exe

III rd Method

1. Open the ecplise.ini file
2. It has some of add on configuration . Find the line "–launcher.XXMaxPermSize”. Now remove the the dafault value 256m and save it. 




Sunday, August 7, 2011

insert doesn't works on hibernate??


Source : http://www.coderanch.com/t/219259/ORM/java/insert-doesn-work-hibernate

insert doesn't work on hibernate


Hi,

Whenever I try to insert data through hibernate into DB, it displays all the steps executed but it doesn't insert a new row into the database. Please tell me what could be the possible cause for this.

The code for my class is

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FirstExample {

    public static void main(String[] args) {
        Session session = null;

        try {
            // This step will read hibernate.cfg.xml and prepare hibernate for use
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            //Create new instance of Contact and set values in it by reading them from form object
            System.out.println("Inserting Record");
            Contact contact = new Contact();
            contact.setId(6);
            contact.setFirstName("Deepak");
            contact.setLastName("Kumar");
            contact.setEmail("deepak_38@yahoo.com");
            session.save(contact);
            System.out.println("Done");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();

        }

    }
}

Nothing happens in a database without a transaction. Have a read of the linked Wiki entry and you should see how to fix this issue.


Below is the working code:

//Transaction object
Transaction transaction = null;

try{
    // This step will read hibernate.cfg.xml and prepare hibernate for use
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session =sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    //Create new instance of Contact and set values in it by reading them from form object
    System.out.println("Inserting Record");
    Contact contact = new Contact();
    contact.setId(6);
    contact.setFirstName("Deepak");
    contact.setLastName("Kumar");
    contact.setEmail("deepak_38@yahoo.com");
    session.save(contact);
    /*This bit ur missing*/
    transaction.commit();
    System.out.println("Done");
}


Friday, August 5, 2011

How to read a properties file in a web application

Source : http://jaitechwriteups.blogspot.com/2007/01/how-to-read-properties-file-in-web.html

How to read a properties file in a web application


The code to do this is pretty simple. But going by the number of people who keep asking this question, i thought i would post the code over here. Let's consider that you have a war file named SampleApp.war which has a properties file named myApp.properties at it's root :

SampleApp.war
   |
   |-------- myApp.properties
   |
   |-------- WEB-INF
                |
                |---- classes
                         |
                         |----- org
                                 |------ myApp
                                           |------- MyPropertiesReader.class

Here root folder in war is equivalent to Source Folder in Netbeans.
That means you have to keep your properties file in default package of your Source Files folder.
Let's assume that you want to read the property named "abc" present in the properties file:

----------------
myApp.properties:
----------------

abc=some value
xyz=some other value

Let's consider that the class org.myApp.MyPropertiesReader present in your application wants to read the property. Here's the code for the same:


package org.myapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Simple class meant to read a properties file
 * 
 * @author Jaikiran Pai
 * 
 */
public class MyPropertiesReader {

    /**
     * Default Constructor
     * 
     */
    public MyPropertiesReader() {

    }

    /**
     * Some Method
     * 
     * @throws IOException
     * 
     */
    public void doSomeOperation() throws IOException {
        // Get the inputStream
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("myApp.properties");

        Properties properties = new Properties();

        System.out.println("InputStream is: " + inputStream);

        // load the inputStream using the Properties
        properties.load(inputStream);
        // get the value of the property
        String propValue = properties.getProperty("abc");

        System.out.println("Property value is: " + propValue);
    }

}

Pretty straight-forward. Now suppose the properties file is not at the root of the application, but inside a folder (let's name it config) in the web application, something like:




SampleApp.war
   |
   |-------- config
   |           |------- myApp.properties   
   |           
   |
   |-------- WEB-INF
                |
                |---- classes
                         |
                         |----- org
                                 |------ myApp
                                           |------- MyPropertiesReader.class




There will just be one line change in the above code:

public void doSomeOperation() throws IOException {
        //Get the inputStream-->This time we have specified the folder name too.
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("config/myApp.properties");
        
        Properties properties = new Properties();
         
        System.out.println("InputStream is: " + inputStream);
        
        //load the inputStream using the Properties
        properties.load(inputStream);
        //get the value of the property
        String propValue = properties.getProperty("abc");
        
        System.out.println("Property value is: " + propValue);
    }


That's all that is required to get it working.

Thursday, August 4, 2011

java.lang.NoClassDefFoundError: javax/swing/GroupLayout$Group

I had written an application in NetBeans and made a jar out of it. When I transferred that jar to my office computer and tried executing it there, I got the following exception.



Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: javax/swi
ng/GroupLayout$Group
at classfinder.ClassFinderApp.startup(ClassFinderApp.java:19)
at org.jdesktop.application.Application$1.run(Application.java:171)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

After comparing lots of things, I found no difference, and finally I decided to google it. And on google I found that jre version was lower in my office computer.

On my laptop, its jre 1.6 and on my office PC, its jre 1.5

When I tried executing the same jar with version 1.5 i was able to reproduce the same exception.

Tuesday, August 2, 2011

How to access embedded iframe's internal elements?

How do I access internal form elements of iframe which is embedded in an HTML page.

Ofcourse document.forms[0] will give me the first form in the parent document. But what I need is the form of the iframe.

Here is the solution

Example:
Test.html
==========
<html>
<head><title>Dynamic Content</title>
<script language="JavaScript">
 function testFun()

 {
    var doc = document.getElementById('myframe').contentWindow.document;
   alert(doc.forms[0].textbox.value);
 }

</script>
</head>
<body>
<iframe src="b.html" name="myframe"></iframe><BR>
<input type="button" onclick="testFun()" value="Submit"></input>
</body>
</html>

b.html
=======
<html>
<body>
<form name="aaa" action="aaa">
<input type=text name="textbox"></input>
<input type="submit"></input>
</form>
</body>
</html>

Monday, August 1, 2011

MD5 encryption and decryption

Today a friend needed to decrypt a password which was encrypted using md5 algorithm. So I got an anxiety to study more about it.

Here is some information that I have gathered about it

  1. MD5 is a secure hash algorithm. It takes a string as input, and produces a 128-bit number, the hash.
  2. The same string always produces the same hash, but given a hash, it is not generally possible to determine the original string.
  3. Secure hash algorithms are useful for protecting passwords and ensuring data integrity

Now, I wanted to know, how do I use it with my web-applications. Thank God there are inbuilt libraries of JQuery that provides support.
You can get jQuery and jquery.md5.js from the following links : jQuery.js and jQuery.md5.js

This example might be a very basic level of encryption of md5.
There are various more secure encryptions available for md5, but at this point in time, I have this much understanding.

Example HTML :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MD5 Encryption Example</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.md5.js"></script>

<script type="text/javascript">
function chn(){
 var a = document.getElementById('txt1');
 var b = document.getElementById('txt2');
 var c= a.value;
 
 var d = $.md5(c);
 b.value = (d);
}

</script>

</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <label>
    <input type="text" name="jh" id="txt1"  onblur="chn();"/>
  </label>
  <label>
    <input type="text" name="q" id="txt2" />
  </label>
</form>
</body>
</html>