Tuesday, July 27, 2010

JTable row sorter and filter by example

In swing JTable, table sorting and filtering is managed by sorter Object. We can set autoCreateRowSorter property to true like as-

JTable myTable = new JTable();
myTable.setAutoCreateRowSorter(true);

It creates a row sorter that is an instance of javax.swing.table.TableRowSorter. This provides a table that does a simple locale-specific sort when the user clicks on a column header.
For more specific sorting, we need to construct an instance of TableRowSorter and specify the sorter for table object.

TableRowSorter sorter = new TableRowSorter( myTable.getModel());
myTable.setRowSorter(sorter);

TableRowSorter uses java.util.Comparator objects to compare its rows. Comparator class that implements this interface need to override compare method of Comparator interface. You can create comparator object this way also-

Comparator comparator = new Comparator() {
public int compare(String s1, String s2) {
// some code that return 0,-1,1 based on your compare logic
}
};

You can specify the comparator using following method of sorter object

public void setComparator(int column, Comparator comparator)

Filtering of rows in JTable:
For filtering of JTable rows you need to specify javax.swing.RowFilter object in sorter like.
Create a RowFilter Object or use inbuilt RowFilter’s static object dateFilter, numberFilter, regexFilter.
And then specify the filter object in sorter

sorter.setRowFilter(rowFilterObject);

That’s it.

Sunday, July 25, 2010

Javascript Interview Question - Part3

How to write a script for "Select" lists using JavaScript?
1. To remove an item from a list set it to null
mySelectObject.options[3] = null
2. To truncate a list set its length to the maximum size you desire
mySelectObject.length = 2
3. To delete all options in a select object set the length to 0.
mySelectObject.leng

Text From Your Clipboard?
It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server

What does the "Access is Denied" IE error mean?
The "Access Denied" error in any browser is due to the following reason.
A JavaScript in one window or frame is tries to access another window or frame whose
document's domain is different from the document containing the script.

Is a JavaScript script faster than an ASP script?
Yes. Since JavaScript is a client-side script it does require the web server's help for its
computation, so it is always faster than any server-side script like ASP, PHP, etc..

Are Java and JavaScript the Same?
No. java and JavaScript are two different languages.
Java is a powerful object - oriented programming language like C++, C whereas JavaScript is a client-side scripting language with some limitations.

How to embed JavaScript in a web page?
JavaScript code can be embedded in a web page between

What Boolean operators does JavaScript support?
Boolean operators in JavaScript are as under
&&, || and !

What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.

How to get the contents of an input box using JavaScript?
Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;
How to determine the state of a checkbox using JavaScript?
Determining the state of a checkbox in JavaScript
var checkedP = window.document.getElementById("myCheckBox").checked;

This entry was originally published at Experts Support Blog

Javascript Interview Question - Part2

What is JavaScript?
JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.
JavaScript is a platform-independent, event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

What’s relationship between JavaScript and ECMAScript?
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision

How do you submit a form using JavaScript?
Use document.forms[0].submit()
(0 refers to the index of the form – if we have more than one form in a page, then the first one has the index 0, second has index 1 and so on).


How to read and write a file using JavaScript?
I/O operations like reading or writing a file is not possible with client-side JavaScript. However , this can be done by coding a Java applet that reads files for the script


How to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.


What are JavaScript Data Types?
JavaScript Data Types are Number, String, Boolean, Function, Object, Null, Undefined 7 :: How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (" 3F" , 16)


How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array()
We can add elements to this array like this
scripts[0] = " PHP"
scripts[1] = " ASP"
scripts[2] = " JavaScript"
scripts[3] = " HTML"
Now our array scripts have 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2. Here is the way to get the third element of an array.
document.write(scripts[2])
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25)


How do you target a specific frame from a hyperlink in JavaScript?
Include the name of the frame in the target attribute of the hyperlink in JavaScript. < a href=”http://www.globalguideline.com” target=”myframe”> Global Guide Line< /a>


What are a fixed-width table and its advantages in JavaScript?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, in JavaScript resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width in JavaScript, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

This entry was originally published at Experts Support Blog

Friday, July 23, 2010

Javascript Interview Question - Part1

What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

What is a prompt box?
A prompt box allows the user to enter input by providing a text box.

What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst?
The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.

How about 2+5+"8"?
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.


What is the difference between SessionState and ViewState?
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.


What does the EnableViewStateMac setting in an aspx page do?
Setting EnableViewStateMac=true is a security measure that allows ASP. NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP. NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed.
Use to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.


What looping structures are there in JavaScript?
JavaScript supports the for loop, while loop, do-while loop, but there is no foreach loop in JavaScript.


How to put a "close window" link on a page?
Use javascript://window.close() link like this
Close


How to hide JavaScript code from old browsers that don't run it?
Use the below specified style of comments
or Use the tags and code the display html statements between these and this will appear on the page if the browser does not support JavaScript


How to comment JavaScript code?
Use // for a single line comments in JavaScript and
/* start of Multiple lines comment in JavaScript
Multiple line comments in JavaScript
*/ for block comments in JavaScript


Name the numeric constants representing max, min values?
Number.MAX_VALUE


What does JavaScript null mean?
The null value is a unique value representing no value or no object.
It implies no object, or null string, no valid Boolean value, no number and no array object.


How do you create a new object in JavaScript?
Create a new object in JavaScript

{code type="javascript"}

var obj = new Object();
//or
var obj = {};
How do you assign object properties?
obj["age"] = 17;
//or
obj.age = 17; {/code}


What’s a way to append a value to an array?
Way to append a value to an array in JavaScript
arr[arr.length] = value;


What is this keyword?
In JavaScript this keywork refers to the current object.


How to set the focus in an element using Javascript?
Setting the focus in an element using JavaScript


How to access an external JavaScript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
where abc.js is the external JavaScript file to be accessed.

Can JavaScript code be broken in different lines?
Breaking is possible within a string statement by using a backslash at the end but not within any other javascript statement. i.e.
{code type="javascript"}document.write("Hello world");{/code}
is possible but not

{code type="javascript"} document.write
("hello world");{/code}

This entry was originally published at Experts Support Blog

Thursday, July 22, 2010

JQuery Interview Question - Part3

Explain the concepts of "$ function" in jQuery with an example?
The type of a function is "function". There are a lot of anonymous functions is jquery.

{code type="javascript"}
$(document).ready(function() {});

$("a").click(function() {});

$.ajax({
url: "someurl.php",
success: function() {
}
});
{/code}

Why is jQuery better than JavaScript?
* jQuery is great library for developing ajax based application.
* It helps the programmers to keep code simple and concise and reusable.
* jQuery library simplifies the process of traversal of HTML DOM tree.
* jQuery can also handle events, perform animation, and add the Ajax support in web applications.

When can you use jQuery?
JQuery can be used to apply CSS, call functions on events, traverse the documents, manipulation purpose and to add effects too.

Advantages of jQuery.
The advantages of using jQuery are:
* JavaScript enhancement without the overhead of learning new syntax
* Ability to keep the code simple, clear, readable and reusable
* Eradication of the requirement of writing repetitious and complex loops and DOM scripting library calls

Explain the features of jQuery?
Features of jQuery are :
* Effects and animations
* Ajax
* Extensibility
* DOM element selections functions
* Events
* CSS manipulation
* Utilities - such as browser version and the each function.
* JavaScript Plugins
* DOM traversal and modification

This entry was originally published at Experts Support Blog

Wednesday, July 21, 2010

JQuery Interview Question - Part2

How can we apply css in odd childs of parent node using JQuery library.

$(”tr:odd”).css(”background-color”, “#bbbbff”);

How can we apply css in even childs of parent node using JQuery library.

$(”tr:even”).css(”background-color”, “#bbbbff”);

How can we apply css in last child of parent using JQuery library.

$(”tr:last”).css({backgroundColor: ‘yellow’, fontWeight: ‘bolder’});

How can we modify css class using JQuery library.

Suppose that Css class has following defination
.class
{
font-size:10px;
font-weight:normal;
color:#000000;
}

now we want to add border property on above class, so we should follow below code.

$(".class").css("border","1px solid blue");
Where $(".class") name of css class. Now .class will automatically add border property in his class definition.

How can we apply css in div element using JQuery library.

This is example to apply css on a div element which have id name myDivId.
$(”#myDivId “).css(”border”,”3px solid red”);
To apply css on all div elements use below code.$("div").css("border","3px solid red");

Where$("div") pointing all div elements in the page.For You need to use.$(”P”) on above code.

How can we submit a form by ajax using Jquery.

Please follow below code to submit a form by ajax using jquery

$('#formid).submit(function() {
$.ajax({
type: "POST",
url: "back.php",
data: "name=php&location=india",
success: function(msg) {
alert( "Data Saved: " + msg );
}
});
}

Where formid is the form ID."POST" is the method by which you want to send data.You can also use "GET" method."back.php" is the php file which you want to call."name=php&location=india" This is values of control. success: function(msg){ alert (“Data Saved: " + msg); } This is a success function, This will execute after success of you post.Often in Ajax back.php does not refresh because this is cached by browser. To avoid this issue add [cache: false,] in above code.Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.

To avoid this issue add [async: false,] in above code.

How can we get value of textbox in jquery.

Include jquery library in the head section of page. Then use below code.
$("#id").val();
jQuery(“#id”).val();

What is Jquery? How Jquery will work?

Jquery is lightweight javascript library file.
Jquery run in all browsers.
Jquery is client side scripting language.
Jquery browser depended framework.
Jquery developed by javascript.

Jquery combined with other library?

Jquery combined with other java script libraries like prototype, mootools that time Jquery coding will be conflict with other libraries.
So that time use this command for non -conflict jquery with other java script libraries.
jQuery.noConflict();

This entry was originally published at Experts Support Blog

JQuery Interview Question - Part1

What is Jquery?

JQuery is Java Script library or Java Script Framework which helps in how to traverse HTML documents, do some cool animations, and add Ajax interaction to any web page. It mainly helps programmer to reduce lines of code as huge code written in Java Script, can be done easily with JQuery in few lines.

What are the different type of selectors in Jquery?

There are 3 types of selectors in Jquery
1. CSS Selector
2. XPath Selector
3. Custom Selector

Name some of the methods of JQuery used to provide effects?

Some of the common methods are :
1. Show()
2. Hide()
3. Toggle()
4. FadeIn()
5. FadeOut()

What are features of JQuery or what can be done using JQuery?

Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling
What is JQuery UI?

JQuery UI is a library which is built on top of JQuery library. JQuery UI comes with cool widgets, effects and interaction mechanism.
What are the steps you need to follow to use jQuery in ASP.Net project?

It's really simple. One just need to add reference of javascript file(.js). Go to Jquery.com and download the latest version of jQuery. When download is completed, there is a "jQuery-1.3.2.js" in the folder. Include this file and you good to go now for JQuery.
How is body onload() function is different from document.ready() function used in jQuery?

Document.ready() function is different from body onload() function because off 2 reasons.
1. We can have more than one document.ready() function in a page where we can have only one onload function.

2. Document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

What does dollar Sign ($) means in JQuery?
Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code
$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery " keyword.
jQuery(document).ready(function(){
});

This entry was originally published at Experts Support Blog

Monday, July 19, 2010

Posting request to server via java class using URLConnection

Posting request to server via java class using URLConnectionHere we will discuss with example how to sent a POST request to a server with attached parameters. Two parameters are sent in the example code below, name and gender.
We use the URL and URLConnection classes to open the connection to the destination. Then the output stream is retrieved by calling getOutputStream() on the URLConnection object.
With the output stream we can write the parameters and then start reading the response from the server using the input stream which we get by calling getInputStream() on the same URLConnection object.
We assume there will only be character based content returned from the server so we use the BufferedWriter to read the response line by line.


Code:
public void sendPostRequest() {
//Building parameter string
String params = "name=vipin&gender=male";
try {
// Send the request
URL url = new URL("http://www.esblog.in");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//Write parameters
writer.write(params);
writer.flush();
// Get the response
StringBuffer response = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
writer.close();
reader.close();
//Output the response
System.out.println(response.toString());
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Friday, July 16, 2010

Passing javascript variable to PHP

There is lots of way to pass the php script data in javascript like simply echoing php varible in PHP. Yes you can simply echo php varibale in javascript within php tag like

<?php
$a = "hello";
?>

<script type="text/javascript">
function test() {
var str = '<?php echo $a ?>';
}
</script>


You can also pass php data into javascript function as a function parameter to use in javascript.


<script type="text/javascript">
function test(a) {
var str = a;
}
</script>

<input type="button" onclick="test('<?php echo $a ?>')">


Not the question is can you pass the javascript variable into PHP?

As per my concern there is no direct method to pass javascript variable into php becuase there is no way to execute client side script(javascript) into server side(PHP).So you have to send the javascript data into server.To send the javascript data into server you have to send HTTP/Ajax request as we do normally through ajax/HTTP Post/HTTP GET request.

This entry was originally published at Experts Support Blog

Thursday, July 15, 2010

Changing the Look and Feel (LAF) of swing UI

Architecture of swing is so designed that you can change the look and feel of GUI at run time easily for your applications. By default swing provides java look and feel (Metal).

There are various looks and feel available in SUN’s JRE

  1. CrossPlatformLookAndFeel: This is java look and feel and looks same on all platforms. It is part of java api (javax.swing.plaf.metal) and is default if you do nothing in your code to set different look and feel.
  2. SystemLookAndFeel: In this application uses native look and feel to the system it is running on.System LAF is determined at run time.
  3. Synth: you can create your look and feel with an XML file.
  4. Multiplexing: Way to show numbers of different look and feel at the same time.

Various system vendors’ look and feel as following

  1. Solaris, Linux with GTK+ 2.2 or later: GTK+
  2. Other Solaris, Linux: Motif
  3. IBM UNIX: IBM*
  4. HP UX: HP*
  5. Classic Windows: Windows
  6. Windows XP: Windows XP
  7. Windows Vista: Windows Vista
  8. Macintosh: Macintosh*

Programmatically setting the look and feel:

We can specify the look and feel using UIManager.setLookAndFeel() method with the fully qualified name of the appropriate subclass of LookAndFeel .

public static void setNativeLookAndFeel() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch(Exception e) {}

}

public static void setJavaLookAndFeel() {

try {

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

} catch(Exception e) { }

}

public static void setMotifLookAndFeel() {

try {

UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

} catch(Exception e) { }

}


PHP Connection Status & Connection handling

Internally in PHP a connection status is maintained. There are 3 possible states:

* 0 - NORMAL
* 1 - ABORTED
* 2 - TIMEOUT

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache .conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache .conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.

Compressing/Wrapping the response in J2EE application

I am sharing techniques for j2ee based web applications, this is very simple to configure with your web application
-------------------------------------------------------------------------------------------
Below are the steps to implement the compression filter in j2ee applications, this filter compress all the request resources to server, wrap the response and make faster response to your browser.

Steps:-

1: Compression Filter module: First you need to download the filter package to integrate this module to your java web application.Click here to download the file.

2: Now you need to define the filter mapping in web.xml file, following is the filter mapping xml, that you need to embed in web.xml under the <web-app>tag

<filter>
<filter-name>compressionFilter</filter-name>
<filter-class>//(Fully classified filter class name)
filter.CompressionFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>compressionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Thats it...
Cheers 8)

File Uploading Using PHP Curl

File uploading through PHP Curl is very simple. You just have to append @ in front of path of file name & send it to upload handler page as Post parameter.

Suppose input type file name is "image" like <input type ="file" name="image">
Then use the following PHP curl code to upload the file.

<?php

$ch = curl_init();
$url = "http://example.com/upload_handler.php";
// URL where file uploading is handled.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
"image"=>"@/path/to/mypic.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);

?>

Use of Stack Class

I am sharing how to use the Stack class. Hope it will be very useful for you.

A Stack adds and removes elements on a First-In First-Out basis.
The key methods of the Stack class are push(), peek(), pop(), empty() and search().


Method description:
push() - adds an element to the top of the stack.
peek() - returns the first element from the top of the stack without removing it from the stack.
pop() - as peek() but removes it from the stack.
empty() - checks if there are elements in the stack or not.
search() - returns the position of an element in the stack.

//Create the Stack instance and add a couple of elements to it
Stack stk = new Stack();

String s1 = "item 1";
String s2 = "item 2";

stk.push(s1);
stk.push(s2);

Now we have two elements in the stack, and to check what element is at the top of the stack (and will be the first to be removed) we use the peek() method to find out.

System.out.println(stk.peek());

The output is:
item 2

To find out the position of the first element, we use the method search().

//Find position of a certain element
int pos = stk.search("item 1");
System.out.println(pos);

This will print out the position within the stack.
2

To remove elements from the stack, we use the method pop().

System.out.println(stk.pop());
System.out.println(stk.pop());

OutPut:
item 2
item 1

The 'item 2' was added after 'item 1' so that element is removed first.
Now the stack is empty, and to be sure we check with the empty method:

stk.empty();
It returns true