Monthly Archives: May 2006

Moving the Cursor in a Scrollable Result Set

This example demonstrates the various methods for moving the cursor in a scrollable result set.

[java]
try {
// Create a scrollable result set
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = stmt.executeQuery(“SELECT * FROM my_table”);

// Move cursor forward
while (resultSet.next()) {
// Get data at cursor
String s = resultSet.getString(1);
}

// Move cursor backward
while (resultSet.previous()) {
// Get data at cursor
String s = resultSet.getString(1);
}

// Move cursor to the first row
resultSet.first();

// Move cursor to the last row
resultSet.last();

// Move cursor to the end, after the last row
resultSet.afterLast();

// Move cursor to the beginning, before the first row.
// cursor position is 0.
resultSet.beforeFirst();

// Move cursor to the second row
resultSet.absolute(2);

// Move cursor to the last row
resultSet.absolute(-1);

// Move cursor to the second last row
resultSet.absolute(-2);

// Move cursor down 5 rows from the current row. If this moves
// cursor beyond the last row, cursor is put after the last row
resultSet.relative(5);

// Move cursor up 3 rows from the current row. If this moves
// cursor beyond the first row, cursor is put before the first row
resultSet.relative(-3);
} catch (SQLException e) {
}
[/java]

Overcoming RowFilter and Select Limitation

In ADO.NET, you can use the DataView.RowFilter property and the DataTable.Select method to filter a subset of records. However, the expressions that you can use have limitations. This article demonstrates three techniques to work around the limitations of the filter expressions.

[vbnet]
‘DataTable1 is an existing DataTable object.
DataTable1.Columns.Add(“Flag”, GetType(Boolean))
DataTable1.Columns(“Flag”).ColumnMapping = MappingType.Hidden
Dim dr As DataRow
For Each dr In DataTable1.Rows
‘ If the criteria are satisfied Then
dr(“Flag”) = True
‘ End If
Next
Dim dv As New DataView(DataTable1, “Flag = True”, “”, DataViewRowState.CurrentRows)
DataGrid1.DataSource = dv
[/vbnet]

Maybe a help..

I’m trying to use sqlite in my java progs..might be a help…
posted in java forum

HI. The problem is the package in the site. When you use the fck.mthr class SQLite.JDBCDriver, from this package, it does not point to the classes in the JDBC2x, but to a crazy “JDBC2y”.

Try the package that I foud out at :

http://dev.radrails.org/trac/browser/trunk/org.sqlite.driver/SQLite?rev=373.

It worked with at the first time.

You will have to organize the files, close to the package from http://www.ch-werner.de/javasqlite/overview-summary.html

OBS : I also got it with the package from “http://www.ch-werner.de/javasqlite/overview-summary.html” , but with a diferent code that I don´t think that is secure. I jumped the class JDBCDriver, and I use the classes in JDBC2x :

[java]
import java.sql.*;
import SQLite.JDBC2x.*;

public class SQLiteJDBC
{
public static void main( String args[] ) throws SQLException
{
String url2 = “jdbc:sqlite:/C:\teste.db”;
try {

JDBCConnection c = new JDBCConnection (url2,””);

JDBCStatement st =(JDBCStatement) c.createStatement();

String campo;
int i = 0;
ResultSet rs = st.executeQuery( “SELECT * FROM teste;” );
while ( rs.next() ) {
campo = rs.getString(“teste”);
System.out.println( “Linha ” + i + ” -> campo “teste” = ” + campo );
i++;
}
rs.close();
st.close();

c.commit();
c.close();
} catch ( SQLException e ) {
System.err.println( e.getClass().getName() + “: ” + e.getMessage() );
System.exit(1);
}
}
}

//————————————————————————-
[/java]
*********************ATENTION***************************

Please, if you tested it and it worked to you, please, repass to the other forums. It was dificult to find this answer on web.

See you……….

How to Print in JetBee

How to print a report.

There are several approaches to code a report printing applications using the JetBee print library. It will depend on whether you want to use the Java print model, or an alternative print model provided by the JetBee print library. And it also depends on if you want to print under the foreground or a background thread.

If you have existing Java programs and want them to utilize the library, then a quick and easy way is to use the Java print mode. See How to print using the Java print model.

If you want to use the JetBee print model, please see How to print using the JetBee print model.

How to print using the Java print model.

The JetWriter class can also work with the Java Printable class easily. If you have existing programs that are using the Java Printable class, or if you want to continue to use the Java Printable class while taking advantages of the JetBee print library, you can do this:

class MyReport implements Printable {

}
JetWriter jw = new JetWriter();
boolean go = jw.jetPrintDialog();
if (go) {
jw.jetExePrintable(new MyReport()); // execute in foreground thread.
}

If you want to use a background thread to print the report, you need simply to use the jetRunPrintable() instead:


if (go) {
jw.jetRunPrintable(new MyReport()); // execute in a background thread.
}

How to print using the JetBee print model.
This can be easily achieved by using a JetWriter object:

JetWriter jw = new JetWriter();

Once you have a JetWriter object, you can print using the member functions of the writer. Or you may obtain a Graphics2D object with which all the powerful Graphics2D functions can be used to print the report. For example:

// optionally set the print job attributes here.
jw.jetOpenReport();
Graphics2D g = jw.jetGetGraphics2D();
g.drawString(“JetBee Sample 1 Report”, 220, 150);
g.drawLine(220, 152, 355, 152);

This method is a convenient way to code for reports that are relatively simplier and can be finished quickly. There is no need to code for other class or routines. However, program coded in this way will run in the foreground thread.

If it is needed to print a report in a background thread, or using the features provided by the JetReport or its derived classes, then you may consider to create a class to contain the codes that print the report.

Your class would be derived from the JetReport or one of its derived classes such as the JetGraphics2DReport class.

For example:

class ProductList extends JetGraphics2DReport {
public void jetPrint() throws JetException {
// codes for generating the report contents.
// …
}
}

Then, in your main program, create a JetWriter instance and pass an instance of your report class to the JetWriter with the function jetRunReport():

JetWriter jw = new JetWriter();
// optionally set the print job attributes here.
jw.jetRunReport(new ProductList());

Then, the writer will call the codes in your report class in a background thread to generate the report.
How to preview a report.
The preview service can be easily employed simply by activating it using a function:

JetWriter jw = new JetWriter();

jw.jetSetAutoPreview(true); // activate the preview service.

Alternatively, some constructors also allow the preview service to be set:

JetWriter jw = new JetWriter(true, false); // preview is activated; printer output is disabled.

Once activated, the library will automatically bring up a preview window when a few pages of the report are generated and ready to be shown. It does not need to wait for the entire report to be finished. This would be useful for reports that contain thousands of pages.
How to print AWT or Swing components.
The jetPrintComponent() family of functions can be used to print any AWT/Swing components. These functions allow the position and size of a component to be set. There are also specific functions to print JTable objects. For example:

JetWriter jw = new JetWriter();
jw.jetOpenReport();
JLabel mylabel = new JLable(“Description”);
jetPrintComponent(mylabel, 50, 100);
JTable mytable = new JTable(…);
jetPrintComponent(mytable, 100, 200, “80%”, “80%”);

Marlons Report in Java

Snippet daw ni strong

String headers = “Medina General Hospital”;
String oz = “Ozamiz City”;
String stdate = “Date”;

JetWriter jw = new JetWriter(true, false);
jw.jetOpenReport();

Graphics2D g = jw.jetGetGraphics2D();

// g.drawString(headers, 220, 151);
g.drawString(headers, 221, 150);
g.drawLine(221, 152, 358, 152);
g.drawString(oz, 250, 170);
g.drawString(tDate.toString(), 350, 200);
g.drawLine(340,201, 450, 201);
g.drawString(stdate,380,213);
g.draw3DRect(130,130, 335, 335, false);
g.drawString(dcCharge, 221,225);
g.drawString(csnum.toString(),150, 250);
g.drawString(cs.toString(), 340,250);
g.drawString(csT.toString(), 340, 280);

jw.jetCloseReport();

Encyrption in Java

e464. Encrypting with DES Using a Pass Phrase
This example demonstrates how to use a pass phrase (a string password of multiple words) for encryption.

public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;

// 8-byte Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};

// Iteration count
int iterationCount = 19;

DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
“PBEWithMD5AndDES”).generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());

// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}

public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes(“UTF8”);

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}

public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, “UTF8”);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}

// Here is an example that uses the class
try {
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(“My Pass Phrase!”);

// Encrypt
String encrypted = encrypter.encrypt(“Don’t tell anybody!”);

// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

e462. Encrypting a String with DES

This example implements a class for encrypting and decrypting strings using DES. The class is created with a key and can be used repeatedly to encrypt and decrypt strings using that key.

public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;

DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance(“DES”);
dcipher = Cipher.getInstance(“DES”);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);

} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}

public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes(“UTF8”);

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}

public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, “UTF8”);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}

Here’s an example that uses the class:

try {
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance(“DES”).generateKey();

// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);

// Encrypt
String encrypted = encrypter.encrypt(“Don’t tell anybody!”);

// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

Java Snippets

e35. Reading Text from a File

try {
BufferedReader in = new BufferedReader(new FileReader(“infilename”));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}

e37. Writing to a File
If the file does not already exist, it is automatically created.

try {
BufferedWriter out = new BufferedWriter(new FileWriter(“outfilename”));
out.write(“aString”);
out.close();
} catch (IOException e) {
}

e20. Creating a File

try {
File file = new File(“filename”);

// Create file if it does not exist
boolean success = file.createNewFile();
if (success) {
// File did not exist and was created
} else {
// File already exists
}
} catch (IOException e) {
}

e19. Determining If a File or Directory Exists

boolean exists = (new File(“filename”)).exists();
if (exists) {
// File or directory exists
} else {
// File or directory does not exist
}

File shortcuts in Linux

File shortcuts in Linux

In Windows and MacOS, you can create handy desktop shortcuts to access files and directories whose paths you never are able to memorize. In MacOS, such a shortcut is called alias. In Linux, shortcuts are called symbolic links (symlinks); they are created using the terminal command ln. Some use cases:

Simplest case: You want to create a symlink to /long/path/to/dir/myfile in the current directory and give the shortcut the same name as the original (myfile), then you type
ln -s /long/path/to/dir/myfile
To create a shortcut to /long/path/to/dir/myfile in the current directory, but set the shortcut’s name to myShortcut
ln -s /long/path/to/dir/myfile myShortcut
All together now: To create a shortcut to /long/path/to/dir/myfile in the directory /path, and set the shortcut’s name to myShortcut
ln -s /long/path/to/dir/myfile /path/myShortcut

For directories, it works the same way.
Useful tips for using the Terminal command ln:

* What’s the difference between a symlink and a hard link? When specifying the ln -s option, you get a symbolic link, without it, you get a hard link to the file or directory. If you want a Windows-style shortcut it’s a symlink, so you must use the -s option. Symlinks are clearly marked and can be deleted without the original being touched. But beware, if someone deletes The One Original(tm), all of the symlinks will irrecoverably break!
Hard links on the other hand, never break, as long as one of the instances still exists — no matter which. In other words, hard links allow you to have one (original) file in many places under different names. Note, that you will not be able to tell a hard link from its original! They are the same. You edit one, you edit all. You need to keep track of hard links yourself.
You see, the reason why beginners use symlinks is, symlinks are clearly marked and less confusing. 😉
* How to remove a hard link? Use the unlink command on the one of the hard links that you do no want to keep. Be careful when unlinking the last instance of the file, or when unlinking a normal file: Unlinking will quietly remove these files without any warning! (Actually, they are still on you harddrive, but you won’t be able to find them anymore…)
* How to remove a symlink? Symbolic links can be savely deleted with the rm command. If you should get the error message “rm cannot remove directory”, do not out of a habit use rm -rf mySymlink/* on a symlink to a directory, because that will delete the original’s content! Instead make sure not to end the symbolic link’s name in a slash when removing it. (You may get a slash in the end if you let the shell complete a link to a directory by pressing the tab key).
* Many people have trouble remembering the order of the arguments to ln. 🙂 It’s actually the same order that cp and mv use: First the source, that’s the existing file or directory where you want the link to point to, then the target, that’s the shortcut’s name. If you mix up source and target, you create a useless link pointing nowhere inside the target directory (or you get an error message). Confused? Just keep one thing in mind: The first argument must be the source — because specifying the file or directory to link to is obviously mandatory. The target, however, is second, because it’s optional — if you don’t supply it, ln can just use the original file’s name and place the shortcut in the current working directory by default.
* How to tell what’s a file and what’s a link? The Linux shell usually marks symlinks, either by a color or by adding a character like @ to the file name. (You never type the @ when working with the symlink, though!) If you are not sure, you can get more information about your files by listing them with ls -l. This will clearly mark symlinks with a small letter L at the beginning of the line and a little arrow after the name plus the path where they point to.
There is no way to tell a hard link from a ‘normal’ file! Like I said, they are the same thing, one file appears in two different places at the same time.

Here is an example of what symbolic and hard links look like in the wild. Note the L and the arrows identifying myfile and myShortcut as symlinks. Symlinks are usualy suspiciously small (compared to what you’d expect from a real file) and their change/creation dates are the dates of the symlink’s change/creation, not the original’s!
The files split_personality_one.txt and split_personality_too.txt don’t look any different than just_some_normal_file.txt, but they are actually hard links! Psst, tell you a secret: All hard links of a flock have the same size and date… (that’s the only hint you’ll get from the shell about their identity.)

[jane:~]> ls -l

lrwxrwxrwx 1 jane users 65 Aug 15 15:19 myfile -> /long/path/to/dir/containing/the/original/myfile

lrwxrwxrwx 1 jane users 65 Aug 19 11:59 myShortcut -> /long/path/to/dir/containing/the/other/myfile

-rw-r–r– 1 jane users 3471 Sep 1 11:22 just_some_normal_file.txt

-rw-r–r– 2 jane users 763 Aug 24 17:14 split_personality_one.txt

-rw-r–r– 2 jane users 763 Aug 24 17:14 split_personality_too.txt

Interesting Post on Java

Hi,
JComboBox has any property like ItemData Available in VB ?
I want to store Integer value corresponding to each Item in the JComboBox.
Give me your valuable suggestions or solutions.

Thanks,
SENTHILKUMAR R

People often make the mistake of filling their models with strings…
Since a ComboBoxModel can contain any class you’d simply fill your model with a class that contains your object and integer. For simplicity you’d make its toString method return the same value as your object’s toString method. You’d then expose your integer with something like “getNumber”.
Personally I’d put a meaningful entity into the combo box model and change the renderer to figure out a string for that item.
Hope this helps.

KPSeal