Wednesday, August 29, 2012

Monday, August 27, 2012

get substring using javascript

stringName.substring(from, to)

ex:

var mystr="hello";

alert(mystr.substring(0,2));

result:  "hel"

alert(mystr(2));

result: "llo"

get data of a cell in a table using javascript

go to required "td" tag (tdTag)
alert(tdTag.innerHTML);

xpath creater from node using javascript


function createXPathFromElement(elm) {
    var allNodes = document.getElementsByTagName('*');
    for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
    {
        if (elm.hasAttribute('id')) {
                var uniqueIdCount = 0;
                for (var n=0;n < allNodes.length;n++) {
                    if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
                    if (uniqueIdCount > 1) break;
                };
                if ( uniqueIdCount == 1) {
                    segs.unshift('id("' + elm.getAttribute('id') + '")');
                    return segs.join('/');
                } else {
                    segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
                }
        } else if (elm.hasAttribute('class')) {
            segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
        } else {
            for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
                if (sib.localName == elm.localName)  i++; };
                segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
        };
    };
    return segs.length ? '/' + segs.join('/') : null;
};

function lookupElementByXPath(path) {
    var evaluator = new XPathEvaluator();
    var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return  result.singleNodeValue;
}

remove directory using bat file

rmdir /s /q "C:\PGP Corporation" 

how to make a zip file using windows default zipping in bat file



This will create someArchive.zip file which included english.txt


 set FILETOZIP=c:\english.txt


    set TEMPDIR=C:\temp738
    rmdir %TEMPDIR%
    mkdir %TEMPDIR%
    copy %FILETOZIP% %TEMPDIR%

    echo Set objArgs = WScript.Arguments > _zipIt.vbs
    echo InputFolder = objArgs(0) >> _zipIt.vbs
    echo ZipFile = objArgs(1) >> _zipIt.vbs
    echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
    echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
    echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
    echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
    echo wScript.Sleep 2000 >> _zipIt.vbs

    CScript  _zipIt.vbs  %TEMPDIR%  C:\someArchive.zip

    pause

Tuesday, August 21, 2012

how set environment variable using bat file

You can set environment variable using bat file in two different ways.

method 1:
This method is temporary way.It will set environment variable while executing the bat file
let say i want set environment varable MY_HOME as my c://windows drive

set MY_HOME=c://windows


method 2:
This method will set the environment variable permanently to user environment variable category.That mean that variable only valid for that user account.This is use a vb script to set that environment variable.But no need to install vb on your machine.vbscript just like bat commands but different.

write the vb script name in bat file (in my case it's name is demo.vbs)

my bat file:


@echo OFF
demo.vbs


vb script: (in this case inside c://windows folder)


Set objShell = WScript.CreateObject("WScript.Shell")
Set colUsrEnvVars = objShell.Environment("USER")
Set fso = CreateObject("Scripting.FileSystemObject")
colUsrEnvVars("MY_HOME") = fso.GetParentFolderName(wscript.ScriptFullName) 





Remeber:  This vbscript should be in the directory c://windows folder.Because it's add the system variable as the path where it's included.

**remember to restart the machine after run this bat.


Monday, August 20, 2012

delete a file using java


This delete the file f1

File f1 = new File(file);
  boolean success = f1.delete();
  if (!success){
  System.out.println("Deletion failed.");
  System.exit(0);
  }else{
  System.out.println("File deleted.");
    }

Writing a DOM Document to an XML File


// This method writes a DOM document to a file
public static void writeXmlFile(Document doc, String filename) {
    try {
        // Prepare the DOM document for writing
        Source source = new DOMSource(doc);

        // Prepare the output file
        File file = new File(filename);
        Result result = new StreamResult(file);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
}

get an input from user using java popup

This will ask input from the user and store it in name variable

String name = JOptionPane.showInputDialog ( "String input text" )


demo:

open default web browser using java in widows


This method will open your default web browser in windows and open the url "www.google.lk"

String url="www.google.lk";  //add required url here
 try {
             String osName = System.getProperty("os.name");
                    if (osName.startsWith("Windows"))
                           Runtime.getRuntime().exec(
                                "rundll32 url.dll,FileProtocolHandler " + url);
} catch (Exception ex) {
}

java swing :Adding and Removing an Item in a JList Component

The default model for a list does not allow the addition and removal of items. The list must be created with a DefaultListModel.


// Create a list that allows adds and removes
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);

// Initialize the list with items
String[] items = {"A", "B", "C", "D"};
for (int i=0; i<items.length; i++) {
    model.add(i, items[i]);
}

// Append an item
int pos = list.getModel().getSize();
model.add(pos, "E");

// Insert an item at the beginning
pos = 0;
model.add(pos, "a");



This method replaces an item:
// Replace the 2nd item 
pos = 1; 
model.set(pos, "b");

These methods are used to remove items:
// Remove the first item
pos = 0;
model.remove(pos);

// Remove the last item
pos = model.getSize()-1;
if (pos >= 0) {
    model.remove(pos);
}

// Remove all items
model.clear();

refferd from: 
http://www.exampledepot.com/egs/javax.swing/list_listaddrem.html


java swing : Getting the Selected Items in a JList Component

The following methods return the indices of the selected items:


// To create a list, see Creating a JList Component

// Get the index of all the selected items
int[] selectedIx = list.getSelectedIndices();

// Get all the selected items using the indices
for (int i=0; i<selectedIx.length; i++) {
    Object sel = list.getModel().getElementAt(selectedIx[i]);
}

// Get the index of the first selected item
int firstSelIx = list.getSelectedIndex();

// Get the index of the last selected item
int lastSelIx = list.getMaxSelectionIndex();

// Determine if the third item is selected
int index = 2;
boolean isSel = list.isSelectedIndex(index);

// Determine if there are any selected items
boolean anySelected = !list.isSelectionEmpty();

Friday, August 17, 2012

how to read xml file using java

This is a really good blog which explain clearly how to read xml file using java.

http://gardiary.wordpress.com/2011/03/10/read-xml-file-in-java-using-sax-parser/

what is firebug

        Firebug is a nice tool basically developed as firefox extension.Although it is a firefox extension now it also developed as a google chrome extension.Firebug using for debug the web applications.It is help to find the errors in web pages.It shows the html codes and other web page related stuff itself.So user can edit the code and see the results in real time.
     
        Many of web developers use this extension because of the easyness of usage.Also quality assurance people also use this to find element xpath and other related details for testing purposes.So it is really need to having some basic knowledge about this usefull tool.In this post i will give a basic introduction about it.

First of all let's install firebug in firefox.

1.Open firefox browser

2.Go to below link and click install firebug button
     http://getfirebug.com/



when install it some popup will come and ask to allow the program.So you have to allow it.After installing firefox asks to restart.So click restart to restart the firefox.

3.After firefox restarting, see the right hand bottom corner of the fire fox.you will see an icon like below.













4.click on that icon.Then firebug will open.



5.Open a any web page and click on the firebug icon.Then firebug window will open.After that right click on an any element of the web page and click inspect element option from the popup menu.

   Then all the details about that element will show in the firebug window.Such as element id,name etc..
Also you can edit the html code and see the changes in the webpage in real time.

This is only a basic introduction.If you really interest you can go through some tutorials in the internet.I hope to post another post about how to develop our own extension for firefox and firebug.


Thursday, August 16, 2012

sony new phones

There are new phones will remove within next few weeks from sony.

Sony xperia tipo, sony xperia tipo dual

Sony xperia dual has dual sim facility with android 4.0. This is the first dual sim phone made by sony.




SPECIFICATIONS

for xperia tipo dual: http://www.sonymobile.com/global-en/products/phones/xperia-tipo-dual/ 

for xperia tipo: http://www.sonymobile.com/global-en/products/phones/xperia-tipo/specifications/#black


set java home using putty


set jdk home ("/opt/jdk_1.6/" is the path of java installation in server which i use)

export JAVA_HOME=/opt/jdk_1.6/

set jre home

export JRE_HOME=/opt/jdk_1.6/jre

get time stamp using java


class:

package com.mkyong.common;

import java.sql.Timestamp;
import java.util.Date;

public class GetCurrentTimeStamp
{
    public static void main( String[] args )
    {
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
    }
}



output

2010-03-08 14:59:30.252