Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, April 30, 2010

Value restricions

Some primitive value besides a conrete data-type may have a predefined set of values. And the value can be set only to one of that variants, like enumerations. XML schema allows us to restrict the value of a given type by a set of enumerated values. From the other hand we can restrict some value by defining its min/max bounds:

http://www.w3.org/2001/XMLSchema">

…









…








…

…

…



source: java-tips.org

Monday, April 26, 2010

Tired of including configuration files in your scripts

I am often tired of including configuration files in my scripts. Even if it is a single file it becomes important to include that file in our scripts otherwise we wont get the necessary variables set. Once when I started searching for a workaround for it, I found that we can configure it right in one place and say PHP take care of this headache.
Yes, We can do it.

1.Place all your configuration files in one folder in the server. Say "DOCUMENT_ROOT/config/lib"
2. Create a new file with a name preinclude.php
3. Declare or include (again include ) all your common variables, config files in this file.
4.In the DOCUMENT_ROOT folder create a .htaccess file
5. Write the following code in this:

# Code starts here
php_value auto_prepend_file "path to include directory/preinclude.php"
# Code ends here

We can include whichever file which we feel should be executed before each and every file execution here.

Tuesday, April 20, 2010

Show data with JTable

This Java Swing tip illustrates a method of showing data in database in a JTable. JTable act as a output for the database. The developer may use this to display a part of data (for example data generated form a query) to the user in a table. The table gives user an impression of database.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class DatabaseTest extends JFrame {
JTextField hostField;
JTextField queryField;
QueryTableModel qtm;

public DatabaseTest() {
super("Database Test Frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(350, 200);
qtm = new QueryTableModel();
JTable table = new JTable(qtm);
JScrollPane scrollpane = new JScrollPane(table);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
p1.add(new JLabel("Enter the Host URL: "));
p1.add(hostField = new JTextField());
p1.add(new JLabel("Enter your query: "));
p1.add(queryField = new JTextField());
p1.add(new JLabel("Click here to send: "));
JButton jb = new JButton("Search");

jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
qtm.setHostURL(hostField.getText().trim());
qtm.setQuery(queryField.getText().trim());
}
} );

p1.add(jb);
getContentPane().add(p1, BorderLayout.NORTH);
getContentPane().add(scrollpane, BorderLayout.CENTER);
}
public static void main(String args[]) {
DatabaseTest tt = new DatabaseTest();
tt.setVisible(true);
}
}

Source: java-tips.org

Sunday, April 18, 2010

Creating a Confirm Dialog Box

The easiest way to create a Yes/No/Cancel dialog box is to use showConfirmDialog(Component, Object) method of JOptionPane class.
The following example uses a confirm dialog box with a text message and stores response in the response variable:
int response;
response = JOptionPane.showConfirmDialog(null, "Should i delete all files?");


source: java-tips.org

Sunday, April 04, 2010

Input Dialog Box

An input dialog box asks a question and uses a text field to store the response.
The easiest way to create an input dialog in Java is to use showInputDialog(Component, Object, String, int) method of JOptionPane class.

The following example uses this method to create an input dialog box:

String response = JOptionPane.showInputDialog(null, "What is your name?", "Enter your name", JOptionPane.QUESTION_MESSAGE);

Source: java-tips.org

Friday, April 02, 2010

Message Dialog Box

A message dialog box is a simple window that displays information. A message dialog box can be created with a call to the showMessageDialog(Component, Object) method of JOptionPane class.

The following statement creates a message box:
JOptionPane.showMessageDialog(null, "I am happy.");

Source: java-tips.org

Tuesday, March 09, 2010

Cross-site scripting (XSS)

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

The injected script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.

source : msdn

Sunday, March 07, 2010

Java program for image decompression

This is a java program to decompress the given image.we have first initialized the given file using file input stream reader and read character by character from input file and copied into the target file and displayed the size of the image.The program is as follows.

import java.io.*;
import java.util.zip.*;
class Izip{public static void main(String args[])throws Exception
{
InflaterInputStream in=new InflaterInputStream(new FileInputStream("Ashes.zip"));
FileOutputStream sout=new FileOutputStream("Ashes.bmp");
int b;
while((b=in.read())!=-1)
sout.write(b);
in.close();
sout.close();
File f1=new File("Ashes.zip");
File f2=new File("Ashes.bmp");
System.out.println("The size of zipped file is "+f1.length());
System.out.println("The size of unzipped file is "+f2.length());
}
}

OUTPUT:
C:\jdk1.3\bin>javac Izip.java
C:\jdk1.3\bin>java IzipThe size of zipped file is 1372The size of unzipped file is 589878

Saturday, February 20, 2010

Getting Cookie ID

This code gets the cookie id of current page without using WebUtil in QTP.

theCookie= Browser("micClass:=Browser").Page("micClass:=Page").Object.Cookie
pos=InStr(1,theCookie,"/",1)
cookieID= mid(theCookie, pos + 1, 16)

Thursday, February 18, 2010

Getting Active Object deatils

Browser("").page("").Object.activeElement.Name
Browser("").page("").Object.activeElement.Value
Browser("").page("").Object.activeElement.ID

Tuesday, February 09, 2010

Retrieving the contents of a ZIP file

This Java tip illustrates a method of listing the contents of a ZIP file. Developer may use this as a functionality for its users to first see the contents of the ZIP file and then decompress the chosen one.
try {
ZipFile sourcefile = new ZipFile("source.zip");
for (Enumeration entries = sourcefile.entries(); entries.hasMoreElements();) {
String zipEntryName = ((ZipEntry)entries.nextElement()).getName();
}
} catch (IOException e) {
}

Source: java-tips.org

Friday, February 05, 2010

How do you make a link open in a new window or tab?

This tip that helps us to make links open up in new tabs or windows. When you create the hyperlink, add target="_blank" just after you mention the url and before you close the tag.

For example, you want to hyperlink Click here to navigate to Google Maps and you want that to open up in a new window, then this is how you do it --
you say: Click Here

Saturday, January 02, 2010

Reading a zip file

This sample code read the name of all files from a zip file. It uses ZipInputStream to read zip file.


import java.io.*;
import java.util.zip.*;

public class ZipFileRdrExp {

public static void main(String[] args) {

try {

FileInputStream fis = new FileInputStream("C:\\MyZip.zip");
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze;
while((ze=zis.getNextEntry())!=null){
System.out.println(ze.getName());
zis.closeEntry();
}

zis.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


Source: java-tips.org

Thursday, December 31, 2009

Writing a Zip file

This sample code shows the method to create a Zip file and add files to it. It uses ZipOutputStream to write zip file.


import java.io.*;
import java.util.zip.*;

public class ZipFileWrtExp {

public static void main(String[] args) {

try {
FileOutputStream fos = new FileOutputStream("C:\\MyZip.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry("C:\\file1.txt");
zos.putNextEntry(ze);
zos.closeEntry();

ze= new ZipEntry("C:\\file2.txt");
zos.putNextEntry(ze);
zos.closeEntry();
zos.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

Source: java-tips.org

Sunday, December 27, 2009

Listing the image formats that can be read and written

This Java tip illustrates a method of listing the image formats that can be read and written. The complete list of available readable and writeable formats can be retrieved by calling ImageIO.getReaderFormatNames() and ImageIO.getWriterFormatNames(). By default, the javax.imageio package can read GIF, PNG, and JPEG images and can write PNG and JPEG images.


// Get list of unique supported read formats
String[] formatNames = ImageIO.getReaderFormatNames();
formatNames = unique(formatNames);
// e.g. png jpeg gif jpg

// Get list of unique supported write formats
formatNames = ImageIO.getWriterFormatNames();
formatNames = unique(formatNames);
// e.g. png jpeg jpg

// Get list of unique MIME types that can be read
formatNames = ImageIO.getReaderMIMETypes();
formatNames = unique(formatNames);
// e.g image/jpeg image/png image/x-png image/gif

// Get list of unique MIME types that can be written
formatNames = ImageIO.getWriterMIMETypes();
formatNames = unique(formatNames);
// e.g. image/jpeg image/png image/x-png

// Converts all strings in 'strings' to lowercase
// and returns an array containing the unique values.
// All returned values are lowercase.
public static String[] unique(String[] strings) {
Set set = new HashSet();
for (int i=0; i String name = strings[i].toLowerCase();
set.add(name);
}
return (String[])set.toArray(new String[0]);
}

source:java-tips.org

Friday, November 06, 2009

Finding and displaying hyperlinks in a web page

The Java application written below uses regular expressions to find and display hyperlinks contained within a Web page. After compiling the file, you should save a Web page to the same folder that contains ShowLinks.class.

import java.io.*;
import java.util.regex.*;
public class ShowLinks {
public static void main(String[] arguments) {
if (arguments.length < 1) {
System.out.println("Usage: java ShowLinks [page]");
System.exit(0);
}
String page = loadPage(arguments[0]);
Pattern pattern = Pattern.compile(" Matcher matcher = pattern.matcher(page);
while (matcher.find()) {
System.out.println( matcher.group(1));
}
}

private static String loadPage(String name) {
StringBuffer output = new StringBuffer();
try {
FileReader file = new FileReader(name);
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else
output.append(line + "\n");
}
buff.close();
} catch (IOException e) {
System.out.println("Error – " + e.toString());
}
return output.toString();
}
}

java-tips.org

Wednesday, November 04, 2009

Compressing a Byte Array

This Java tip illustrates an example of compressing a Byte Array. Developer may compress a byte array with the help of Deflater class.
byte[] input = "compression string".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try {
bos.close();
} catch (IOException e) {
}
byte[] compressedData = bos.toByteArray();

java-tips.org

Thursday, October 29, 2009

Applying Regular Expressions on the contents of a file

This Java tip illustrates a method of applying Regular Expressions on the contents of a file. The matching routines in java.util.regex require that the input be a CharSequence object. This tip implements a method that efficiently returns the contents of a file in a CharSequence object.

public CharSequence fromFile(String filename) throws IOException {
FileInputStream input = new FileInputStream(filename);
FileChannel channel = input.getChannel();
ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int)channel.size());
CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
return cbuf;
}

Here is sample code that uses the above method:
try {
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher(fromFile("infile.txt"));
while (matcher.find()) {
String match = matcher.group();
}
} catch (IOException e) {
}
java-tips.org

Saturday, October 17, 2009

Shell script - Compare two files

#!/bin/bash
clear
ARGV=3
if [ $# -eq 3 ];
then
echo "The following lines are Missing in the Destination File $2" >$3
echo -e "#######################################################################################"echo -e "#\t Please wait…."
while read LINE
do
grep -F "$LINE" $2>/dev/null
if [ $? -eq 0 ];
then
echo "">/dev/null
else
echo "$LINE" >>$3
fi
done <$1
else
echo "Syntax Usage: ./filecompare.sh source destination output"
fi
echo -e "#\t Script Done"
echo -e "#\t `cat $3wc -l` lines are missing in the file $2. Output file is $3"
echo -e "#######################################################################################"

Monday, September 21, 2009

Pseudo conversational transaction in CICS

Pseudo conversational transaction:
There are some advantages in CICS online system.

Multitasking: CICS allows multiple transactions (tasks) to execute at the same time
Multithreading: CICS allows multiple concurrent tasks to share the same program
Re-entrance: Programs running under CICS do not change themselves so that they can continue from where they left off after an interruption.

CICS –> Transaction to trigger application and It is also batch job to the mainframe.
Transaction –> 4 Character unique identification and all these transaction is controlled by control tables.
Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory