iwebie
HOME MOVIES TV SHOWS SPORTS GENERAL
 RSSPRIVACY
 

Archive for the ‘Programming’ Category

« Previous EntriesNext Entries »

Basic Shell Programs

Monday, July 7th, 2008

1) Shell Program To check the greater number between two numbers

[sourcecode language='sh']
echo Enter a Number
read num1
echo Enter Number
read num2
if test $num1 -ge $num2
then echo $num1 is greater than $num2
else
echo $num2 is greater than $num1
fi
[/sourcecode]

2) Shell Program to Check a number is even or odd

[sourcecode language='sh']
echo Enter a Number to Find Even or odd
read num
b=`expr $num % 2 |bc`
if [ $b -eq 0 ]
then
echo Even number
else
echo Odd Number
fi
[/sourcecode]

3) Shell Program to check whether a year is leap or Not

[sourcecode language='sh']
echo Enter the year to check for Leap
read year
leap=`expr $year % 4 | bc`
check1=`expr $year % 100 |bc`
if [ $check1 -eq 0 ]
then
check2=`expr $year % 400 | bc`
if [ $check2 -eq 0 ]
then
echo Leap
else
echo Not Leap
fi
break;
fi
if [ $leap -eq 0 -a $check1 -ne 0 ]
then
echo Leap
fi
[/sourcecode]

4) Shell Program to Find a File exists in the present working directory

[sourcecode language='sh']
echo Enter a File Name
read filename
if [ -s $filename ]
then
if [ -f $filename ]
then
echo File Exists…
else
echo Directory Exists…
fi
ls $filename -n
else
echo Not found
fi
[/sourcecode]

5) Shell Program To copy a file into another file

[sourcecode language='sh']
echo Enter Source File Name Destination File name
read srcfile destfile
cp $srcfile $destfile
echo Copy Complete…
echo $destfile “Is a Copy of ” $srcfile
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments »

Java Factorial Program

Sunday, July 6th, 2008

[sourcecode language='java']
public class Factorial {

public static long factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n – 1);
}

public static void main(String[] args) {
for (int i = 1; i <= 10; i++)
System.out.println(”Factorial of “+i+” : “+factorial(i));
}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming 1 Comment »

How to list System Properties in Java

Sunday, July 6th, 2008

[sourcecode language='java']
import java.util.Enumeration;
import java.util.Properties;

public class SystemProperties {
static Properties listProps = System.getProperties();

public static void main(String args[]){
Enumeration enums = listProps.elements();

while(enums.hasMoreElements()){
System.out.println(enums.nextElement());
}
// Getting the username system property
String username;
username = System.getProperty(”user.name”);
System.out.println();
System.out.println(”Username System Property is “+username);
}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments »

Java Data Type Conversions

Friday, July 4th, 2008

Below is a program to demonstrate simple Java Type conversions with examples. You will notice the following converstions;

  • Java String to Primitive Data Type
  • Java Primitive Data Type to String
  • Use of Wrapper classes to support the conversion

[sourcecode language='java']
public class JavaTypeConversions {

public static void main(String args[]) {

// ASCII code to String Conversion
int i = 74;
String iStr = new Character((char) i).toString();
System.out.println(”Ascii Code : ” + i + “\t”
+ “Converted to String : ” + iStr);

// decimal to binary Conversion
// Similarly you can convert it into a HexString using
// Integer.toHexString
int j = 74;
String bStr = Integer.toBinaryString(j);
System.out.println(”Decimal Value : ” + j + “\t” + “Binary String : ”
+ bStr);

// double to String Conversion
// Similarly you can convert from float to String using Float.toString
// Similarly you can convert from Integer to String using
// Integer.toString
double k = 74.50;
String dStr = Double.toString(k);
System.out.println(”Double Value : ” + k + “\t”
+ “Converted to String : ” + dStr);

// Char to Ascii Conversion
char l = ‘J’;
int m = (int) l;
System.out.println(”Char Code : ” + l + “\t” + “Converted to Ascii : ”
+ m);

// HexaDecimal to Integer
int n = Integer.valueOf(”A8DA3″, 16).intValue();
System.out.println(”Hexadecimal Code : A8DA3\t”
+ “Converted to Ascii : ” + n);

// String to double
// You can also do Double.parseDouble(”str”)
String oStr = “128″;

double p = Double.valueOf(oStr).doubleValue();
System.out.println(”String :” + oStr + “\t” + “Converted to double : ”
+ p);

// int to hexadecimal

int q = 17;
System.out.println(”int : “+q+”\t Converted to Hex is : ” + Integer.toHexString(i) );

}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments »

How to use ServletContextListener Interface?

Thursday, July 3rd, 2008

ServletContextListener

ServletContext : Each web application has a ServletContext associated with it. The ServletContext object is created when the application is started and is destroyed when the application is shut down. A ServletContext has a global scope and is similar to a global variable in an application.
 
ServletContextListener: Using this listener interface, programmers can add any object to the ServletContext before servicing any client request. The object gets initialised when the ServletContext gets started and is available as long as the ServletContext is running.

This interface has two methods with the following signatures
[sourcecode language='java']
void contextDestroyed (ServletContextEvent sce)
   Notifies that the servlet context is about to be shut down.

void contextInitialized (ServletContextEvent sce)
   Notifies that the Web Application is ready to process client requests.

[/sourcecode]

You need to create a java class that implements javax.servlet.ServletContextListener interface and provide the implementation for the above two methods.

For Example: The ServletContextListener interface is useful when you need to create a database connection before processing any client request and, when you want the connection to be available throughout the application.

[sourcecode language='java']
package com.database;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributesListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.database.DbConnection;

public class DatabaseContextListener implements ServletContextListener {

  private ServletContext context = null;
  private Connection conn = null;

  public DatabaseContextListener() {

}

  //This method is invoked when the ServletContext is started
//and is ready to process requests

  public void contextInitialized(ServletContextEvent event)
  {
    this.context = event.getServletContext();
    conn = DbConnection.getConnection; // Here DbConnection is an customised class which creates a database connection
    context = setAttribute(”dbConn”,conn);
  }

  //This method is invoked when ServletContext is going to be
//shut down so all the connections are closed

  public void contextDestroyed(ServletContextEvent event)
  {
    this.context = null;
    this.conn = null; 
  }
}
[/sourcecode]

Then deploy this class in the web archive(.war) file and make an entry in the deployment descriptor web.xml within the <listener> tags as given below:

[sourcecode language='xml']
           com.database.DatabaseContextListener
   
 
[/sourcecode]

Once your web application is started, you can retrieve the database object from the ServletContext in any servlet or jsp in this below manner.

[sourcecode language='java']
Connection conn = (Connection) getServletContext().getAttribute(”dbConn”);

[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming 10 Comments »

Compression and DeCompression in Java

Thursday, July 3rd, 2008

The below example will demonstrate the following concepts in java using java.util.zip API

  • How to compress a Java Byte Array
  • How to compress a Java String
  • How to decompress a Java Byte Array
  • How to decompress a Java String

[sourcecode language='java']
import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class CompressUncompressStrings {

public static void main(String[] args) {

String myString = “This is my String”;
String compressedMyString = compressString(myString);

System.out.println();
System.out.println(”——————————————————————-”);
System.out.println(”myByte has been compressed to compressedMyString whose value is : ”
+ compressedMyString);
System.out.println(”Now the String has been Compressed and placed in compressedMyString”);
System.out.println(”Lets Uncompress the Compressed String back to the Original myByte”);
System.out.println(”——————————————————————–”);
System.out.println();
String deCompressedMyString = deCompressString(compressedMyString);

System.out.println(”compressedMyString has been decompressed to : “+ deCompressedMyString);

}

private static String compressString(String myString) {
byte[] myByte = myString.getBytes();

System.out.println(”Original String is : ” + myString);

// Compression level of best compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);

// Give the Compressor the input data to compress

compressor.setInput(myByte);
compressor.finish();

// Create an expandable byte array to hold the compressed data.
// It is not necessary that the compressed data will be smaller than the
// uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(myByte.length);

// Compress the data
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}

try {
bos.close();
} catch (Exception e) {
e.printStackTrace();
}

// Get the compressed data
byte[] compressedMyByte = bos.toByteArray();
String compressedMyString = new String(compressedMyByte);

return compressedMyString;
}

private static String deCompressString(String compressedMyString) {

Inflater decompressor = new Inflater();
byte[] buf = new byte[1024];
byte[] compressedMyByte = compressedMyString.getBytes();
decompressor.setInput(compressedMyByte);

// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(
compressedMyByte.length);

// Decompress the data
buf = new byte[1024];
while (!decompressor.finished()) {
try {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
} catch (DataFormatException e) {
}
}
try {
bos.close();
} catch (Exception e) {
e.printStackTrace();
}

// Get the decompressed data
byte[] decompressedMyByte = bos.toByteArray();

String decompressedMyString = new String(decompressedMyByte);

return decompressedMyString;

}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming 2 Comments »

How to Centre a JFrame

Sunday, June 29th, 2008

[sourcecode language='java']
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

// Displaying a JFrame at the center of the screen using Java Toolkit Class
public class CenterFrameDemo extends JFrame {

CenterFrameDemo() {
setTitle(”Center a Frame on Screen”); // jframe title
setSize(400, 300); // jframe size
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {

// java jframe close
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(null, “Are you sure ?”) == JOptionPane.YES_OPTION) {
setVisible(false);
dispose(); // jframe exit
} else {

}
}
});
}

public static void main(String[] args) {
CenterFrameDemo cfd = new CenterFrameDemo();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
cfd.setLocation((int) (d.getWidth() – cfd.getWidth()) / 2, (int) (d
.getHeight() – cfd.getHeight()) / 2);
cfd.setVisible(true);
}

}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments »

Java Swing JList List Model Example

Sunday, June 29th, 2008

[sourcecode language='java']
import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListDemo extends JFrame {

private JList list; // java JList

private String[] listColorNames = { “Red”, “blue”, “green”, “yellow”,
“white” };

private Color[] listColorValues = { Color.RED, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.WHITE };

private DefaultListModel colorModel;

public JListDemo() {
super(” JList List Models Demo “);
colorModel = new DefaultListModel(); // jlist listmodel
getContentPane().setLayout(new FlowLayout());
for (String cN : listColorNames) {
colorModel.addElement(cN);
}
list = new JList(colorModel);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisibleRowCount(3);
getContentPane().add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {

public void valueChanged(ListSelectionEvent e) {
getContentPane().setBackground(
listColorValues[list.getSelectedIndex()]);
}
});
setSize(200, 200);
setVisible(true);
}

public static void main(String[] args) {
JListDemo test = new JListDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments »

SQL Tuning

Wednesday, June 25th, 2008

Tuning in SQl

Oracle’s SQL is a very flexible language. We can make use of many different SQL statements to accomplish the same task. Even though there are several queries and retrieval statements producing similar results, one should make use of the most efficient choice . A SQL choice is optimized only if it produces the accurate results in a short span of time, without overriding the performance of other system resources. Whenever an SQL statement is executed, Oracle first looks for identical statements matching in the context (SGA) area as it holds the SQL statements in memory after parsing. Thus use of Bind variables is advisable when ever possible in place of Literals.

SQL tuning can be done by:

Making use of ROWID where ever possible
Reason:
Every record that is added to the database will have an unique ROWID and will not change until the delete statement is issued on that record. In case a record block or location has been changed for some reason, the original ROWID would still point to the new location or the new ROWID and so on. Thus as far as possible use ROWID to optimize the code for retrievals of a record.

Avoid making use of UNION and instead use UNION ALL
Reason:

UNION ALL includes duplicate rows and does not require a sort. Whereas the UNION operation sorts the result set to eliminate any rows,which are within the sub-queries. As the SORT operation is very expensive in terms of CPU consumption try as far as possible avoiding its use. Unless you require the duplicate rows to be eliminated,use UNION ALL.

Avoid making use of NOT IN and instead use NOT EXISTS for indexed columns
eg.
Normal Query -
[sourcecode language='sql']
select * from emp
where emp_id NOT IN
(select gid from company)
[/sourcecode]

Optimized Query -
[sourcecode language='sql']
select * from emp e
where NOT EXISTS
(select * from company c
where c.gid = e.emp_id)
[/sourcecode]

Avoid using NOT IN and instead use IN with MINUS incase of non indexed columns
eg.
Normal Query -
[sourcecode language='sql']
select * from emp
where emp_id NOT IN
(select gid from company)
[/sourcecode]

Optimized Query -
[sourcecode language='sql']
select * from emp
where emp_id IN
(select emp_id from emp
MINUS select gid from company)
[/sourcecode]

Avoid using EXISTS and instead use Joins for Unique Scan Indexes and tables with less number of records
eg.
Normal Query -
[sourcecode language='sql']
select emp_name,emp_id
from emp
where EXISTS (select * from company where gid = id)
[/sourcecode]

Optimized Query -
[sourcecode language='sql']
select name,id
from emp E,company C
where E.id = C.gid
[/sourcecode]

Avoid using of HAVING clause, instead make use of WHERE clause
Reason:
HAVING clause fetches all the rows and only then filters the selected rows, this would eat up lots of system resources and time. Thus as far as possible do not make use of HAVING clause in select query.
eg.
[sourcecode language='sql']
select *
from emp
where emp_name = ‘Bond’
having emp_id = ‘007’
[/sourcecode]
Instead use -
[sourcecode language='sql']
select *
from emp
where emp_name = ‘Bond’
and emp_id = ‘007’
[/sourcecode]

Avoid using DISTINCT and use EXISTS instead
eg.
Normal Query -
[sourcecode language='sql']
select DISTINCT emp_id, emp_name
from company C, emp E
where C.gid = E.emp_id
[/sourcecode]

Optimized Query -
[sourcecode language='sql']
select emp_id, emp_name
from emp E
where EXISTS (select ‘X’
from company C
where C.gid = e.emp_id );
[/sourcecode]

EXISTS processes faster as the query will be terminated once the sub-query has been satisfied .

Make use of DECODE to Reduce Processing
The DECODE statement avoids repetitive scanning of the same rows and the joins to the same table.
eg:
[sourcecode language='sql']
select SUM(SAL)
from emp
where dept_num = 007
AND emp_name LIKE ‘BOND%’;
[/sourcecode]

The same query can be optimized as
[sourcecode language='sql']
select
SUM(DECODE(dept_num,007, SAL, NULL)) D007_SAL,
from emp
where emp_name LIKE ‘BOND%’;
[/sourcecode]

DECODE can also be made used in place of GROUP BY or ORDER BY clause.

Some fast tips -

Avoid using of OR and instead make use of UNION -
Consider the use of UNION instead of OR in the WHERE clauses. Using OR on an indexed column causes the optimizer to perform a full-table scan rather than an indexed retrieval.

Avoid using of NOT when ever dealing with Indexed Columns
Reason:
Whenever NOT is made use of, a full-table scan is performed and it wont be using the index.
Indexes are built on the records which exists in a table, and not on which does not exist in a table.

The following statement will never use the index on emp_id column
[sourcecode language='sql']
select * from
emp
where emp_id not like ‘9%’
[/sourcecode]

Avoid usage of ‘!‘ operator use ‘>‘ instead
eg.
[sourcecode language='sql']
select *
from emp
where emp_id != 007
[/sourcecode]

Optimize by using :
[sourcecode language='sql']
select *
from emp
where emp_id > 0
[/sourcecode]

Avoid usage of ‘||‘ operator use ‘AND‘ instead
eg.
[sourcecode language='sql']
select *
from emp
where emp_name || emp_id = ‘BOND007’
[/sourcecode]

Optimize by using :
[sourcecode language='sql']
select *
from emp
where emp_firstname = ‘BOND’
AND emp_id = ‘007’
[/sourcecode]

Avoid usage of ‘TO_CHAR‘ and use ‘TRUNC‘ instead
eg.
[sourcecode language='sql']
select *
from emp
where to_char(emp_joindate,’mmddyyyy’) < to_char(sysdate,’mmddyyyy’)
[/sourcecode]

Optimize by using :
[sourcecode language='sql']
select *
from emp
where emp_joindate < trunc(sysdate)
[/sourcecode]

Avoid usage of ‘*’ instead make use of primary key or non null index column
eg.
[sourcecode language='sql']
select count(*) From emp
[/sourcecode]

Optimize by using :
[sourcecode language='sql']
select count (primary_key or non null INDEX column ) from emp
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming 1 Comment »

I18N Internationalization

Monday, June 23rd, 2008

I18N – Internationalization

Internationalization is a process of designing a software application so that it can support various languages. All the text messages to be displayed in the application is to be listed in a centralized file and can be accessed depending upon the user preferences later in the JSP file or Java class. The advantage is that the specified labels or descriptions can be reused in multiple JSP files and to provide multiple language support for the application.

Locale is a representation of a language and country combination,eg. en_US,es_SP. The language codes are specified in lowercase and the country codes are specified using uppercase characters, as defined by International Organization for Standardization – the ISO. The country code is optional, so ‘en’ alone can be a valid locale string for the English language.

Common centralized file also known as resource bundles are simply property files with message key and corresponding value pairs,this is to be prepared for every language using the filename convention as MessageResource_en_US (filename_languagecode_country) if country code is used else can be named as MessageResource_en (filename_languagecode) with the file extension “properties”. The messages are placed in the file using the convention as message key followed by the actual text message to be displayed. i.e.greeting=Hello(hi)where the string greeting would be the message key which will be placed in either the JSP or Java class and the word “Hello(hi)” would be displayed on the User Interface. The message key would be the same for all the locales.

Sample Java Class Code

[sourcecode language='java']
import java.util.Locale;
import java.util.ResourceBundle;

public class I18N {

static public void main(String[] args) {

String language;
Locale prefferedLocale;
ResourceBundle messages;

if (args.length != 1) {
language = new String(”en”);
} else {
language = new String(args[0]);
}

prefferedLocale = new Locale(language);
messages = ResourceBundle.getBundle(”MessageResource”, prefferedLocale);
System.out.println(messages.getString(”greeting”));
}
}
[/sourcecode]

Then Create a property file as

MessageResource_en.properties
greeting=hello (hi)

MessageResource_es.properties
greeting=hola! saludo

Compile the java code and provide the argument with the language code to get appropriate language display.

javac I18N.java
java I18N en //To get output in English
or
javac I18N.java
java I18N es //To get the Output in Spanish

Implementation of I18N for a Web based Application would be published shortly.

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller
Posted in Programming No Comments » « Previous EntriesNext Entries »
Most Popular

Watch over 100,000 movies and TV shows on your PC
Recent Posts

  • Watch Crazy on the Outside Online Free
  • Watch It’s Complicated Full Video Online
  • Watch Leap Year Free Stream Online
  • Watch Manchester United vs Birmingham Live Stream
  • Watch Avatar Online Stream
  • Watch Nine Online Video
  • Watch Crazy Heart Full Stream
  • Modern Family Season 1 Episode 11 | Watch Modern Family s01e11 Up All Night Full Episode
  • Burnley vs Arsenal EPL | Watch Burnley vs Arsenal Live Stream
  • Watch The Princess and the Frog Online Free

Warning: include(adbottom.html) [function.include]: failed to open stream: No such file or directory in /var/www/vhosts/iwebie.com/httpdocs/wp-content/themes/iWebie/rightsidebar.php on line 20

Warning: include() [function.include]: Failed opening 'adbottom.html' for inclusion (include_path='.:/opt/lsws/lsphp5/lib/php') in /var/www/vhosts/iwebie.com/httpdocs/wp-content/themes/iWebie/rightsidebar.php on line 20
Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
Powered by WordPress