Friday, September 3, 2010

Vaccine Scheduler

Vaccine scheduler is desktop based software built in java, swing and mysql that provides the utility to schedule the vaccination of vaccine for doctor’s client and send the reminders to clients before the scheduled date of vaccination. So it increases the probability of not missing a vaccine to vaccination at proper time. Hence it is useful for both doctors and clients (patient). This software has been built in such a way that you can configure vaccine schedule according to standards. In future a new vaccine may be introduced, so we have kept in mind of adding new vaccines. Hence it makes this software strongly configurable.

Interested in Vaccine Scheduler? Click here to contact us.


Core features:
1. New client registration:
Doctor can register new client (Patient), at the time of registration system generates the vaccine schedule for that client. Following screen shows the client information. Doctor is able to edit/update the client information. Searching for client also there integrated.


2. View Client Schedule Chart:
This provides the utility to track the client schedule. This screen shows the information about the vaccine scheduled for a client. Here you can track about due date, given date, Notification sent etc. And also able to set the status of client’s particular vaccine. Different color show different functionality.



3. Vaccine Configuration / setting:
Here you can add new vaccine. It gives you a benefit if a new vaccine is discovered in future, you can add that vaccine in this system.


On following screen you can add time periods on which vaccination is to be scheduled. This information is used in defining vaccine schedule description.

Following screen provides the utility add the schedule vaccine time and dose number for a particular vaccine.


4. Email Configuration:
This is the email smtp configuration for sending the reminder of vaccination to client.

Interested in Vaccine Scheduler? Click here to contact us.

This entry was originally published at Experts Support Blog

Centering a swing window on screen

In swing or AWT, if you initialize a frame or window by default its position start from the top left corner of screen. Some time it looks odd as we are intended to see the window/frame at center of screen.
To make a window centered, we all need to set the location of window to center with respect to screen size.
There are following steps to make a window centered.
1. Get the screen size
2. Set the window/frame location by calculating it with screen size and frame size.

See the following example.
centerOnScreen Method provide the functionality to make a window centered.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
*
* @author vipin
*/
public class CenteredFrameExample {

JFrame frame;
JLabel label;
public CenteredFrameExample() {
frame = new JFrame("Centered JFrame.");
label = new JLabel();
frame.setSize(250, 150);
frame.setPreferredSize(new Dimension(250, 150));
frame.getContentPane().add(BorderLayout.CENTER, label);
centerOnScreen(frame);
frame.setVisible(true);
frame.pack();
}

public static void main(String args[]) {
CenteredFrameExample centeredFrame = new CenteredFrameExample();
String text = "<html><divstyle='font-weight:bold;color:green;padding:5px;'>This is the centered frame...</div></html>";
centeredFrame.label.setText(text);
}

/**
* Centers a window on screen.
* <p>
* @param w The window to center.
*/
public void centerOnScreen(Window w) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

w.setLocation(screenSize.width / 2 - (w.getWidth() / 2),
screenSize.height / 2 - (w.getHeight() / 2));
}
}


That's all...

This entry was originally published at Experts Support Blog

Task scheduling in java – recurring tasks and one time occurring tasks

In this blog we will learn how to schedule a timer task to run at certain time. Java provides a facility to schedule tasks as per requirement.
java.util.TimerTask instance provides a task that can be scheduled to run one time or after scheduled periodic time. We can define actions to be performed by this timer task instance. We all need to override the run method of TimerTask class.
java.util.Timer Class provides the facility to schedule a timer task to occur in future in a separate background thread. Timer.schedule() method provides the functions to performed a task for one time or a periodic time interval. You can specify the initial delay.

Examples:
Scheduling a onetime occurring and a recurring task
MyTask.java

import java.util.Timer;
import java.util.TimerTask;
public class MyTask extends TimerTask {

// override the run method to perform a scheduled task action.
public void run() {
System.out.println("Running a task.");
}
}

MyTaskScheduler.java

import java.util.*;
public class MyTaskScheduler {
public static void main(String[] args) {
MyTask task = new MyTask();
Timer timer = new Timer();
// one time occurring task with specified 2 second initial delay and after every 1 second period.
timer.schedule (task, 2000, 1000);
// Schedule a task to run after every 1 second (1000 millisecond) – recurring task
timer.schedule( task, 1000);
}
}

We can also use Timer class’ method scheduleAtFixedRate() for recurring task.

This entry was originally published at Experts Support Blog

Wednesday, August 18, 2010

Redirect standard error from console to a file

I got some useful information to share:). hope will be helpful for java developers. How to redirect standard error?
Yes - Here is the solution:
To redirect standard error (or System.err) there's a method in the System class called setErr() which takes a PrintStream instance as argument.
See the following example:

/**
* Redirects System.err and sends all data to a file stored on disk.
*
*/
public void redirectSystemErrors() {
try {
System.setErr(new PrintStream(new FileOutputStream("error_file.txt")));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}

That's all!!!
This entry was originally published at Experts Support Blog

Sunday, August 15, 2010

Javascript Interview Questions - Part7

What is the difference between undefined value and null value?

(i) Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null

(ii) typeof undefined variable or property returns undefined whereas typeof null value returns object


What is variable typing in JavaScript?

It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows

example

i = 10;

i = "string";

This is called variable typing


Does JavaScript have the concept level scope?

No. Javascript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c, c++, java.


What are undefined and undeclared variables?

Undeclared variables are those that are not declared in the program (do not exist at all), trying to read their values gives runtime error. But if undeclared variables are assigned then implicit declaration is done .

Undefined variables are those that are not assigned any value but are declared in the program. Trying to read such variables gives special value called undefined value.


What is === operator?

In JavaScript === is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.


How to disable an HTML object?

To disable an HTML object in JavaScript use below line of code...

document.getElementById("myObject").disabled = true;


How to create a popup warning box?

Below line will help us how to create a popup warning box in JavaScript....

alert('Warning: Please enter an integer between 0 and 100.');


How to create a confirmation box?

Below line will help us how to create a Confirmation box in JavaScript....

confirm("Do you really want to launch the missile today. HuM?");


How to create an input box?

Below line will help us how to create a Input box in JavaScript....

prompt("What is your name?");


How to reload the current page?

To reload the current web page using JavaScript use the below line of code...

window.location.reload(true);


What does break and continue statements do in JavaScript?

Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop in JavaScript.


How to create a function using function constructor?

The following example illustrates this

It creates a function called square with argument x and returns x multiplied by itself.

var square = new Function ("x","return x*x");


This entry was originally published at Experts Support Blog

Friday, August 13, 2010

Javascript Interview Questions - Part6

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 3.

What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.

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);

What does isNaN function do?
Return true if the argument is not a number.

What is negative infinity?
It's a number in JavaScript, derived by dividing negative number by zero.

What boolean operators does JavaScript support?
&&, and !

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

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 looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.

How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};

How do you assign object properties?
obj["age"] = 17 or obj.age = 17.

What's a way to append a value to an array?
arr[arr.length] = value;

What is this keyword?
It refers to the current object.

What does undefined value mean in JavaScript?
Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.

This entry was originally published at Experts Support Blog

Tuesday, August 10, 2010

Javascript Interview Questions - Part5

What is the difference between the three following scenarios:

{code type = "javascript"}
var myFunction = function()
{
var person;
person;
window.person;
}

{/code}
The first is local variable, the last two are global.

How do you create an object in JavaScript?
var person = new Object; or var person = {};

How to you assign a value to an object?
person["name"] = "dave"; or person.name = "dave";

What is the difference between object and constructor in JavaScript?
Constructor works like a class, and before using, we need to create an instance. Object can be accessed directly: no instance creation.

How do you create a local and global method in a constructor?

{code type = "javascript"}
var myClass = function()
{
var PrivatMethod = function()
{
}

this.PublicMethod = function(){

}

}

{/code}

Have you heard of Douglas Crockford?
Yes he is the "inventor" of JSON.

How do you inherit from one object to another?
var Object1 = {someProp : "some value", someOtherProperty : "some other Value"};var Object2 = {someProp2 : "some value", someOtherProperty2 : "some other Value"};Object1.prototype = new Object2;//now we can alertalert(Object1.someProp2);

What debugging tools do you use?
Firebug in Firefox (console.log(); method) and Visual Studio in IE ('debug' command inserted in javascript file)

How do you delete the last element of an array in JavaScript?
array_object_variable.pop();
The pop() method in JavaScript will delete the last element of the array. Whereas the push() method will add a new element at the start of the array.

How do you get the random number between 0 and 50?
my_js_random_number = Math.floor(Math.random() * 51);
In the similar manner you can generate random number from 0 to N, you need to pass N+1 instead of 51 in this function.

How do you redirect a page using JavaScript?
To redirect to you new page or URL in JavaScript, we can use the location object.
location = ‘newpage.html’

How do you refresh the current page using JavaScript?
To refresh the current page using a javascript function, we can use the below method:
location.reload();

This entry was originally published at Experts Support Blog

Saturday, August 7, 2010

Javascript Interview Questions - Part4

What is the difference between JavaScript and Jscript?

Jscript supports more rich set of functionality/commands than the java script, through which ActiveX and local computer can be accessed. These commands are used in an intranet where the connecting computer’s configuration is known and they are all being accessed using Internet Explorer. While java script targets unknown machine configuration and Jscript cannot for which java script are suitable for internet which Jscripts are not.


What is java script and what are their functionalities?

JavaScript is a client side scripting language that is mainly used to perform client side processing to prevent server round trips and to make the user response time faster. It is widely used for validation purpose such as confirm password validation and etc. It is generally embedded within the HTML which on client side is interpreted by the browser and the scripts are copy able.


What is the main difference between Client side JavaScript and Server side Java Script? How actually they run on both side?

To state the main difference, JavaScript at the client side does not require a web server to make it run instead it uses the client’s processor for this purpose. This eradicates the portability issue. But in server side JavaScript deployment, portability, configuration are major and vast issues and requires a web server to run the script within a page before rendering its output as a response html page.


What are the methods of validating whether the form is secure?

Security of a form can be ensured by several ways some of them are:-

1.Action Attribute of the form- The form action attribute must start with https:// for ensuring the secure site.

2.Checking the Java Routine- In the Java routine the formname.action="specified URL” which should also begin with https:// for ensuring the secure site.

3.Checking the URL of the form itself whether it begins with https://

Any one of the condition should be obeyed by the web form else the form is not secured.


How can JavaScript make a Web site easier to use?

Javascripts run on the client side which saves the server roundtrip time for small processing. It means that it makes web pages more interactive as everything is not required to be submitted at the server. Let’s consider a small clock if controlled by the server then the transmission time will make the clock faulty in this case javascript is used.


What does sticky session mean in a web-farm scenario?

Sticky session is a characteristic which provides load balancing solution for web farms for re-routing the request of the session to the machine which first answered the request for that session. This ensures the session persistency in case when the session is routed to other servers. Sticky session causes uneven load distribution across servers.


How do we get JavaScript onto a web page?

The script element can directly be added inside the body of the page. It should start with the tag tag. The script can also be added to the head tag of the web page. Similarly the other way is by placing the script in a separate file which gets downloaded on the client’s machine when the page is requested.


How to change style on an element?

Cascaded Style Sheet CSS and java script has an uncanny relationship. On top of DOM CSS style rules are listed. Properties of the CSS say like font-weight are translated as myElement.style.fontWeight. The elements belonging to their class can be swapped out. For example:-


{code type="javascript"}

document.getElementById("Text").style.color = "red";

document.getElementById("Text").style.fontSize = "15";


{/code}


Discuss how can we access Elements using java script?

Each elements of JavaScript can be accessed by their names. To access the page, document element is used and to access the browser the window element is used in the script. This element’s values are required for several computing reason say validation check. For example:

var myID = windows.document.formLogin.userID.value;


What is the difference between undefined value and null value?

Undefined value having no keyword and not defined is known as undefined value. While declaring a variable it does not contain any value hence it is called as undefined value. Null value has to be specifically declared as null indicating that the variable doesn’t point at any particular location in memory. For example String str = null; declares variable str which references null.


What is decodeURI(), encodeURI() in JavaScript?

In order to transform the URL into its hexadecimal equivalent the encodeURI() and decodeURI() are used. This is done to send the characters that by default cannot be specified in a URL.

For example, the following code snippet performs the encoding of URL:


{code type="javascript"}


var uri = http://agnlosticajams.weber.com; // original URI

var encodeuri=encodeURI(uri);

document.write("necodeuri”);

var decodeuri = decodeURI(ncodeuri);

document.write(“/>decodeuri”);


{/code}


What are windows object and navigator object in JavaScript?

The top level object in java script is the windows object. It further has several other objects such as document, location, history, menu bar, name, etc. contained within itself. The global object on which client side java scripts are written is the windows object. Information regarding the client system is returned by the Navigator browser of the script. For all users Navigator browsers are the base object.


How to read and write a file using java script?

This can be done in two ways which are discussed below,

1.Using an ActiveX objects (Internet Explorer only)

Using ActiveX objects, following should be included in the code to read a file

var fso = new ActiveXObject("Scripting.FileSystemObject");

var s = fso.OpenTextFile("C:\\example.txt", 1, true);

2. By the use of JavaScript extensions which runs from the Java Script editor.

In JavaScript Extensions,

fh = fopen(getScriptPath(), 0); to open a file


Discuss the relationship between JavaScript and ECMAScript?

Javascript is a scripting language that has been widely accepted for client side web development. However it originated from ECMA standards. ECMA and livescripts are just other names of java script.


This entry was originally published at Experts Support Blog

Tuesday, August 3, 2010

Play sound file using JQuery Sound Plugin

This JQuery sound plugin provides the utility to play the audio file in background without showing the player on UI and stop the running audio file.
Plugin soundPlay function is parameterized and you can pass different argument to initialize the player. You can pass url of sound file, playerId and command as options to override the default values of soundPlay.
url: Location of sound file
playerId: id of hidden player
command: play or stop what action is to be performed. Download Demo

Following is the example to play and stop a sound file:-

First you need to include the jquery.sound.js plugin file.
Then bind the html elements to soundPlay function with specific command


<script type="text/javascript" src="js/jquery.sound.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#playLink').click(function() {
$.fn.soundPlay({url: 'music/I_Like_It_I_Love_It.mid',
playerId: 'embed_player',
command: 'play'});
$("#sound_file_name").html("I_Like_It_I_Love_It.mid");
});
$('#stopLink').click(function() {
$.fn.soundPlay({playerId: 'embed_player', command: 'stop'});

});

});

</script>

HTML code: Define the html elements that is to be bind with JQuery sound plugin.

<div id="container">
<div id="player-ui">
<div><span style="float:left">Sound File:</span><span id="sound_file_name"> </span></div>
<div>
<a href="javascript://"  id="playLink">
<img src="images/play.png" alt="Play" title="Play" />
</a>
<a href="javascript://"  id="stopLink">
<img src="images/stop.png" alt="Stop" title="Stop" />
</a>
</div>
</div>
</div>


Download a Demo

Enjoy playing sound files.

This entry was originally published at Experts Support Blog

Customize Labels in swing GUI with HTML CSS

While working on swing I face an issue with my JLabel on swing UI. I need to right a long text on a swing label and since the width of label
was fixed, due to that some text is hiding and going outside of label area, So whole text on label was not being displayed. After some while
I got the solution of problem by using html instead of plain text. Swing provides utility that support to display html on GUI. We can use
html for showing labels anywhere in gui eg on JLabel, JButton, JTable Headers' text etc

Following is the example that shows how to use HTML with swing components.
public class CustomJLabel {
JLabel label;
JFrame frame;
public CustomJLabel() {
frame = new JFrame("Custom JLabel with HTML style.");
label = new JLabel();
frame.setSize(250, 150);
frame.setPreferredSize(new Dimension(250, 150));
frame.setLocation(300, 200);
frame.getContentPane().add(BorderLayout.CENTER, label);
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
CustomJLabel customLabel = new CustomJLabel();
String text = "This is the first line."
+ "
This is the second line.
This is the third line.";
customLabel.label.setText(text);
}
}

This entry was originally published at Experts Support Blog

Monday, August 2, 2010

Manage logging in tomcat server

You can manage or restrict the logging in tomcat by setting some configurations. Configuration file present in conf/ folder of tomcat named logging.properties.
The default logging.properties specifies a ConsoleHandler for routing logging to stdout and also a FileHandler. A handler’s log level threshold can be set using SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST or ALL. The logging.properties shipped with JDK is set to INFO. You can also target specific packages to collect logging from and specify a level. Here is how you would set debugging from Tomcat. You would need to ensure the ConsoleHandler’s level is also set to collect this threshold, so FINEST or ALL should be set.
org.apache.catalina.level=FINEST

Default logger for tomcat: conf/logging.properties

——————————————————————————————————————————
handlers = 1catalina.org.apache.juli.FileHandler, 2localhost.org.apache.juli.FileHandler, \
3manager.org.apache.juli.FileHandler, 4admin.org.apache.juli.FileHandler, \
java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.FileHandler.level = FINE
1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.FileHandler.prefix = catalina.

2localhost.org.apache.juli.FileHandler.level = FINE
2localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.FileHandler.prefix = localhost.

3manager.org.apache.juli.FileHandler.level = FINE
3manager.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.FileHandler.prefix = manager.

4admin.org.apache.juli.FileHandler.level = FINE
4admin.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
4admin.org.apache.juli.FileHandler.prefix = admin.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
2localhost.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
3manager.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].handlers = \
4admin.org.apache.juli.FileHandler

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

For a specific web application logging.properties should be placed in WEB-INF/classes


handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = servlet-examples.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

This entry was originally published at Experts Support Blog

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