Google

Wednesday, December 9, 2009

Netbeans: Enabling Assertions



Make the changes in red as above.

Saturday, October 24, 2009

How to compile standalone exe from Matlab

http://www.onecore.net/howtocreate-standalone-executable-for-matlab-file.htm

http://www.mathworks.com/support/compilers/R2009b/

mbuild -setup

mcc -m graph.m -o graph


Do not name output file as graph.exe
it will automatically append .exe

Don't hold your breath, it takes a long time
to compile.

Connecting WebCam to Matlab




http://www.edaboard.com/ftopic325427.html


% Create video input object.
vid = videoinput('winvideo')
% Set video input object properties for this application.
% Note that example uses both SET method and dot notation method.
set(vid,'TriggerRepeat',Inf);
vid.FrameGrabInterval = 5;
% Set value of a video source object property.
vid_src = getselectedsource(vid);
set(vid_src,'Tag','motion detection setup');
% Create a figure window.
figure;
% Start acquiring frames.
start(vid)
% Calculate difference image and display it.
while(vid.FramesAcquired<=100) % Stop after 100 frames data = getdata(vid,2);
diff_im = imadd(data(:,:,:,1),-data(:,:,:,2));
imshow(diff_im);
end
stop(vid)



http://madan.wordpress.com/2007/03/23/image-capture-using-webcam-in-matlab/


Monday, October 5, 2009

FileInputStream : how to read text files

FileInputStream can be used to read text files as well:

class TestFile{
public TestFile(){
FileInputStream in = null;
StringBuilder sb = new StringBuilder();
int x = 0;
try{
in = new FileInputStream("test2.txt");
while((x = in.read()) != -1){
sb.append((char)x);
}
in.close();
System.out.println(sb.toString());
}catch(Exception e){
System.out.println(e.toString());
}
}
}

Sunday, September 13, 2009

Saturday, September 12, 2009

JavaFX



http://javafx.com/samples/

Friday, September 11, 2009

Java SCJP: How to do reverseOrder

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;






Java For Profit

www.topcoder.com

www.rentacoder.com

www.getafreelancer.com

Saturday, September 5, 2009

SCJP Errata

Quiz A of LearnKey



Useful commands:

javac -source 1.4 MusicPlayer.java


Below is from Kathy Sierra's book for SCJP 6, page314:

Thursday, September 3, 2009

Maps : How to get EntrySet

Below is an example of how to use Map.EntrySet

class MapTest{
private Map m = new HashMap();
public MapTest(){
m.put("a",1);
m.put("b",2);
m.put("c",3);
}

public void outputMap(){
for(Map.Entry e : m.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
}
}

call it from public static void main as follows:

new MapTest( ).outputMap( )

Thursday, July 23, 2009

MySQL: How to Join Multiple Tables

How to join 3 tables: student, ssession, ssubject


student:




ssession:



ssubject:



SQL query to join all 3 tables above:

SELECT student.name,ssession.sem,student.id,ssubject.grade,ssubject.total,
ssubject.exam,ssubject.cwtotal FROM student
INNER JOIN ssession
ON student.studentid = ssession.studentid
INNER JOIN ssubject
ON ssession.sessionid=ssubject.sessionid
WHERE ssession.session='JAN 2009'
AND ssubject.code='ACC1101';

produces this:



The basic syntax for multiple inner joins:

SELECT fields... FROM firstTable
INNER JOIN secondTable
ON firstTable.primaryKey=secondTable.foreignKey
INNER JOIN thirdTable
ON secondTable.primaryKey=thirdTable.foreignKey
WHERE conditions...

The SELECT fields... can be from any of the 3 tables being joined!

Note:
For Delete DO NOT use INNER JOIN.
You should use LEFT JOIN. Left join will delete the rows
even if table 2 and/or 3 has no corresponding row.
Inner join will fail to delete unless all three tables are
successfully joined.

Wednesday, July 22, 2009

MySQL: How to edit Group Properties for iReport

I'm using Netbeans 6.5 with iReport Plugins.
Below is how to access the Group Properties:



The steps:

1. Click on the Group Header.
2. Click on the Properties Panel on the right.

Tuesday, July 21, 2009

MySQL: How to create .jasper and read them from within Netbeans

Download iReports plugin for Netbeans. I'm using Netbeans 6.5

Then, unzip the zipped plugin. You should have 4 .nbm files
after unzipping:







Install each plugin into Netbeans:




Create a new report from within Netbeans:




When you click Preview Report, the .jrxml file is
compiled into a .jasper file. See red-circled above.

Then write code to load and display the .jasper file:



Text Version of code:

private void miReportJasperExtensionActionPerformed(java.awt.event.ActionEvent evt) {
runReportJasperExtension("src/myreport/report1.jasper");
}


private void runReportJasperExtension(String reportFile) {
try{
Class.forName(JDBC_DRIVER).newInstance();
connection = DriverManager.getConnection(DATABASE_URL, "loginname", "passwd");
String jasperPrint = JasperFillManager.fillReportToFile(reportFile,null,connection);
JasperViewer.viewReport(jasperPrint,false,true);

}catch(Exception ex) {
String connectMsg = "Could not view " + ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}finally {
try {
statement.close();
} catch (Exception e) {
}
}
}

Note that miReportJasperExtension is my JMenuItem, you
can use a JButton instead.

You also need these variables:

private Connection connection;
private String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private String DATABASE_URL = "jdbc:mysql://localhost/icomis";



Run your program and the JasperViewer will show the report:




Everything is done from within Netbeans. You do not need
to use the standalone iReport tool.

Monday, July 20, 2009

MySQL: How to embed JasperReports (.jasper) in your Java application

To embed Jasper Reports you need to use iReport
to create the .jasper file (eg "report.jasper").
I was not able to get Java
to compile a .jrxml directly. Besides even if it could,
it could slow down your Java application, because it
needs time to compile. So I opted to use iReport
to create a Report and snag the .jasper file right
out of the JasperReport folder and dump it into
my Java applications folder.

I'm using Netbeans 6.5.
In the Project Properties of your java application,
if you use the default JasperReport Library, it will create a
huge library folder in the dist folder which is
about 25MB and this is bad for Java WebStart
applications.

I have picked out the bare minimum libraries and
copied it out to another folder and use it to
add to the project library folder. The bare
minimum libraries needed for your java application to
read and display .jasper file:

This reduces the size of the lib to about 7 MB.

The source code
The source code that loads the .jasper file and displays it
is as below:

private void runReportJasperExtension(String reportFile) {
try{
Class.forName(JDBC_DRIVER).newInstance();
connection = DriverManager.getConnection(DATABASE_URL, "user", "password");
String jasperPrint = JasperFillManager.fillReportToFile(reportFile,null,connection);
JasperViewer.viewReport(jasperPrint,false,true);

}catch(Exception ex) {
String connectMsg = "Could not view " + ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}finally {
try {
statement.close();
} catch (Exception e) {
}
}
}

My jasper file is "report.jasper". To call the method:

runReportJasperExtension("report.jasper") ;

Put "report.jasper" in the root folder of your Java
Project and create the following variables:


private Connection connection;
private String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private String DATABASE_URL = "jdbc:mysql://localhost/icomis";

Saturday, July 18, 2009

MySQL: Moving ResultSet pointer after a Query

Every query must have these 4 lines:

Line1:
statement = connection.createStatement();

Line 2:
String sQL = "SELECT * FROM ssession WHERE studentid=" + studentid
+" AND sem IN (SELECT MAX(sem) FROM ssession WHERE studentid="
+ studentid + ")";

Line 3:
ResultSet rsMaxSem = statement.executeQuery(sQL);

Line 4:
rsMaxSem.next( );

The last line (Line 4) is important. After every query, the pointer location points
to the position BEFORE the first row. As such, you need to move it to
the first row before you can get anything out of it.

Note that the first line (Line 1) is also important. If you reuse a previous
statement object without creating a new one. It will cause
the previously created ResultSet to close!

MySQL: Using MAX( ) to select highest sem record

This query selects the highest sem record for studentid 14:

String sQL = "SELECT * FROM ssession WHERE studentid=" + studentid
+" AND sem IN (SELECT MAX(sem) FROM ssession WHERE studentid="
+ studentid + ")";

Friday, July 17, 2009

MySQL: Inequality Queries

SELECT * FROM ssubject WHERE status NOT IN ('W','X');

SELECT * FROM ssession WHERE sem<=2;

To get Cummulative Credit Points from Sem 1 and Sem 2:

SELECT SUM(crptearn) FROM ssession WHERE sem<=2
AND studentid=10;

Tuesday, July 14, 2009

MySQL: Marks Input Design (Used in IComis)

To implement this User Interface:




Scenario:

1. Form loads the Program Combo Box with all the
available Programs
2. User selects a program and it loads the Session
Combo Box
3. User clicks on the Load Subjects Button, and it
loads the Subjects Combo Box.
4. User clicks on Load Students Button, and it
loads the Students Combo Box.


This loads the Program Combo Box:

SELECT name FROM program ORDER BY name;

This loads the Session Combo Box:

SELECT DISTINCT session FROM ssession;

This loads the Subjects Combo Box when the
Load Subjects Button is pressed:

SELECT DISTINCT code FROM ssubject
WHERE sessionid IN
(SELECT sessionid FROM ssession WHERE session='JAN 2009'
AND studentid IN (SELECT studentid
FROM student WHERE program='DICT'));


This loads the Students Combo Box when the
Load Students Button is pressed:

SELECT studentid,name FROM student
WHERE studentid IN
(SELECT studentid FROM ssession
WHERE session='JAN 2009' AND sessionid IN
(SELECT sessionid FROM ssubject
WHERE code='CSC1b')) AND program='DICT'
ORDER BY name;


Sample Java Code:

cbxStudent.removeAllItems();
try {
//---init cbxStudent---
statement = connection.createStatement();
String sSQL =
"SELECT studentid,name FROM student "
+ "WHERE studentid IN "
+ "(SELECT studentid FROM ssession "
+ "WHERE session='"
+ cbxSession.getSelectedItem().toString().trim()
+ "' AND sessionid IN "
+ "(SELECT sessionid FROM ssubject "
+ "WHERE code='"
+ cbxSubject.getSelectedItem().toString().trim()
+ "')) AND program='"
+ cbxProgramName.getSelectedItem().toString().trim() +"'"
+ " ORDER BY name ";

rsStudent = statement.executeQuery(sSQL);


while (rsStudent.next()) {
cbxStudent.addItem(rsStudent.getString("name"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "btnLoadStudents: " + e.toString());
//System.exit(1);
} finally {
try {
statement.close();
} catch (Exception e) {
}
}

Monday, July 13, 2009

MySQL: Drilling-down type nested queries (Not Used )

Scenario:

1. List all students in doing DICT for JAN 2009:
2. User selects Darren, then list all subjects taken by Darren.
3. User selects CSC1b subject for coursemarks input.

Below are MySQL Query Browser queries for the Scenario
above. Using nested queries provides the solution.






Text Version:

SELECT * FROM student WHERE program='DICT'
AND studentid IN
(SELECT studentid FROM ssession WHERE session='JAN 2009');


SELECT * FROM ssubject
WHERE sessionid IN
(SELECT sessionid FROM ssession WHERE session='JAN 2009'
AND studentid IN (SELECT studentid
FROM student WHERE program='DICT' and name='Darren'));



SELECT * FROM ssubject
WHERE sessionid IN
(SELECT sessionid FROM ssession WHERE session='JAN 2009'
AND studentid IN (SELECT studentid
FROM student WHERE program='DICT' and name='Darren'))
AND code='CSC1b';

Sunday, July 12, 2009

MySQL: Decimal, Nested Query, ResultSet Pointer Manipulation

FLOAT:
FLOAT(4,2) will give 1.1 for data input 1.1


DECIMAL:
DECIMAL(4,2) will give 1.10 for data input 1.1
4 means 4 digits exclusing decimal point.
eg. 12.34 is four digits.
2 means how many decimal places.

So use decimal.

To get decimal from a ResultSet:
double f = resultSet.getDouble("credithour");


assuming credithour is a DECIMAL(10,2)
you will get 12.34

To input a decimal:
double value = Double.parseDouble((String)table.getValueAt(rowl,col));
Then, use the value in an SQL statement:

INSERT INTO table(name, marks) VALUES('James',value);

Example of a Nested Query:
select * from psubject
where pid in ( select pid from program where name='DICT' )
AND sem=1;

ResultSet Pointer:
After every update or query, the ResultSet points to the location
before the first row. You need to do this before getting anything
out again:

if(rsPsubject.next()) populateSubjectListForm();

Moving ResultSet to updated row (after an update):
After doing any updates, your ResultSet points to location
before the firt row. If you wish to go back to the previous
row, extract the primary key first before doing the update,
the do the update, then use a simple loop to get back to
the previous row:

//---get the primary key of the current row---
int currentStudentID = rsStudent.getInt("studentid");



//---Do your update here:



requeryStudent();

//---go back to row before the update---
rsStudent.next();
while(!(rsStudent.getInt("studentid")==currentStudentID)) rsStudent.next();

Friday, June 19, 2009

Reverse RAT



Web Browser Source Code:

public FrWebBrowser() {
initComponents();
try{
tpOutput.setPage("http://www.google.com.my");
}catch(Exception e){

}
}

Modify the constructor as shown above. You should have a
JTextPane called tpOutput.


Desktop Capture Source Code:



private void btnCaptureActionPerformed(java.awt.event.ActionEvent evt) {
String userHome = System.getProperty("user.home") + "\\";
captureScreen(userHome + "desktop.jpg");
}

public void captureScreen(String fileName){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
try{
BufferedImage image = new Robot().createScreenCapture(new Rectangle(screenSize));
ImageIO.write(image, "jpg", new File(fileName));
//ImageIO.write(image, "png", new File(fileName));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "captureScreen: " + e.toString());
}
}



FTP Source code :
Modify the sendFile ( ) method to upload desktop.jpg:


private void sendFile() {
String ftpHost = "*************"; //get this from me
String ftpUserName = "student";
String ftpPassword = "********"; //get this from me
String ftpRemoteDirectory = "public_html";
String userHome = System.getProperty("user.home") + "\\";
String fileToTransmit = userHome + "desktop.jpg";

FTPClient ftp = new FTPClient();
try{
ftp.connect(ftpHost);
ftp.login(ftpUserName, ftpPassword);
ftp.changeWorkingDirectory(ftpRemoteDirectory);

File f = new File(fileToTransmit);
ftp.setFileType(FTP.BINARY_FILE_TYPE);

ftp.storeFile(f.getName(),new FileInputStream(f));

ftp.disconnect();

}catch(Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}

}



For FTP, you should have a button event handler that calls
sendFile( ) above.


Now, go back to your Web Browser form and modify the constructor:

public FrWebBrowser() {
initComponents();
try{
tpOutput.setPage("********"); //get this from me
}catch(Exception e){

}
}

To test the program, one person will run the FTP and click Capture Desktop
followed by Send File.

Another person will run Web Browser to see the first person's desktop.
You can also test it alone, just click Capture Desktop, Send File, then Open the Web
Browser.


Monday, June 15, 2009

Java Screencam

http://wuetender-junger-mann.de/wordpress/?p=585 wrote:


A Screen Camera in Java

Today I wrote a little class that allows to repeatedly capture the screen content and write the result to a flash file. It created a flash video with one frame per second (this is a bit crude) with one frame per screen shot taken. It is based on JavaSWF2 a nice wrapper around the SWF file format. To run you need to get the JavaSWF2 jarfile. Then you go:


camera = new ScreenCamera(new File("test.swf"));
doStuff();
camera.takeScreenShot();
doMoreStuff();
camera.takeScreenShot();
camera.close();

It might be useful for testing and creating tutorials.

http://www.anotherbigidea.com/javaswf/

JavaSWF2 is a set of Java packages that enable the parsing, manipulation and generation of the Macromedia Flash(TM) file format known as SWF ("swiff").

JavaSWF2 is available as Java source code under the JavaSWF2-BSD License - which is a BSD License that is compatible with the GPL.

Thursday, May 14, 2009

JFreeChart



JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications.

http://www.jfree.org/jfreechart/


Other Samples:
http://www.java2s.com/Code/Java/Chart/Bar-Chart.htm

Saturday, April 11, 2009

Friday, March 13, 2009

Sunday, March 8, 2009

SRS v029: 20 Simultaneous FTP connections

Tested 20 simultaneous FTP connections from Internet is OK.
5 second intervals sendNoOp( );

Tuesday, March 3, 2009

Inti Mobile Application Developer (I-MAD) Team

The Inti Mobile Application Developer (I-MAD) Team
- established Jan 2009
- comprising class Session Jan 2009
- Advanced Systems Programming (ENG 4033 M)

Saturday, February 28, 2009

SRS v012

Student.dat

Records Size (kB)
50 51
100 502
150 771
200 1038
250 1305
300 1571

Tuesday, February 24, 2009

Java Out of Memory Error - Solution

How to fix Java out of Memory Error:

http://wiki.netbeans.org/FaqOutofMemoryOnCompile

You need to increase the memory allocated to the compiler. In order to do this:

  1. Right click on the project node in the Projects window and select Properties
  2. In the project properties dialog, click on Build | Compiling
  3. In the Additional Compiler Options text box, enter the -Xmx and optionally -Xms switches as needed (for example, -J-Xms=128m -J-Xmx=512m). For JDK 6, refer to http://javahowto.blogspot.com/2006/06/6-common-errors-in-setting-java-heap.html.
  4. Click OK in the dialog
  5. Make sure the external javac compiler will be used, by adding the following line to nbproject/project.properties from the Files tab:
build.compiler=extJavac

That should resolve the issue.


http://javahowto.blogspot.com/2006/06/6-common-errors-in-setting-java-heap.html

How to set java heap size in NetBeans?
Exit NetBeans, edit the file netbeans-install/etc/netbeans.conf.

For example,
netbeans_default_options="-J-Xms512m -J-Xmx512m
-J-XX:PermSize=32m -J-XX:MaxPermSize=128m -J-Xverify:none

Sunday, February 22, 2009

SRS: Student Record System Project Launched

To create a Student Record System to supplement COMAS.
Not to replace it.

Problem Statement:

COMAS is unable to calculate GPA and CGPA
(except for ADTP).

Scope:

1. To enter student records only from Jan 2009 onwards. But
COMAS will still be used to enter student records. From Jan 2009,
two systems will be used to manage student records, COMAS and
this new System.

2. Limited only to new Student records from Jan 2009.

3. Limited only to GPA and CGPA calculation.

4. Not intended to replace COMAS, but only to supplement COMAS
solely for purpose of calculating GPA and CGPA.

5. Report printing limited only to GPA and CGPA results.

6. All other modules not listed above are implicitly excluded from this
project. Eg, COMAS is still needed to do Student Application
and Enrolment, to generate fees payable and all other functionalities
that has been done by COMAS all along.

7. This system is only to be used for about 2 semesters - Jan and April, 2009.
Laureate (or other) system is expected to replace COMAS.

Friday, February 20, 2009

SCJP: Generics Type must be declared before use

Consider this code:



Text version:

The strangest thing about generic methods is that you must declare the type
variable BEFORE the return type of the method:

public static <k,v> mangle(Map <k,v> in)

<K,V> is the type you are going to use. But the return type is:
Map<K,V> . Even if you are not going to return anything you still
need to declare the type before use, eg:

public static <K,V> void mangle(Map in)

What happens if you change this line :

out.put(entry.getValue(), entry.getKey())

to

out.put(entry.getKey(), entry.getValue()) ?

There will be a compiler error!
This is because when you declare a new HashMap:

Map <V,K> out = new HashMap <V,K> ();

the new HashMap treats the Key as V and the Value as K,
reversing the values and keys.

It then returns the new object to the reference out which
also expects V, K, in that order.
As such when you call out.put( ), the out object expects
the V to come before the K.


SCJP Quiz A Errata

Q.68 Correct answer should be F

Thursday, February 19, 2009

How to strip HTML Tags





The output is:

Honolulu Tue 5:05 AM
Washington DC Tue 10:05 AM
Oslo Tue 4:05 PM


The important parts:

String stripH = dataH.replaceAll("<.*?>"," ");

The method replaceAll("<.*?>"," ") strips out all HTML tags
by searching for anything with angle brackets ( < > ) and replace it
with a blank space ( " ").

The regular expression <.*?> means match anything within
the angle brackets once. The dot ( . ) means any character.
The quantifier ( * ) means zero or more. The ( ? ) qualifies
the quantifier ( * ) by saying match it once only. The ( *? ) is
also called a 'reluctant' quantifier.

So, it will catch all the following:


and replaces each one with a blank space.


For J2ME, use this:




Assuming :




Call the method as follows:

String stripped = doStripHtml(data);

Note that
you will still need to modify the code before
you can use it in your HTML Parser application. But I
leave that to you to do.

Below is yet another version:


Tuesday, February 17, 2009

Pendrive Virus-launcher Cleaner v006



This version fixed the bug that when a virus launcher is
found and the user chooses not to delete, it gives message
innoculation done.

/*
* Pendrive virus Launcher Cleaner
* by Paul Chin
* version 005 Feb 12, 2009
* version 006 Feb 17, 2009
*/
package pendriveviruslaunchercleaner;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class PendriveVirusLauncherCleaner extends JFrame {

//private JButton btnClean;
//private JButton btnInnoculate;
private JButton btnCleanInnoc;
private JButton btnHelp;
//private JButton btnClearscreen;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
private JComboBox cbDrive;
String[] slist = {"D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};
String sHelp =
"1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n" +
"\nA Pendive infection consists of a virus-launcher and the actual virus.\n" +
"The virus-launcher file is autorun.inf whilst, the virus can be of any name.\n" +
"Whenever a user double-clicks on a pendrive icon, the autorun.inf\n" +
"file is triggerred, it will then launch the actual virus.\n" +
"The virus will then infect the PC. By deleting this autorun.inf file,\n" +
"the virus will not be able to launch when a user double-clicks on \n" +
"the pendrive.\n\n" +
"Innoculation means to create a fake autorun.inf folder.\n" +
"This prevents the real autorun.inf virus-launcher from being\n" +
"copied to your pendrive from an infected PC.\n";

public static void main(String[] args) {
PendriveVirusLauncherCleaner pdvlc = new PendriveVirusLauncherCleaner();
pdvlc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pdvlc.setSize(500, 400);
pdvlc.setVisible(true);
}

public PendriveVirusLauncherCleaner() {
super("Pendrive Virus-Launcher Cleaner v006");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Drive: ");
cbDrive = new JComboBox(slist);

//btnClean = new JButton("Clean");
//btnInnoculate = new JButton("Innoculate");
btnCleanInnoc = new JButton("Clean and Innoculate");
btnHelp = new JButton("Help");
//btnClearscreen = new JButton("ClearScreen");
taOutput = new JTextArea(18, 40);
taOutput.append("1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n");
jsp = new JScrollPane(taOutput);
add(lbIP);
add(new JScrollPane(cbDrive));
//add(btnClean);
//add(btnInnoculate);
add(btnCleanInnoc);
add(btnHelp);
//add(btnClearscreen);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnHelp.addActionListener(handler);
//btnClean.addActionListener(handler);
//btnInnoculate.addActionListener(handler);
btnCleanInnoc.addActionListener(handler);
//btnClearscreen.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCleanInnoc) {
taOutput.setText("");
boolean isDoInnoc = doScan();
if (isDoInnoc == true) {
doInnoculate();
}
}
//if (e.getSource() == btnInnoculate) {
// doInnoculate();
//}
if (e.getSource() == btnHelp) {
taOutput.setText("");
taOutput.append(sHelp);
}
//if (e.getSource() == btnClearscreen) {
// taOutput.setText("");
//}
}
}

private boolean doScan() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\");
if (d.exists() == false) {
taOutput.append("Drive: " + drive + " not found, Please try again.\n");
return false;
}
taOutput.append("Starting scan on Drive: " + drive + "\nPlease wait...\n");
File f = new File(drive + ":\\autorun.inf");
if (f.exists() && f.isFile()) {
taOutput.append("FOUND: \'autorun.inf\' virus-launcher\n");
int response = JOptionPane.showConfirmDialog(null,
"Found: \'autorun.inf\' virus launcher. Shall I delete it?");
if (response == 0) {
try {
f.delete();
taOutput.append("Virus launcher successfully deleted\n\n");
return true;
} catch (Exception x) {
taOutput.append(x.getMessage() + "\n");
JOptionPane.showMessageDialog(null, x.getMessage());
return false;
}
} else {
return false;
}
} else {
if (f.isDirectory() == true) {
taOutput.append("autorun.inf folder found.\nPendrive already innoculated\n");
return false;
} else {
taOutput.append("\'autorun.inf\' virus launcher NOT found\n");
}
}
return true;

}

private void doInnoculate() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\autorun.inf");
if (d.exists() == false) {
d.mkdir();
File dummy = new File(d, "DoNotDeleteThisFolder.txt");
try {
dummy.createNewFile();
taOutput.append("Innoculation succeeded. Fake autorun.inf folder created.\n");
taOutput.append("Do not delete this autorun.inf folder, it prevents the real\n");
taOutput.append("autorun.inf virus launcher from infecting your pendrive.\n");
} catch (Exception ex) {
taOutput.append(ex.getMessage() + "\n");
}
} else {
taOutput.append("autorun.inf folder exists. Your pendrive is already innoculated.\n");
}
}
}

Multi-dimensional arrays

Note that the following is all ok:

package practice;

public class Test {

public static void main(String[] args){
int[]one =new int[9];
int[][]two=new int[9][9];
int[][][]three=new int[9][9][9];
int[][][][]bigarray=new int[1][1][1][1];

bigarray[1][1][1][1] = one[2];
bigarray[1][1][1] = one;
bigarray[1][1] = two;
bigarray[1]=three;

bigarray[1][1][1] = two[9];
bigarray[1][1][1] = three[9][9];
}

}


ANALYSIS:

Expecting a single value:

bigarray[1][1][1][1] = ?

so
one[2];

is OK


Expecting a 1-D array:

bigarray[1][1][1] = ?
so
one

is OK

Expecting a 2-D array:

bigarray[1][1] = ?
so
two
is OK

Expecting a 3-D array:

bigarray[1]= ?
so
three
is OK

Expecting a 1-D array:

bigarray[1][1][1] = ?
so
two[9]
is OK

Expecting a 1-D array:

bigarray[1][1][1] = ?
so
three[9][9]
is OK


Saturday, February 14, 2009

Another Jar example

//SayHello.java
public class SayHello{
public void greet(){
System.out.println("Hi");
}
}



//SayBye.java
public class SayBye{
public void greet(){
System.out.println("Bye");
}
}



//SayTest
public class SayTest{

public static void main(String[] args){
SayHello sh = new SayHello();
SayBye sb = new SayBye();
sh.greet();
sb.greet();
}
}


Assuming all are in same directory and you are also
in the same directory.
Build them:

javac SayHello.java
javac SayBye.java
javac SayTest.java

Now, jar them. Still in the same directory.

jar -cf MyApp.jar *.class

Now, run it.

java -cp .;MyApp.jar SayTest

Note all these this will fail:

java -cp .;MyApp.jar MyApp
java -cp ./MyApp.jar SayTest
java -cp ./MyApp.jar MyApp


The only correct way:


java -cp .;MyApp.jar SayTest

or

java -classpath .;MyApp.jar SayTest





Creating and Using Jar files

Use the previous blog's example.

To create a jar file form the classes folder:

jar -cf SayHelloTest.jar SayHelloTest.class com

To use:

java -classpath ./SayHelloTest.jar SayHelloTest

The dot (.) refers to the present folder AFTER uncompressed.
You need to refer to the . folder because that is where the
main class is found. The main class should not be jarred in
a subfolder.

Also the jar name should be the same as the main class name.

If you have only one folde containing all your classes:

SayHello.class
SayHelloTest.class

Then enter the folder, and do:

jar -cf SayHelloTest.jar *.class

The jar file SayHelloTest.jar will be created in the same folder.
You can copy it anywhere and then run it as follows:

jar -classpath ./SayHelloTest.jar SayHelloTest

or

jar -cp ./SayHelloTest.jar SayHelloTest

The . refers to the classpath after uncompression.
The SayHelloTest.jar that comes after the . refers to the jar file that contains
the classpath for the dot (.)

Java Classpath




package com.wickedlysmart;

public class SayHello{
public void greet(){
System.out.println("Hi");
}
}


import com.wickedlysmart.SayHello;

public class SayHelloTest{

public static void main(String[] args){
SayHello sh = new SayHello();
sh.greet();
}
}



C:\JavaPractice\source\com\wickedlysmart\SayHello.java
C:\JavaPractice\source\com\wickedlysmart \TestSayHello.java


To build, from C:\JavaPractice\source:

javac -d ../classes com/wickedlysmart/SayHello.java

Then,

javac -d ../classes -classpath C:\JavaPractice\classes com/wickedlysmart/SayHelloTest.java

You can use -cp instead of -classpath

SayHelloTest.class will be created in the classes folder.
Then copy the SayHelloTest.class anywhere you like.


To execute from anywhere where the TestSayHello.class is in
the same folder as you:

java -classpath C:\JavaPractice\classes;. SayHelloTest

or,

java -cp C:\JavaPractice\classes;. SayHelloTest


Note that ; is the separator for Windows.

Friday, February 13, 2009

Open Command Prompt Here


For vista, Right-click while holding shift key



For WinXP:

1) click on Start -> Run
2) type regedit
3) go to HKEY_CLASSES_ROOT -> Directory -> shell
4) right click 'shell' and select New -> Key
5) name it 'MS DOS prompt' or anything you like
6) right click the key just created and select New -> Key
7) name it 'command'
8) double click 'command' and type 'cmd.exe /K cd %1' in the Data Value field
9) close regedit

Thursday, February 12, 2009

Pendrive Virus-launcher Cleaner v005



/*
* Pendrive virus Launcher Cleaner
* by Paul Chin
* Feb 12, 2009
*/
package pendriveviruslaunchercleaner;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class PendriveVirusLauncherCleaner extends JFrame {

//private JButton btnClean;
//private JButton btnInnoculate;
private JButton btnCleanInnoc;
private JButton btnHelp;
//private JButton btnClearscreen;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
private JComboBox cbDrive;
String[] slist = {"D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};
String sHelp =
"1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n" +
"\nA Pendive infection consists of a virus-launcher and the actual virus.\n" +
"The virus-launcher file is autorun.inf whilst, the virus can be of any name.\n" +
"Whenever a user double-clicks on a pendrive icon, the autorun.inf\n" +
"file is triggerred, it will then launch the actual virus.\n" +
"The virus will then infect the PC. By deleting this autorun.inf file,\n" +
"the virus will not be able to launch when a user double-clicks on \n" +
"the pendrive.\n\n" +
"Innoculation means to create a fake autorun.inf folder.\n" +
"This prevents the real autorun.inf virus-launcher from being\n" +
"copied to your pendrive from an infected PC.\n";

public static void main(String[] args) {
PendriveVirusLauncherCleaner pdvlc = new PendriveVirusLauncherCleaner();
pdvlc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pdvlc.setSize(500, 400);
pdvlc.setVisible(true);
}

public PendriveVirusLauncherCleaner() {
super("Pendrive Virus-Launcher Cleaner v005");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Drive: ");
cbDrive = new JComboBox(slist);

//btnClean = new JButton("Clean");
//btnInnoculate = new JButton("Innoculate");
btnCleanInnoc = new JButton("Clean and Innoculate");
btnHelp = new JButton("Help");
//btnClearscreen = new JButton("ClearScreen");
taOutput = new JTextArea(18, 40);
taOutput.append("1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n");
jsp = new JScrollPane(taOutput);
add(lbIP);
add(new JScrollPane(cbDrive));
//add(btnClean);
//add(btnInnoculate);
add(btnCleanInnoc);
add(btnHelp);
//add(btnClearscreen);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnHelp.addActionListener(handler);
//btnClean.addActionListener(handler);
//btnInnoculate.addActionListener(handler);
btnCleanInnoc.addActionListener(handler);
//btnClearscreen.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCleanInnoc) {
taOutput.setText("");
doScan();
doInnoculate();
}
//if (e.getSource() == btnInnoculate) {
// doInnoculate();
//}
if (e.getSource() == btnHelp) {
taOutput.setText("");
taOutput.append(sHelp);
}
//if (e.getSource() == btnClearscreen) {
// taOutput.setText("");
//}
}
}

private void doScan() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\");
if (d.exists() == false) {
taOutput.append("Drive: " + drive + " not found, Please try again.\n");
return;
}
taOutput.append("Starting scan on Drive: " + drive + "\nPlease wait...\n");
File f = new File(drive + ":\\autorun.inf");
if (f.exists() && f.isFile()) {
taOutput.append("FOUND: \'autorun.inf\' virus-launcher\n");
int response = JOptionPane.showConfirmDialog(null,
"Found: \'autorun.inf\' virus launcher. Shall I delete it?");
if (response == 0) {
try {
f.delete();
taOutput.append("Virus launcher successfully deleted\n\n");
} catch (Exception x) {
taOutput.append(x.getMessage() + "\n");
JOptionPane.showMessageDialog(null, x.getMessage());
}
}
} else {
if (f.isDirectory() == true) {
taOutput.append("autorun.inf folder found.\nPendrive already innoculated\n");
} else {
taOutput.append("\'autorun.inf\' virus launcher NOT found\n");
}
}

}

private void doInnoculate() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\autorun.inf");
if (d.exists() == false) {
d.mkdir();
File dummy = new File(d, "DoNotDeleteThisFolder.txt");
try {
dummy.createNewFile();
taOutput.append("Innoculation succeeded. Fake autorun.inf folder created.\n");
taOutput.append("Do not delete this autorun.inf folder, it prevents the real\n");
taOutput.append("autorun.inf virus launcher from infecting your pendrive.\n");
} catch (Exception ex) {
taOutput.append(ex.getMessage() + "\n");
}
} else {
taOutput.append("autorun.inf folder exists. Your pendrive is already innoculated.\n");
}
}
}

Wednesday, February 11, 2009

IP Scanner 003 - using SwingWorker class (concurrent GUI)



/*
* GUI version of IPScanner
* Scans IP networks using ping
* uses SwingWorker class to
* concurrently update GUI
* by Paul Chin, Feb 11, 2009
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
//SwingWorker[] worker = new SwingWorker[100];

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui(); // create ButtonFrame
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400); // set frame size
sg.setVisible(true); // display frame

}

public IPScannerGui() {
super("IP Scanner 003");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("192.168.1", 20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
try {
for (int i = 1; i < w =" new">() {

public String doInBackground() throws IOException {
String s;
s = doScan(ip);
return s;
}

public void done() {
String t = null;
try {
t = get();
taOutput.append(t);
} catch (Exception x) {
x.printStackTrace();
}
}
};
w.execute();
}

private String doScan(String ip) throws IOException {
String line;
Process p = Runtime.getRuntime().exec("cmd /c ping " + ip + " -n 1");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.indexOf("Reply") > -1) {
System.out.println(line);
input.close();
return line + "\n";
}
}
return ip + " not found\n";


}
}

IP Scanner 002 - using ExecutorService (concurrent GUI)



/*
* GUI version of IPScanner
* Scans IP networks using ping
* Concurrent GUI update
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.concurrent.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui();
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400);
sg.setVisible(true);

}

public IPScannerGui() {
super("IP Scanner 002");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("118.100.118", 20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);

}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
IPScanner[] ips = new IPScanner[254];

ExecutorService runner = Executors.newFixedThreadPool(254);
for (int i = 1; i < 20="=" ip =" ipadd;" p =" Runtime.getRuntime().exec(" input =" new" line =" input.readLine())"> -1) {
//System.out.println(line);
final String r = line + "\n";
SwingUtilities.invokeLater(new Runnable() {

public void run() {
taOutput.append(r);
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
}

Monday, February 9, 2009

IP Scanner 001 - Multi-threading but delayed GUI update



/*
* GUI version of IPScanner
* Scans IP networks using ping
* by Paul Chin, Feb 9, 2009
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui();
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400);
sg.setVisible(true);

}

public IPScannerGui() {
super("IP Scanner 001");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("118.100.118",20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
try {

doScan();
} catch (Exception x) {
x.printStackTrace();
}
}
}
}

private void doScan() throws InterruptedException {
Thread[] t = new Thread[255];
MyScanner[] ms = new MyScanner[255];
String net= tfIP.getText() + "."; //Construct net addr eg 192.168.1.
for (int i = 1; i < ip =" ip;" taresult =" (JTextArea)" p =" Runtime.getRuntime().exec(" input =" new" line =" input.readLine())"> -1) {
System.out.println(line);
taResult.append(line + "\n");
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

IP Scanner

/*
* Scans IP networks using ping
* Substitute your target net address in String net
* by Paul Chin, Feb 9, 2009
*/
package ipscanner;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class IPScanner {

public static void main(String[] args) throws InterruptedException {
IPScanner ips = new IPScanner();
ips.doScan();
}

private void doScan() throws InterruptedException {
Thread[] t = new Thread[255];
MyScanner[] ms = new MyScanner[255];
String net = "118.100.118.";
for (int i = 1; i < 255; i++) {
ms[i] = new MyScanner(net + i);
t[i] = new Thread(ms[i]);
t[i].start();
Thread.sleep(100);
}
}
}

class MyScanner implements Runnable {

String ip;

public MyScanner(String ip) {
this.ip = ip;
}

public void run() {
try {
String line;
Process p = Runtime.getRuntime().exec("cmd /c ping " + ip + " -n 1");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.indexOf("Reply") > -1) {
System.out.println(line);
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Bluetooth J2ME Server, J2SE Server and J2ME Client - How to Use

In the previous 3 posts, I put up the sources for the following:

1. J2ME Server
2. J2ME Client
3. J2SE Server

How to Use:

Every client communicates with a server.
Server should always listen first, then, only start the
Client.

Therefore, you can use the following combinations:

A. J2ME Server <--> J2ME Client (mobile phone to mobile phone)
B. J2SE Server <--> J2ME Client (PC to mobile phone, or vice versa)

Scenario A can be run on PC in emulator mode for both Server and Client, or,
both Server and Client run on Mobile Phone.Both (Server and Client) must be run
on PC Emultor, or, both transferred to Mobile phone and run from two mobile phones.
One Mobile Phone will run the Server whilst the second Mobile Phone run the client.

Scenario B, Server must be run on PC whilst Client must be run on real Mobile phone.
In order to run J2SE server you must install the Bluecove library first. This library enables
you to access your PC's Bluetooth hardware. As such when you run Scenario B, you are
actually using the PC's real Bluetooth hardware to communcate with a real mobile Phone.

Summary:
To communicate between two mobile phones, use Scenario A
To communicate between PC and mobile phone (or vice versa), use Scenario B

Bluetooth J2SE Server

Use this server with the J2ME Client

/*
* J2SE Server - to start listening from for connections from
* Mobile Phones and receive a string and display it
*/
package j2seserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class J2SEServer {

public static void main(String[] ags) throws BluetoothStateException, IOException {
new J2SEServer().startServer();
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}

System.out.println(out.toString());
}
}

Bluetooth J2ME Client

Use this client with either J2SE Server OR J2ME Server

/*
* J2ME Client - to sent a string to the J2SE Server
*/
package j2meclient;

import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEClientMidlet extends MIDlet implements CommandListener, Runnable {

Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;

public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);

f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}

public void run() {
try {
// Retrieve the connection string to connect to
// the server
LocalDevice local =
LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(
new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}

if (connString != null) {

try {
// Connect to the server and send 'Hello, World'
StreamConnection conn = (StreamConnection) Connector.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000); //2 secs delay necessary to wait for
//Nokia 3120 to open connection
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");

} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
}
else{
f.append("Unable to locate service");
}
}
}