Tuesday, 2 September 2014

Calling JavaScript function in href vs. onclick

Background

There are multiple ways to call a Javscript function in an anchor tag. You can put the method in href attribute or you can use onclick event or jquery events. This post is about good practices while calling a javascript function in such a scenario.


Usage in order of  increasing good practice


<a id="myLink" href="javascript:MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

But the best practice as of now is to use jquery and attach an even handler to the elements id. Something like -

$('#myLink').click(function()

  {

     MyFunction();

     return false;

  }); 

 Notes

  • The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
  • In case javascript is enabled adding return false in  onclick will will prevent browser from following the link.
  •  If you don't have a link in href attribute you should do javascript:void(0) rather than # in the href attribute.  '#' will take the user back to the top of the page if it is present in the href attribute and onclick is not returning false.

 

Related Links


Saturday, 30 August 2014

JAXB Tutorial

JAXB

JAXB stands for JAVA Architecture for XML bindings. We will come to it in some time. Before that we need to understand a even basic concept - Serialization. Simply speaking Serialization is the process of turning an object in memory into a stream of bytes so that it can be transferred over a network or stored in a persistent storage.


There are various ways to serialize an object. For eg.

  1.  Serialization via XML. Convert the Object to XML transfer it and then convert it back to XML. 
  2. You can do the save via JSON (Javascript object notation).
  3. Or you can use the Serialization provided by Java i.e by making your class implement Serilizable interface.
In this post we will see how can we serialize/de-serialize Objects to and from xml.

Note : The verbs Marshal and Unmarshal are synonymous with Serialize and Deserialize. Specially in XML serialization you will hear the words   Marshal and Unmarshal very frequently.


Dependencies ??

If you are using JDK 6 or higher version you don't have to worry about any dependencies as JAXB comes bundled with it. If you are using a lower version that Java 6 then you can download the jars from here. Download and add “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

 To the code....

First Create a model class file in package opensourceforgeeks.model. Lets call it Employee.java . Add the following code to it.
package opensourceforgeeks.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 * @author athakur
 *
 */

@XmlRootElement
public class Employee {

    private String name;
    private int age;
    private int id;
    
    public String getName() {
        return name;
    }
    
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", id=" + id + "]";
    }

}
 


Next lets create a class to test this out.  Create class JAXBTest.java under package opensourceforgeeks.test. Add the following code to it and run - 

package opensourceforgeeks.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import opensourceforgeeks.model.Employee; 
/**
 * 
 * @author athakur
 *
 */ 
 public class JAXBTest {

    public static void main(String args[]) {

        Employee employee = new Employee();
        employee.setName("Aniket");
        employee.setAge(23);
        employee.setId(101);

        try {

            File file = new File("C:\\Users\\athakur\\Desktop\\data.txt");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            
            System.out.println("Serializing Data");
            //Serilization
            //put the xml in the file
            jaxbMarshaller.marshal(employee, file);
            //also print it on standard ouput
            jaxbMarshaller.marshal(employee, System.out);
            
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            
            System.out.println("Deserializing Data");
            //Deserialization
            //read the xml to get the Object
            Employee newEmployee = (Employee) jaxbUnmarshaller.unmarshal(file);
            System.out.println(newEmployee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }


    }

}
Your project structure should look like below - as per above conventions of-course. You are free to put the code anywhere you like :)


Output : 

On the standard output console you can see - 

Serializing Data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="101">
    <age>23</age>
    <name>Aniket</name>
</employee>
Deserializing Data
Employee [name=Aniket, age=23, id=101]

You can also verify the data in the file whose path you have provided. XML should be generated in that file. It will have same XML as shown on standard output. For more details you can refer to the tutorial provided on the JAXB official site.

Summary

Its quite self explanatory - the bindings and the conversion. Got the following diagram from the web that explains it in simplest way -



Related Links

Sunday, 24 August 2014

Enabling telnet client on Windows 7

Background

A terminal emulation or telnet is a program for TCP/IP networks such as the Internet. The Telnet program runs on your computer and connects your PC to a server on the network. You can then enter commands through the Telnet program and they will be executed as if you were entering them directly on the server console. (More on Wiki)

If you type telnet in your windows console you will see command not found


That's because telnet client is not enabled by default on Windows. Lets see how can we enable it.

To enable Telnet command line utilities:

  1. Click Start > Control Panel.
  2. Click Programs and Features.
  3. Click Turn Windows features on or off.
  4. In the Windows Features dialog box, check the Telnet Client check box.
  5. Click OK. The system installs the appropriate files. This will take a few seconds to a minute.

Screenshots





And telnet client should be enable in your windows. You can just type telnet and check. It should open Microsoft telnet client. Or you can try directly connection to a host.

Eg. telnet alt4.gmail-smtp-in.l.google.com 25



Related Links

Saturday, 23 August 2014

TortoiseSVN icons not showing up under Windows 7

Problem

Not to brag about it but SVN is probably the most widely used versioning system. It is used in most of the top companies. Now here is the problem I faced not once but twice. Tortoise SVN  (download) is a widely used UI based svn client. It supports all basic svn operations and has a nice UI for looking at the history, diffs and merge.  It even has nice overlay images to denote if you file is updated , modified or has some conflict. It so happens in windows 7 that after installing the software the overlay images do not appear. I have used it for almost a year now without any problem but today when I tried to configure it same problem appeared (overlay images not showing up). So below I will provide the simplest way to resolve this.



Solution

Once you have installed the software and overlay icons do not show up simply repair the installation.

From the TortoiseSVN lead developer (2010-04-17) : "You might have to do a repair install (start the installer again, then choose 'repair') after you've updated to 1.6.8. Otherwise the overlay icons might not show up properly. Sorry for the inconvenience."

You can do it the following way

  1. Launch the setup again and select repair.

  2. On next screen select next.

  3. In the next screen you will see the applications that the repair wizard will attempt to restart. Avoid selecting second option as you will unnecessarily have to reboot your machine. Two important applications that will restart are
    1. Svn status cache and
    2. Windows Explorer


    Other applications may include any svn processes that may be still in progress like checkout of a branch.

That should do it. But if it is still not resolved I suggest go through the links in "Related Links" sections. There are some useful answer on Stack overflow. But mind most of them include playing with system registry. Unless you are sure do not mess with it :).






Related Links

Sunday, 17 August 2014

Reading password from command line in Java using java.io.Console

Background

Sometime we need to get passwords from the user. Passwords is a very crucial and secret information. We generally show the text while entering password as '*' characters or not display the characters at all. Java provides in built facility to enter passwords that are not echoed while entering. We are going to see this example.

Documentation

We are going to use readPassword() method of Console class is java.io package.

Method documentation is as follows - 

   /**
    * Reads a password or passphrase from the console with echoing disabled
    *
    * @throws IOError
    *         If an I/O error occurs.
    *
    * @return  A character array containing the password or passphrase read
    *          from the console, not including any line-termination characters,
    *          or <tt>null</tt> if an end of stream has been reached.
    */
    public char[] readPassword() {
        return readPassword("");
    }


Code Example


/*
 * author : athakur
 */

public class HelloWorld {
    
    public static void main(String args[]) throws IOException {
        Console console = System.console();
        if(console == null) {
            //This is a bug in eclipse IDE
            //password will be shown on console
            System.out.println("Could not get Console. Falling back to default input mechanism");
            System.out.println("Enter password : ");
            String password = new BufferedReader(new InputStreamReader(System.in)).readLine();
            System.out.println("Password : " + password);
            //process password
        }
        else {
            //intended behavior             System.out.println("Enter password : ");
            char[] password = console.readPassword();
             System.out.println("Password : " + Arrays.toString(password));
            //process password
        }
    }
}

Generally we would store the password in DB or validate. In above code I am printing it just to demonstrate it's working. Note how the password is not printed when user types it in.



When will it fail?

You must have notices the null check in the beginning of the code. That is because there is a know bug (bug #122429) in Eclipse IDE. We cannot get Console instance. So we have added a null check. However the mechanism will work just fine in normal console.




Related Links

t> UA-39527780-1 back to top