Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Monday, February 28, 2011

One To One relationship


In one to one relationship the primary key of the first table is foreign key in the second table, and each row from the first table has exactly one or none correspondence in the second table. For proving this relationship, we will:

• Create two tables
• Set the one to one relationship
• Apply a set of JOINs, to select a set of records
• Delete a record in cascade style

Creating two tables

We will create a table named Managers and a table named Teams, and we suppose that each manager has a team and each team has a single manager, which requires the relationship one to one. The tables were designed in MySQL Workbench 5.2 CE, and they look like below:

Set the one to one relationship

Next, we can create a one to one relationship from table Teams to table Managers – the primary key from Tables (id), will be a foreign key in Managers (this will be a generated column). We did that using the MySQL Workbench 5.2 CE EER Diagram designer, and it looks like below:

As you can see the foreign key is represented by the Teams_id column, which was auto-generated for our relationship. The designer reveals this relationship, like below:

The SQL statements that stand behind these operations (create table and relationship), is listed below:

-- -----------------------------------------------------
-- Table `mydb`.`Teams`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`Teams` ;

CREATE TABLE IF NOT EXISTS `mydb`.`Teams` (
`id` INT NOT NULL ,
`team` VARCHAR(45) NULL ,
PRIMARY KEY (`id`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `mydb`.`Managers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`Managers` ;

CREATE TABLE IF NOT EXISTS `mydb`.`Managers` (
`id` INT NOT NULL ,
`m_name` VARCHAR(45) NULL ,
`m_surname` VARCHAR(45) NULL ,
`invest` VARCHAR(45) NULL ,
`Teams_id` INT NOT NULL ,
PRIMARY KEY (`id`, `Teams_id`) ,
INDEX `fk_Managers_Teams` (`Teams_id` ASC) ,
CONSTRAINT `fk_Managers_Teams`
FOREIGN KEY (`Teams_id` )
REFERENCES `mydb`.`Teams` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;

Next, you can populate the tables with a few records like below:

The corresponding SQL is listed below:

-- -----------------------------------------------------
-- Data for table `mydb`.`Teams`
-- -----------------------------------------------------
SET AUTOCOMMIT=0;
USE `mydb`;
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (1, 'Manchester United');
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (2, 'Juventus Torino ');
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (3, 'Real Madrid');
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (4, 'FC Barcelona');
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (5, 'FC Liverpool');
INSERT INTO `mydb`.`Teams` (`id`, `team`) VALUES (6, 'FC Steaua');

COMMIT;

-- -----------------------------------------------------
-- Data for table `mydb`.`Managers`
-- -----------------------------------------------------
SET AUTOCOMMIT=0;
USE `mydb`;
INSERT INTO `mydb`.`Managers` (`id`, `m_name`, `m_surname`, `invest`, `Teams_id`)
VALUES (1, 'Roy', 'Hodgson', '10000$', 5);
INSERT INTO `mydb`.`Managers` (`id`, `m_name`, `m_surname`, `invest`, `Teams_id`)
VALUES (2, 'Marcello', 'Lippi', '35000$', 2);
INSERT INTO `mydb`.`Managers` (`id`, `m_name`, `m_surname`, `invest`, `Teams_id`)
VALUES (3, 'Alex', 'Ferguson', '100000$', 1);
INSERT INTO `mydb`.`Managers` (`id`, `m_name`, `m_surname`, `invest`, `Teams_id`)
VALUES (4, 'Jack', 'Greenwell', '80000$', 4);
INSERT INTO `mydb`.`Managers` (`id`, `m_name`, `m_surname`, `invest`, `Teams_id`)
VALUES (5, 'Jose', 'Mourinho', '200000$', 3);

COMMIT;

Apply a set of JOINs, to select a set of records

SQL INNER JOIN Keyword (INNER JOIN is the same as JOIN)
• The INNER JOIN keyword return rows when there is at least one match in both tables.

Teams table contains a record (id:6) that has no match in Managers table. As you can see that record was omitted!!!
SQL LEFT JOIN Keyword(In some databases LEFT JOIN is called LEFT OUTER JOIN.)
• The LEFT JOIN keyword returns all rows from the left table (Teams), even if there are no matches in the right table (Managers).

As you can see, in the LETF JOIN statement the record id:6 from Teams is listed!
SQL RIGHT JOIN Keyword (In some databases RIGHT JOIN is called RIGHT OUTER JOIN)
• The RIGHT JOIN keyword returns all rows from the right table (Managers), even if there are no matches in the left table (Teams).

Delete a record in cascade style

MySQL allows us to specify the delete style, like this:

[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, do not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table. Currently, cascaded foreign key actions do not activate triggers.
SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported. If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICT. InnoDB rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.

Our tables were generated with CASCADE reference option, therefore if we delete the from Teams the record with id:3, then the cascade style should automatically result in deleting the record with id:5:

The SQL DELETE statement for this operation:

DELETE FROM Teams WHERE Teams.id=3

After you run this SQL against the database, the result will look like below:

Saturday, February 26, 2011

Ask Users Before Rejecting X509 Certificate


This tip implements a X509TrustManager that asks clients before it rejects a certificate chain. The keystore used is just an example— you can adapt it for any other keystore:

import java.security.*;
import java.security.cert.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

class X509TrustManagerDialog implements ActionListener{

Button accept=new Button("ACCEPT");
Button reject=new Button("REJECT");
Label label1=new Label("A X.509 certificate was rejected to the standard verification");
Label label2=new Label("Accept / Reject this certificate ?");
Dialog t=null;

public X509TrustManagerDialog()
{
t=new Dialog(new Frame());

t.setSize(400,100);
t.setLocation(50,50);
t.setModal(true);
t.setResizable(false);
t.setLayout(new FlowLayout());
t.add(label1);t.add(label2);t.add(accept);t.add(reject);

accept.addActionListener(this);
reject.addActionListener(this);

t.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
if((e.getActionCommand()).equals("ACCEPT"))
{
t.setVisible(false);
return;
}

if((e.getActionCommand()).equals("REJECT"))
System.exit(1);
}

}

class QueryX509TrustManager implements X509TrustManager{

X509TrustManager X509TM=null; //default X.509 TrustManager
TrustManagerFactory ClientTMF=null; //SunX509 factory from SunJSSE provider
KeyStore ClientKS=null; //keystore SSLCert - just an example

TrustManager[] ClientTMs=null; //all the TrustManagers from SunX509 factory

char[] ClientKeystorePassword="Varonmykey".toCharArray();//SSLCert access password

//QueryX509TrustManager constructor
public QueryX509TrustManager(){

//get an KeyStore object of type JKS (default type)
try{
ClientKS=KeyStore.getInstance("JKS");
}catch(java.security.KeyStoreException e)
{System.out.println("1: "+e.getMessage());}

//loading SSLCert keystore
try{
ClientKS.load(new FileInputStream("SSLKeystore"),ClientKeystorePassword);
}catch(java.io.IOException e)
{System.out.println("2: "+e.getMessage());
}catch(java.security.NoSuchAlgorithmException e)
{System.out.println("3: "+e.getMessage());
}catch(java.security.cert.CertificateException e)
{System.out.println("4: "+e.getMessage());}

//TrustManagerFactory of SunJSSE
try{
ClientTMF=TrustManagerFactory.getInstance("SunX509","SunJSSE");
}catch(java.security.NoSuchAlgorithmException e)
{System.out.println("5: "+e.getMessage());
}catch(java.security.NoSuchProviderException e)
{System.out.println("6: "+e.getMessage());}

//call init method for ClientTMF
try{
ClientTMF.init(ClientKS);
}catch(java.security.KeyStoreException e)
{System.out.println("7: "+e.getMessage());}

//get all the TrustManagers
ClientTMs=ClientTMF.getTrustManagers();

//looking for a X509TrustManager instance
for(int i=0;i < ClientTMs.length;i++)
{
if(ClientTMs[i] instanceof X509TrustManager)
{
System.out.println("X509TrustManager certificate found...");
X509TM=(X509TrustManager)ClientTMs[i];
return;
}
}
}

//checkClientTrusted
public void checkClientTrusted(X509Certificate[] chain,String authType)
throws CertificateException{
try{
System.out.println("Verify-client...");
X509TM.checkClientTrusted(chain,authType);
}catch(CertificateException e)
{
System.out.println("I: "+e.getMessage());
X509TrustManagerDialog valid=new X509TrustManagerDialog();
}
}

//checkServerTrusted
public void checkServerTrusted(X509Certificate[] chain,String authType)
throws CertificateException{
try{
System.out.println("Verify-server...");

//ask the user what to do ?
X509TM.checkServerTrusted(chain,authType);
}catch(CertificateException
e)
{
System.out.println("II: "+e.getMessage());

//ask the user what to do ?
X509TrustManagerDialog valid=new X509TrustManagerDialog();
}
}

//getAcceptedIssuers
public X509Certificate[] getAcceptedIssuers(){
return X509TM.getAcceptedIssuers();
}
}

Find Out What Cipher Suites Are Supported in JSSE


You can make the Java Secure Socket Extension list the supported cipher suites using the following code:

SocketFactory SSLF=SSLSocketFactory.getDefault();
SSLsoclu=SSLF.createSocket("12.110.20.211",443);

String[] cipher_suites=((SSLSocket)
SSLsoclu).getSupportedCipherSuites();
for(int i=0;i< cipher_suites.length;i++)
System.out.println(cipher_suites[i]);


Run :

SSL_RSA_WITH_RC4_128_MD5
SSL_RSA_WITH_RC4_128_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA
SSL_RSA_WITH_3DES_EDE_CBC_SHA
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
SSL_RSA_WITH_DES_CBC_SHA
SSL_DHE_RSA_WITH_DES_CBC_SHA
SSL_DHE_DSS_WITH_DES_CBC_SHA
SSL_RSA_EXPORT_WITH_RC4_40_MD5
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
SSL_RSA_WITH_NULL_MD5
SSL_RSA_WITH_NULL_SHA
SSL_DH_anon_WITH_RC4_128_MD5
TLS_DH_anon_WITH_AES_128_CBC_SHA
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
TLS_KRB5_WITH_RC4_128_SHA
TLS_KRB5_WITH_RC4_128_MD5
TLS_KRB5_WITH_3DES_EDE_CBC_SHA
TLS_KRB5_WITH_3DES_EDE_CBC_MD5
TLS_KRB5_WITH_DES_CBC_SHA
TLS_KRB5_WITH_DES_CBC_MD5
TLS_KRB5_EXPORT_WITH_RC4_40_SHA
TLS_KRB5_EXPORT_WITH_RC4_40_MD5
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
TLS_DHE_DSS_WITH_AES_128_CBC_SHA

Extract JAR and ZIP Entries with JarURLConnection


Use the following code to extract JAR and ZIP Entries with JarURLConnection:

import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.*;
import java.util.jar.*;

class read extends Frame{

URL url=null;
JarURLConnection URLcon=null;
JarFile jar=null;
TextArea TA=new TextArea(15,35);

public read(String titlu)
{
super(titlu);
}

void init()
{
setLayout(new FlowLayout());
setSize(300,300);
add(TA);
setVisible(true);
}

public void getURLContent()
{
try {
//local file
//url=new URL(
//"jar:file:/C:/Program%20Files/Java/jdk1.5.0/jre/lib/jsse.jar!/"
//);
//remote file
url=new URL(
"jar:http://sosnoski.com/opensrc/xmlbench/code/xmlbench.jar!/");

URLcon=(JarURLConnection)(url.openConnection());
jar=URLcon.getJarFile();
}catch(MalformedURLException e)
{System.out.println("Eroare1:"+e.getMessage());
}catch(IOException e)
{System.out.println("Eroare2:"+e.getMessage());}
}

void entry()
{
Enumeration entries=jar.entries();
while(entries.hasMoreElements())
{
String entry=((JarEntry)entries.nextElement()).getName();
TA.append(entry+"\n");
}
}

}

public class JarURLContent{
public static void main(String[] args)
{
read t=new read("URL");
t.getURLContent();
t.init();
t.entry();
}
}

Execute a SQL Statement with Variable Parameters


When you need to execute the same SQL statement (in general an UPDATE) multiple times with different parameter values you can use the PrepareStatement method like this:

Connection conn=null;
PreparedStatement pst=null;
String[] nm=new String[3];
int[] nc=new int[3];
...
try {
nm[0]="Costescu",nm[1]="Alexandrescu",nm[2]="Popovici";
nc[0]=234423;nc[1]=123344;nc[2]=534562;

pst=conn.prepareStatement("UPDATE Table1 SET Nume=? WHERE Nr_cont=?");
for(int i=0;i<=2;i++)
{
pst.setString(1,nm[i]);
pst.setInt(2,nc[i]);
pst.executeUpdate();
}
}catch (SQLException e){System.out.println(e.getMessage());}
...

Evaluate XQuery Expressions with Java and SAXON 8


The following tip shows you how to combine Java and SAXON 8 in order to evaluate XQuery expressions. This application presumes that the XQuery expression is in an external file, called Q.xquery, and the XML file used for interrogation is called XML.xml:

//Java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;

//SAXON
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.query.StaticQueryContext;
import net.sf.saxon.query.XQueryExpression;
import net.sf.saxon.trans.XPathException;

public class XQueryExample {

public static void main(String[] args) {

//the Q.xquery file
InputStream queryStream=null;
String queryFileName="C://Data_Local//XML//XQuery//Q.xquery";

//documentul XML ce va fi interogat este reprezentat de
//fisierul AircraftDealer.xml
File XMLStream=null;
String xmlFileName="C://Data_Local//XML//XQuery//XML.xml";

//print the result to the console
OutputStream destStream=System.out;

//compile the XQuery expression
XQueryExpression exp=null;

//create a Configuration object
Configuration C=new Configuration();

//static and dynamic context
StaticQueryContext SQC=new StaticQueryContext(C);
DynamicQueryContext DQC=new DynamicQueryContext(C);

//indentation
Properties props=new Properties();
props.setProperty(OutputKeys.METHOD,"xml");
props.setProperty(OutputKeys.INDENT,"yes");

try{
queryStream=new FileInputStream(queryFileName);
SQC.setBaseURI(new File(queryFileName).toURI().toString());

//compilation
exp=SQC.compileQuery(queryStream,null);
SQC=exp.getStaticContext();
}catch(net.sf.saxon.trans.XPathException e)
{System.err.println(e.getMessage());
}catch(java.io.IOException e)
{System.err.println(e.getMessage());}

//get the XML ready
try{
XMLStream=new File(xmlFileName);
InputSource XMLSource=new InputSource(XMLStream.toURI().toString());
SAXSource SAXs=new SAXSource(XMLSource);
DocumentInfo DI=SQC.buildDocument(SAXs);
DQC.setContextNode(DI);

//evaluating
exp.run(DQC,new StreamResult(destStream),props);
destStream.close();
}catch(net.sf.saxon.trans.XPathException e)
{System.err.println(e.getMessage());
}catch (java.io.IOException e)
{System.err.println(e.getMessage());}

}
}

Encode and Decode URLs Using UTF-8


This tip shows you how to encode and decode your URLs using the UTF-8 character encoding:

import java.net.*;

public class URL_Encoder_Decoder{
public static void main(String[] args){

String url = "@sir de caractere@,nr. 1290 'paragraf 3'";
try{
String encode_url=URLEncoder.encode(url,"UTF-8");
String decode_url=URLDecoder.decode(encode_url,"UTF-8");
System.out.println(url);
System.out.println(encode_url);
System.out.println(decode_url);
}catch(java.io.UnsupportedEncodingException e)
{System.out.println("Error:"+e.getMessage());}
}
}

Output:
@sir de caractere@,nr. 1290 'paragraf 3'
%40sir+de+caractere%40%2Cnr.+1290+%27paragraf+3%27
@sir de caractere@,nr. 1290 'paragraf 3'

Developing a NIO-Based Client


This tip shows you how to develop a New I/O-based client. As you probably know, NIO offers many advantages such as speed and the ability to maintain a large number of concurrent connections. Here's the code:

import java.io.*;
import java.nio.*;
import java.net.*;
import java.util.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class ClientNIO{
public static void main(String args[])
{
InetSocketAddress ISA=null;
SocketChannel clientNIO=null;
Selector selector=null;
SelectionKey key=null;

int port=5000;

try{
clientNIO=SocketChannel.open();
clientNIO.configureBlocking(false);
}catch(IOException e)
{System.out.println(e.getMessage());}

try{
InetAddress addr=InetAddress.getByName("localhost");
ISA=new InetSocketAddress(addr,port);
}catch(UnknownHostException e)
{System.out.println(e.getMessage());}

try{
clientNIO.connect(ISA);
}catch(IOException e)
{System.out.println(getMessage());}

try{
selector = Selector.open();
}catch(IOException e)
{System.out.println(e.getMessage());}

try{
SelectionKey clientKey=clientNIO.register(selector,SelectionKey.OP_CONNECT);
}catch(Exception e)
{System.out.println(e.getMessage());}

try{
while(selector.select(1000)>0)
{
Set keys=selector.selectedKeys();
Iterator iter=keys.iterator();
while(iter.hasNext())
{
key=(SelectionKey)iter.next();
iter.remove();
SocketChannel channel=(SocketChannel)key.channel();
if((key.isValid())&&(key.isConnectable()))
{
if(channel.isConnectionPending())channel.finishConnect();
ByteBuffer serverBuf = null;

System.out.println("Connected...");

while(true)
{
serverBuf = ByteBuffer.wrap(new String
("Answer me dear server ...").getBytes());
channel.write(serverBuf);

serverBuf.clear();

ByteBuffer clientBuf = ByteBuffer.allocateDirect(1024);
clientBuf.clear();
channel.read(clientBuf);

clientBuf.flip();
Charset charset=Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();

CharBuffer charBuffer = decoder.decode(clientBuf);
System.out.println(charBuffer.toString());
clientBuf.clear();
}
}
}
}
}catch(IOException e)
{System.out.println(e.getMessage());
try{
key.channel().close();key.cancel();
}catch(Exception ex)
{System.out.println(e.getMessage());}}

}

Developing a NIO Server


As you probably know, NIO offers many advantages—like speed and a large number of concurrent connections:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class ServerNIO{
public static void main(String[] args){

ServerSocketChannel serverNIO=null;
InetSocketAddress ISA=null;
Selector selector=null;
ByteBuffer clientBuf=null;
int port=5000;

try{
serverNIO=ServerSocketChannel.open();
serverNIO.configureBlocking(false);
}catch(IOException e)
{System.out.println(e.getMessage());}

try{
InetAddress addr=InetAddress.getByName("localhost");
ISA=new InetSocketAddress(addr,port);
}catch(UnknownHostException e)
{System.out.println(e.getMessage());}

try{
ServerSocket SS=serverNIO.socket();
SS.bind(ISA);
System.out.println("- Ready -");
}catch(IOException e)
{System.out.println(e.getMessage());}

try{
selector=Selector.open();
serverNIO.register(selector,SelectionKey.OP_ACCEPT);
}catch(IOException e)
{System.out.println(e.getMessage());}

while(true)
{try{
selector.select();
}catch(IOException e)
{System.out.println(e.getMessage());}

Set keys=selector.selectedKeys();
Iterator iter=keys.iterator();

while(iter.hasNext())
{
SelectionKey key=(SelectionKey)iter.next();
iter.remove();

if((key.isValid())&&(key.isAcceptable()))
{
try{
ServerSocketChannel SSC=(ServerSocketChannel)key.channel();
SocketChannel clientNIO=SSC.accept();
clientNIO.configureBlocking(false);
SelectionKey SK=clientNIO.register(
selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}catch(IOException e)
{System.out.println(e.getMessage());}
}

if((key.isValid())&&(key.isReadable()))
{
try{
SocketChannel clientNIO=(SocketChannel)key.channel();
clientBuf=ByteBuffer.allocateDirect(1024);
clientNIO.read(clientBuf);
}catch(IOException e)
{System.out.println(e.getMessage());
try{
key.channel().close();key.cancel();
}catch(IOException ex)
{System.out.println(e.getMessage());}}

clientBuf.flip();
Charset charset=Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
try{
CharBuffer charBuffer = decoder.decode(clientBuf);
System.out.println(charBuffer.toString());
clientBuf.clear();
}catch(IOException e)
{System.out.println(e.getMessage());}
}
if((key.isValid())&&(key.isWritable()))
{
SocketChannel clientNIO=(SocketChannel)key.channel();
ByteBuffer serverBuf=ByteBuffer.allocateDirect(1024);
try{
String s="Message from server ...";
serverBuf.put(s.getBytes());
serverBuf.flip();
clientNIO.write(serverBuf);
}catch(IOException e)
{System.out.println(e.getMessage());
try{
key.channel().close();key.cancel();
}catch(IOException ex)
{System.out.println(ex.getMessage());}}
}
}
}
}
}

Creating a StAX Filter for XML


This tip creates a StAX filter using the javax.xml.stream.StreamFilter interface. This filter accepts only characters, but you can also set the filter XML to retrieve only elements, attributes, or both:

class BasicStreamFilter implements StreamFilter{

public BasicStreamFilter(){}

//implement the StreamFilter.accept method
public boolean accept(XMLStreamReader XMLsrFilter)
{
if(XMLsrFilter.isCharacters())return true; else return false;
}
}
...

public class StAXBasicStreamFilter{

public StAXBasicStreamFilter(){}

public static void main(String[] args)
{
XMLInputFactory XMLif=null;
XMLStreamReader XMLsr=null;
XMLStreamReader XMLsrFilter=null;

System.setProperty("javax.xml.stream.XMLInputFactory",
"com.sun.xml.stream.ZephyrParserFactory");

//create an XMLInputFactory intance
XMLif=XMLInputFactory.newInstance();

//setting a few properties
XMLif.setProperty("javax.xml.stream.isSupportingExternalEntities",Boolean.TRUE);
XMLif.setProperty("javax.xml.stream.isNamespaceAware",Boolean.TRUE);
XMLif.setProperty("javax.xml.stream.isReplacingEntityReferences",Boolean.TRUE);

//get an XMLStreamReader object
try{
XMLsr=XMLif.createXMLStreamReader
("file:///C:/Data_Local/XML/",new FileReader
("C://Data_local//XML//AutoDealer.xml"));
XMLsrFilter=XMLif.createFilteredReader(XMLsr,new BasicStreamFilter
());
}catch(java.io.FileNotFoundException e)
{System.out.println(e.getMessage());
}catch(javax.xml.stream.XMLStreamException e)
{System.out.println(e.getMessage());}

...
while(XMLsrFilter.hasNext())
{
int ev=XMLsrFilter.getEventType();
...

Create Your Own Exception


Here's an example of how to create an exception. You can extend this example as needed for your own applications. The important principle is the exeption's mechanism, not its subject:

class PrivateException extends Exception{

//constructor without parameters
public PrivateException() {}

//constructor for exception description
public PrivateException(String description)
{
super(description);
}
}

class Test
{
public Test(){}

//this method will throw a PrivateException
void method1(int a ,int b) throws PrivateException
{
System.out.println("You called method1 !!!\n\n");
//specify when to generate the exception
if(a==b)
{
String description="In method \"method1\" a PrivateException
has been generated\n "+
" The "+a+" and "+b+" arguments are equal!!!\n"+
" Call this method with no equal arguments.";
throw new PrivateException(description);
}
}

//this method will throw a PrivateException
void method2(int a, int b)throws PrivateException
{
System.out.println("You called method2 !!!\n\n");
//specify when to generate the exception
if((a*b)>10)
{
String description="In method \"method2\" a PrivateException
has been generated\n "+
" The "+a+" * "+b+" is grater that 10 !!!\n"+
" Call this method with smaller arguments.";
throw new PrivateException(description);
}
}
}

public class TestPrivateException{
public static void main(String[] args)
{
Test t=new Test();
try{
t.method1(22,20); //NO EXCEPTION
t.method2(11,23); //EXCEPTION
}catch(PrivateException e)
{e.printStackTrace();}
}
}

Create XMLSchema DataTypes Direct from Java


This tip shows you how to create XMLSchema datatypes direct from Java, using the javax.xml.datatype.* package. In this example you'll create a Duration object (xs:duration in XMLSchema) and a XMLGregorianCalendar object (any date/time XMLSchema type).

import javax.xml.datatype.*;

public class Datatype{
public static void main(String[] args)
{
DatatypeFactory DF=null;

//DatatypeFactory
try{
DF=DatatypeFactory.newInstance();
}catch(javax.xml.datatype.DatatypeConfigurationException e)
{System.err.println(e.getMessage());}

//XMLGregorianCalendar
XMLGregorianCalendar XMLGC=DF.newXMLGregorianCalendar
(2010,DatatypeConstants.JANUARY,1,0,0,0,0,0);

//use of XMLGregorianCalendar.toXMLFormat method
System.out.println(XMLGC.toXMLFormat());

//Duration
Duration D=DF.newDuration(true,0,48,0,0,0,0);

//add the amount of time D to XMLGC
//apelam la metoda XMLGregorianCalendar.add
XMLGC.add(D);

//use of XMLGregorianCalendar.toXMLFormat method
System.out.println(XMLGC.toXMLFormat());
}
}

Output:
2010-01-01T00:00:00.000Z
2014-01-01T00:00:00.000Z

Create an RMI-JRMP-SSL Server Using the New JDK1.5.0 Classes


Usually, the RMI client is an RMI client only in that it specifies the true store zone for certificates. For example, you can use any certificate available to System.setProperty:

("javax.net.ssl.trustStore","SSLcert"); System.setProperty
("javax.net.ssl.trustStorePassword","e1002qa2");

In this example, the remote interface is SumaInterface and there's only one remote method called Suma:

import java.rmi.*;
import java.rmi.server.*;
import javax.rmi.ssl.SslRMIServerSocketFactory;
import javax.rmi.ssl.SslRMIClientSocketFactory;

public class SumaImpl extends UnicastRemoteObject implements SumaInterface{

//constructor
public SumaImpl(int port,RMIClientSocketFactory rmiC, RMIServerSocketFactory rmiS)
throws RemoteException
{
//optional
super(port,rmiC,rmiS);
}

//implementing the Suma method
public int Suma(int a,int b)throws RemoteException{
return (a+b);
}

public static void main(String[] args)
{
SumaImpl SI=null;

System.setProperty("javax.net.ssl.keyStore","SSLcert");
System.setProperty("javax.net.ssl.keyStorePassword","e1002qa2");

RMIClientSocketFactory rmiClientSocketFactory=new SslRMIClientSocketFactory();
RMIServerSocketFactory rmiServerSockeyFactory=new SslRMIServerSocketFactory();

//create the remote object
try{
SI=new SumaImpl(0,rmiClientSocketFactory,rmiServerSockeyFactory);
}catch(java.rmi.RemoteException e)
{System.out.println(e.getMessage());}

//registration of SI object
try{
Naming.bind("rmi://localhost:1099/Adunare",SI);
}catch(java.rmi.AlreadyBoundException e)
{System.out.println(e.getMessage());
}catch(java.net.MalformedURLException e)
{System.out.println(e.getMessage());
}catch(java.rmi.RemoteException e)
{System.out.println(e.getMessage());}
}
}

Create a SAXSource with InputSource and XMLReader


One way to create a SAXSource is to use a SAX InputSource and an XMLReader object. The transformer, ContentHandler, calls the XMLReader.parse(InputSource IS) method. Here's an example:

...
try{
//get a SAXParserFactory instance
SAXParserFactory SAXpf=SAXParserFactory.newInstance();

//enabling the namespaces processing
if(SAXpf.isNamespaceAware()==false)
SAXpf.setNamespaceAware(true);

//get a SAXParser object
SAXParser SAXparser=SAXpf.newSAXParser();

//get the XMLReader
XMLr=SAXparser.getXMLReader();

}catch(javax.xml.parsers.ParserConfigurationException e)
{System.out.println(e.getMessage());
}catch(org.xml.sax.SAXException e)
{System.out.println(e.getMessage());}

//creating the SAXSource
Source sXML=new SAXSource(XMLr, new InputSource
("C://XSLT//test.xml"));

//or
//SAXSource sXML=new SAXSource(new InputSource
//("C://XSLT//test.xml"));
//sXML.setXMLReader(XMLr);
...

Create a New Event Using AWTEventMulticaster


This code shows how to create a new event using AWTEventMulticaster.

import java.awt.*;
import java .awt.event.*;

class Buton extends Component{
private Image button_pressed,button_released;
private boolean press=false;

ActionListener actionListener;

public Buton(){

button_pressed=Toolkit.getDefaultToolkit().getImage("?"); //pressed button
button_released=Toolkit.getDefaultToolkit().getImage("?"); //released button

MediaTracker mt = new MediaTracker(this);
mt.addImage(button_pressed,0);mt.addImage(button_released,1);
try {
mt.waitForAll();
} catch (InterruptedException e)
{System.out.println(e.getMessage()); }
enableEvents( AWTEvent.MOUSE_EVENT_MASK );
setSize( button_pressed.getWidth(null),button_pressed.getHeight(null) );
}

public Dimension getPreferredSize(){
return getSize();
}

public void paint(Graphics g){
if(press)g.drawImage(button_pressed,0,0, this);
if(!press)g.drawImage(button_released,0,0,this);
}

public void update(Graphics g){paint(g);}

public void processEvent(AWTEvent e){
if (e.getID()==MouseEvent.MOUSE_PRESSED){
press=true;repaint();
}
if (e.getID()==MouseEvent.MOUSE_RELEASED){
press=false;repaint();Event();
}
super.processEvent(e);
}

public void addActionListener(ActionListener l){
actionListener=AWTEventMulticaster.add(actionListener, l);
}
public void removeActionListener(ActionListener l){
actionListener=AWTEventMulticaster.remove(actionListener, l);
}
private void Event(){
if (actionListener!=null){
ActionEvent t=new ActionEvent(this,ActionEvent.ACTION_PERFORMED,"press");
actionListener.actionPerformed(t);
}
}
}

Create a Menu Bar with JavaFX


Here's a JavaFX example that creates a nice menu bar. All you need is a set of images named: home_1.bmp (unpressed), home_2.bmp (pressed), news_1.bmp, news_2.bmp,contact_1.bmp, contact_2.bmp, photos_1.bmp and photos_2.bmp:

import javafx.ui.*;
import javafx.ui.canvas.*;
import javafx.ui.filter.*;
import java.lang.System;

class NiceMenu extends CompositeNode{
attribute home: String;
attribute news: String;
attribute contact: String;
attribute photos: String;
}

attribute NiceMenu.home = ".//images//home_1.bmp";
attribute NiceMenu.news = ".//images//news_1.bmp";
attribute NiceMenu.contact = ".//images//contact_1.bmp";
attribute NiceMenu.photos = ".//images//photos_1.bmp";

function NiceMenu.composeNode() =

Group {
transform: []
content: [ImageView {
transform: translate(180,72)
image: Image { url: bind home }
onMouseEntered: operation(e:CanvasMouseEvent) {
home=".//images//home_2.bmp";
}
onMouseExited: operation(e:CanvasMouseEvent) {
home=".//images//home_1.bmp";
}
},
ImageView {
transform: translate(240,73)
image: Image { url: bind news }
onMouseEntered: operation(e:CanvasMouseEvent) {
news=".//images//news_2.bmp";
}
onMouseExited: operation(e:CanvasMouseEvent) {
news=".//images//news_1.bmp";
}
},
ImageView {
transform: translate(295,73)
image: Image { url: bind contact }
onMouseEntered: operation(e:CanvasMouseEvent) {
contact=".//images//contact_2.bmp";
}
onMouseExited: operation(e:CanvasMouseEvent) {
contact=".//images//contact_1.bmp";
}
},
ImageView {
transform: translate(473,73)
image: Image { url: bind photos }
onMouseEntered: operation(e:CanvasMouseEvent) {
photos=".//images//photos_2.bmp";
}
onMouseExited: operation(e:CanvasMouseEvent) {
photos=".//images//photos_1.bmp";
}
}]
};

//You can show the menu like this
Frame {
centerOnScreen: true
visible: true
height: 200
width: 1100
title: "Nice Menu"
onClose: operation() {System.exit(0);}
content: ScrollPane {
var color=Color{
red:64
green:64
blue:74
}
background: color
view: Canvas {
background: black
cursor: DEFAULT
content: NiceMenu
}
}
}

Create a JavaFX foreach Nested Loop


When you want to create a nested loop in JavaFX, use the foreach statement. Here's an example that displays a circle model:

import java.lang.*;
import javafx.ui.*;
import javafx.ui.canvas.*;

Frame {
centerOnScreen: true
visible: true
height: 500
width: 500
title: "Foreach demo..."
onClose: operation() {System.exit(0);}
content: ScrollPane {
background: white
view: Canvas {
content: bind foreach (i in [1..10], j in [1..10])
Circle {
cx: i*30
cy: j*30
radius:30
stroke:black
strokeWidth:1
}
}
}
}

Create a "Night" Filter Using RGBImageFilter


This following code shows you how to create the "night" effect for an image using the RGBImageFilter:

import java.awt.image.*;

public class NightFilter extends RGBImageFilter {

double frac;
//0.0<=g<=1.0
public NightFilter(double g) {
frac=g;
}

public int filterRGB(int x, int y, int rgb) {

if (frac<=0) return 0xFF000000;
if (frac>1.0) return 0xFF000000;

int red=rgb & 0x00FF0000;red>>>=16;
int green=rgb & 0x0000FF00;green>>>=8;
int blue=rgb & 0x0000FF;

int r=(int) (red*frac);
int g=(int) (green*frac);
int b=(int) (blue*frac);

return (0x000000FF<<24) | (r <<16) | (g << 8) | b;
}
}

Thursday, February 24, 2011

Create a "Current Date" Extension Element for Xalan


This tip is just a small application that creates an extension element for the Xalan processor. The name of the new element is <today> and it can be used to access the current date. After the application code, there's a small XSL stylesheet that uses this element.

//Java code
package xslt.extension.myelement;

import java.util.Calendar;

public class MyExtension{
public String today(org.apache.xalan.extensions.XSLProcessorContext XSLPC,
org.apache.xalan.templates.ElemExtensionCall EEC)
{
String[] luni={"January","February","March",
"April","May","June","July","August",
"September","October","November","December"};

Calendar C=Calendar.getInstance();
String luna=luni[C.get(Calendar.MONTH)];
String data=String.valueOf(C.get(Calendar.DATE));
String an=String.valueOf(C.get(Calendar.YEAR));

return (data+"."+luna+"."+an);
}
}

//XSL stylesheet
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:ext="xalan://xslt.extension.myelement.MyExtension"
extension-element-prefixes="ext">
<xsl:output method="html" version="4.01" encoding="ISO-8859-1"
indent="yes" media-type="text/html" />

<xsl:template match="/...">
<html>
<body bgcolor="#FFF2EC">
<font face="arial" size="2">
<b>Today:<ext:today></ext:today></i></b>
</font>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Create a Color Using "<<" and "|" Operators


This tip shows you how to create the RED color using the "<<" and "|" operators. After that, the color is used to fill a rectangle:

import java.awt.*;

class draw_red_rect extends Frame{

Color col=null;

public draw_red_rect()
{
super();
}

public void init()
{
setLayout(null);
setSize(100,100);

int A=255<<24;
int R=255<<16;
int G=0<<8;
int B=0<<0; //int B=0;

System.out.println("A="+A+",R="+R+",G="+G+",B="+B);

int RED=A | R | G | B;

col=new Color(RED);
System.out.println("RED="+RED+" // getRGB="+col.getRGB());
System.out.println("RED_BINAR=
"+Integer.toBinaryString(col.getRGB()));

setVisible(true); //show();
}

public void paint(Graphics g)
{
g.setColor(col);
g.fillRect(30,30,50,50);
}
}

public class red{
public static void main(String[] args){
draw_red_rect t=new draw_red_rect();
t.init();
}
}

Compatible Stylesheets with xsl:fallback


The following code is an example of how to use the xsl:fallback element to achieve full compatibility between XSLT different versions.
Imagine that some future 5.0 version of XSLT implements an element. Processors using earlier versions of XSLT wouldn't understand that element, so you can include an element to enable the processor to continue, using elements it understands from an earlier version of XSLT.

<xsl:stylesheet version="5.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

...
<xsl:for-each select="***XPath expression***" >
<xsl:condition test="***any condition***">
XSLT 5.0 - OK - XSLT 5.0
<xsl:fallback>
<xsl:if test="***any condition***">
XSLT 1.0 - OK - XSLT 1.0
</xsl:if>
</xsl:fallback>
</xsl:condition>
</xsl:for-each>
...

A processor using XSLT 1.0/2.0 will fail to recognize the <xsl:condition> element, but because it contains an <xsl:fallback> element the older processor will evaluate the <xsl:if> test in the <xsl:fallback> element instead of throwing an error.

Closing an SSLEngine Connection


This tip shows you how to correctly close a SSLEngine connection. Notice that this is not a simple process, like closing a simple socket!

SSLContext context ...;
SSLEngine engine ...;
ByteBuffer dummy ...;
ByteBuffer OutputNet ...;

engine.closeOutbound();
while(!engine.isOutboundDone())
{
dummy.flip();
OutputNet.clear();

result=engine.wrap(dummy,OutputNet);
status=result.getStatus();
System.out.println("Status:"+status);

if(status==SSLEngineResult.Status.BUFFER_OVERFLOW)
{
System.out.println("BUFFER_OVERFLOW");
OutputNet=ByteBuffer.allocate(SOutputNet.capacity()+100);
}

if(status==SSLEngineResult.Status.OK)
{
System.out.println("OK");
while(OutputNet.hasRemaining())
{
try{
int W=channel.write(OutputNet);
if(W==-1)
{
//the channel has been closed
}
if(W==0)
{
//nothing has been read
}
}catch(IOException e)
{
?
}
}
OutputNet.compact();
}
//BUFFER_UNDERFLOW, CLOSE
}
//closing the transport mechanism
channel.close();

Building Absolute/Relative URIs


This tip show you how to build absolute/relative URIs by using the java.net.URI methods.


Building an absolute URI:

try{
URI uri_absolute=new URI("http://www.java.sun.com/");
URI uri_relative=new URI("index.html");
URI uri_absolute_result=uri_absolute.resolve(uri_relative);
System.out.println(uri_absolute_result);
}catch(URISyntaxException e)
{System.out.println(e.getMessage());}

The result : http://www.java.sun.com/index.html


Building a relative URI:

try{
URI uri=new URI("/docs/imagini/mare/");
URI uri_relative=new URI("eforie/discoteca.jpg");
URI uri_relative_result=uri.resolve(uri_relative);
System.out.println(uri_relative_result);
}catch(URISyntaxException e)
{System.out.println(e.getMessage());}

The result : /docs/imagini/mare/eforie/discoteca.jpg


Getting a relative URI:

try{
URI uri_absolute_1=new URI("http://www.java.sun.com/index.html");
URI uri_absolute_2=new URI("http://www.java.sun.com/");
URI uri_relative_result=uri_absolute_2.relativize(uri_absolute_1);
System.out.println(uri_relative_result);
}catch(URISyntaxException e)
{System.out.println(e.getMessage());}

The result : index.html

Build a Frame with a ScrollPane in JavaFX


What follows is a simple frame designed with the JavaFX scripting language. The frame also has a ScrollPane component.

import javafx.ui.*;
import javafx.ui.canvas.*;
import javafx.ui.filter.*;
import java.lang.System;

Frame {
centerOnScreen: true
visible: true
height: 300
width: 300
title: "Window title"
onClose: operation() {System.exit(0);}
content: ScrollPane {
var color=Color{
red:64
green:64
blue:74
}
background: color
view: Canvas {
background: black
cursor: DEFAULT
}
}
}

Build a Custom Formatter for a Java.util.logging Logger


For a simple custom logger, you can inherit from the base java.util.logging.Formatter class and override its format method to customize the output. Here's an example:

import java.io.*;
import java.util.*;
import java.util.logging.*;

public class CustomFormatter extends java.util.logging.Formatter
{
public String format(LogRecord log)
{
Date date = new Date(log.getMillis());
String level = log.getLevel().getName();
String logmessage = "{"+level+"}" + "{"+date.toString()+"}\r\n";
logmessage = logmessage + log.getMessage() + "\r\n\r\n";

Throwable thrown = log.getThrown();
if (thrown != null) {
logmessage = logmessage + thrown.toString();
}
return logmessage;
}
}

Blocking Namespace Declarations in XSLT Transformation Results


Suppose you want to block a namespace declaration from appearing in your XSLT transformation results; for example, suppose you have the namespace declaration of a function/element extension. You'd have to use the exclude-result-prefixes attribute in the stylesheet element. The value of this attribute is a list of prefixes separated by spaces.
Here's an example:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mc="http://www.airwings.org/register/"
xmlns:informatii="http://www.airwings.org/info/"
xmlns:FR="myPrefix://just.for.fun/java.io.FileReader"
xmlns:BR="xalan://java.io.BufferedReader"
exclude-result-prefixes="FR BR">

In the above example, the myPrefix://just.for.fun/java.io.FileReader and xalan://java.io.BufferedReader declarations will not be copied.

Apply an Identical Transformation to a DOM Tree Using TrAX


To test your TrAX application without involving your live business processes, simply build an identical transformation. You can do this using the newTransformer() method—without any arguments. The following code is a full example that applies an identical transformation to a DOM tree:

//the XML file for this example is named book.xml

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;

class DOM{

DocumentBuilderFactory DBF=null;
DocumentBuilder DB=null;
Document D=null;
Document DR=null;
Transformer tXML=null;

public DOM(){}

public void identicalTransf(String XMLdoc)
{
try{
//create a DocumentBuilderFactory
DBF=DocumentBuilderFactory.newInstance();

//set namesapce aware
DBF.setNamespaceAware(true);

//create a DocumentBuilder
DB=DBF.newDocumentBuilder();

//get the DOM tree for your XML
D=DB.parse(new File(XMLdoc));

//create an empty document for storing the result
DR=DB.newDocument();

//get a TransformerFactory
TransformerFactory tfXML=TransformerFactory.newInstance();

//get a Transformer for identical transformation
try{
tXML=tfXML.newTransformer();
}catch(javax.xml.transform.TransformerConfigurationException e)
{System.out.println(e.getMessage());}

//define the Source
Source sXML=new DOMSource(D);

//define the Result
Result rXML=new DOMResult(DR);

//do the transformation
try{
tXML.transform(sXML,rXML);
}catch(javax.xml.transform.TransformerException e)
{System.out.println(e.getMessage());}

//verify the result
try{
tXML.transform(new DOMSource(DR),
new StreamResult(System.out));
}catch(javax.xml.transform.TransformerException e)
{System.out.println(e.getMessage());}

}catch(javax.xml.parsers.ParserConfigurationException e)
{System.out.println(e.getMessage());
}catch(org.xml.sax.SAXException e)
{System.out.println(e.getMessage());
}catch(java.io.IOException e)
{System.out.println(e.getMessage());}
}
}

public class IdenticalTransformation{
public static void main(String[] args)
{
DOM t=new DOM();
t.identicalTransf("C://Data_local//xml//docs//Carte.xml");
}
}

How to create an accordion panel with HTML/CSS


If you like the below menu:


Then copy-and-paste the below CSS code:

#rafa {
background-color: #cccc99;
}
#roger {
background-color:#cccc88;
}
#novak {
background-color: #cccc77;
}
#andy {
background-color:#cccc66;
}

body {
font: small/1.2 Verdana sans-serif;
}

#accordion {
width: 800px;
height: 400px;
margin: 50px auto;
}

#accordion div {
height:30%;
overflow: hidden;
}

#accordion:hover div {
height: 30px;
}

#accordion:hover div:hover {
height: 340px;
overflow: auto;
}

h1 {
font-size: 105%;
margin: 15px 15px .1em 20px;
}

p {
margin: 1em 25px;
}

img {
float: left;
padding: 3px 3px 3px 3px;
}

In addition, you can test it from HTML, like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>CSS DropDown Menu</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="menu.css" media="screen" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="accordion">
<div id="rafa">
<h1>Rafael Nadal</h1>
<p><img src="./images/rafa.jpg" width="100" height="100">Rafael
Nadal was born in Manacor, Majorca, Spain to Sebastian Nadal,
a businessman managing his own restaurant, Sa Punta...p>
</div>
<div id="roger">
<h1>Roger Federer</h1>
<p><img src="./images/roger.png" width="100" height="100">Roger
Federer (born 8 August 1981) is a Swiss professional tennis player who held
the ATP number one position for a record 237 consecutive weeks...</p>
</div>
<div id="novak">
<h1>Novak Djockovic</h1>
<p><img src="./images/novak.jpg" width="100" height="100">Novak
Djokovic born 22 May 1987) is a Serbian professional tennis player, who is
ranked World No. 3 by the Association of Tennis Professionals (ATP)....p>
</div>
<div id="andy">
<h1>Andy Murray</h1>
<p><img src="./images/andy.png" width="100" height="100">Andrew
"Andy" Murray (born 15 May 1987) is a Scottish professional tennis player
and current British No. 1... </p>
</div>
</div>
</body>
</html>

Tuesday, February 22, 2011

How to exploit Java.NIO for copying files in Java


Java NIO provide a powerful solution for copying files:

public void Copy_File(String from, String where) throws IOException {

FileChannel inChannel = new FileInputStream(from).getChannel();
FileChannel outChannel = new FileOutputStream(where).getChannel();

try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}

How to exploit buffers for copying files in Java


A classic approch of copying files in Java is based on buffers transfer. The below tip put this approch into a simple and compact method.

public void CopyFile(String from, String where) {

BufferedInputStream buff = null;
BufferedOutputStream buffout = null;

try {
buff = new BufferedInputStream(new FileInputStream(from));
buffout = new BufferedOutputStream(new FileOutputStream(where));

int b = 0;
byte[] bytes = new byte[1024];

while (b != -1) {
b = buff.read(bytes);
buffout.write(bytes);
}
System.out.println("File written !");
} catch (Exception e) {
System.out.println("File not written !");
} finally {
try {
buff.close();
buffout.flush();
buffout.close();
} catch (Exception e) {
}
}
}

Monday, February 21, 2011

A Proxy EJB - Servlet for AJAX GET and POST requests


The below class is an EJB that can resolve AJAX GET/POST requests. As you know, AJAX cannot directly access absolute URLs. But, AJAX can "forward" its request to a proxy component, as a servlet (the “gate” to EJB), and that component can access the final resource, instead of AJAX, and return the response to AJAX. The below EJB/Servlet solution accepts GET/POST requests.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;

@Stateless
@LocalBean
@DeclareRoles({"some_role_1", "some_role_2"})
public class AJAXGETPOSTBean {

@Resource
private SessionContext ctx;

/**
* Forward GET AJAX request
*/
@RolesAllowed({"some_role_1", "some_role_2"})
public int getAjaxRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception {

String line = "";
URL new_url = null;
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
OutputStream outputStream = null;
PrintWriter out = null;

String url = request.getParameter("url");

try {
if((ctx.isCallerInRole("some_role_1"))||(ctx.isCallerInRole("some_role_2"))){
if (url.indexOf("http") != -1) {
out = response.getWriter();

//sometimes you need to modify the request machine!
//after you add the new machine URL, you need to paste the rest of request
//you can use the substring method to identify the remaining URL that is
//pasted to the new machine
String local_url = "http://localhost:8080/" +
url.substring(url.indexOf("${paste_this}"));
url = local_url;

new_url = new URL(url);

httpURLConnection = (HttpURLConnection) (new_url.openConnection());
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod(request.getMethod());
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setUseCaches(false);

inputStream = request.getInputStream();
outputStream = httpURLConnection.getOutputStream();

final int length = 200;
byte[] bytes = new byte[length];
int bytesRead = 0;
while ((bytesRead = inputStream.read(bytes, 0, length)) > 0) {
outputStream.write(bytes, 0, bytesRead);
}

outputStream.flush();
outputStream.close();
inputStream.close();

response.setContentType(httpURLConnection.getContentType());

inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

while ((line = bufferedReader.readLine()) != null) {
out.println(line);
}

if (out != null) {
out.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
return 1;
}
}
return 0;

} catch (Exception e) {
if (out != null) {
out.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}

throw e;
} finally {
if (out != null) {
out.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}

/**
* Forward POST AJAX request
*/
@RolesAllowed("some_role_1")
public int postAjaxRequest(HttpServletRequest request,HttpServletResponse response)
throws Exception {

final int length = 1;
URL new_url = null;
String requestString = "";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
PrintWriter xmlOut = null;

String url = request.getParameter("url");

try {
//sometimes you need to modify the request machine!
//after you add the new machine URL, you need to paste the rest of request
//you can use the substring method to identify the remaining URL that is pasted
//to the new machine
String local_url = "http://localhost:8080/" +
url.substring(url.indexOf("${paste_this}"));
url = local_url;

if (ctx.isCallerInRole("some_role_1")) {
inputStream = request.getInputStream();

int bytesRead = 0;
byte[] bytes = new byte[length];
while ((bytesRead = inputStream.read(bytes, 0, length)) > 0) {
String value = new String(bytes);
requestString = requestString + value;
}

//if the machine appears in the request query also, you need to modify it
//accordingly
requestString.replace("original_ip:original_port",
"new_ip(localhost):new_port(8080)");

inputStream.close();

response.setContentType("application/xml");

new_url = new URL(url);
httpURLConnection = (HttpURLConnection) new_url.openConnection();
httpURLConnection.setAllowUserInteraction(false);

httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/xml");

httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);

String authHeader = request.getHeader("Authorization");
String username = request.getParameter("username");

if ((username != null) && !username.trim().equals("")) {
String password = request.getParameter("password");
String up = username + ":" + password;
byte[] encoded = Base64.encodeBase64(up.getBytes());
authHeader = "Basic " + new String(encoded);
}

if (authHeader != null) {
httpURLConnection.setRequestProperty("Authorization", authHeader);
}

xmlOut = new PrintWriter(httpURLConnection.getOutputStream());
xmlOut.write(requestString);
xmlOut.flush();
xmlOut.close();

if (httpURLConnection.getResponseCode() >= 400) {
return 0;
} else {
response.setContentType(httpURLConnection.getContentType());
response.setHeader("Content-disposition",
httpURLConnection.getHeaderField("Content-disposition"));

int chunk;
OutputStream output = response.getOutputStream();
InputStream input = httpURLConnection.getInputStream();

while ((chunk = input.read()) != -1) {
output.write(chunk);
}

input.close();
output.close();
}

if (inputStream != null) {
inputStream.close();
}
if (xmlOut != null) {
xmlOut.close();
}

return 1;
}
return 0;
} catch (Exception e) {
if (inputStream != null) {
inputStream.close();
}
if (xmlOut != null) {
xmlOut.close();
}
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (xmlOut != null) {
xmlOut.close();
}
}
}
}

Now, the servlet that take advantage of this EJB is:

import ejb_package_here;

import java.io.IOException;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "AJAXGETPOSTServlet", urlPatterns = {"/AJAXGETPOSTServlet"})
public class AJAXGETPOSTServlet extends HttpServlet {

@EJB
private AJAXGETPOSTBean ajaxBean;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ajaxBean.getAjaxRequest(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
//@RolesAllowed("memberRole")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ajaxBean.postAjaxRequest(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public String getServletInfo() {
return "Short description";
}
}