Wednesday, August 18, 2010
Redirect standard error from console to a file
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
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
{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
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
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."
+ "
customLabel.label.setText(text);
}
}
This entry was originally published at Experts Support Blog
Monday, August 2, 2010
Manage logging in tomcat server
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