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.

Sunday, March 28, 2010

Associate a ServerSocket with a ServerSocketChannel in an NIO App


This tip shows you how to create a ServerSocketChannel, to which you'll then associate a standard ServerSocket:
//create the ServerSocketChannel
try{
serverNIO=ServerSocketChannel.open();
serverNIO.configureBlocking(false);
}catch(IOException e)
{System.out.println("\nError: " + e.getMessage());}
//indicate the host and the port
try{
InetAddress addr=InetAddress.getByName("localhost");
ISA=new InetSocketAddress(addr,port);
}catch(UnknownHostException e)
{System.out.println("\nError: " + e.getMessage());}
//connect a ServerSocket to a ServerSocketChannel
try{
ServerSocket SS=serverNIO.socket();
SS.bind(ISA);
System.out.println("- Ready -");
}catch(IOException e)
{System.out.println("\nError: " + e.getMessage());}

Bind converters to backing bean properties


The below recipe is just an example of what you can find in the JSF 2.0 Cookbook from Packt.


JSF standard converter tags allow binding attributes (this is also true for listener and validator tags). This means that developers can bind converter implementations to backing bean properties. The main advantages of using the binding facility are:

- developer can allow to the backing bean to instantiate the implementation.
- the backing bean can programmatically access the implementation’s attributes.

How to do it...

To successfully accomplish a binding task, you can follow three simple steps (these steps are true for converter, listener and validator tags):

1. Nest the converter (listener, validator) tag in the component tag.
2. Put in the backing bean a property that take and return the converter (listener, validator) implementation class.
3. Reference the backing bean property using a value expression from the binding attribute of the converter (listener, validator) tag. Per example, let’s bind the standard convertNumber converter to a backing bean property. The idea is to let the backing bean to set the formatting pattern of the user's input. First, you have to register the converter onto the component by nesting the convertNumber tag within the component tag. Then, you have to reference the property with the binding attribute of the convertNumber tag.
<h:form id="numberFormID">
<h:inputText id="numberID" value="#{numbersBean.numbery}">
<f:convertNumber binding="#{numbersBean.number}" />
</h:inputText>
<h:message showSummary="true" showDetail="false" for="numberID"
style="color: red; text-decoration:overline"/>
<br />
<h:commandButton value="Submit" action="selected?faces-redirect=true"/>
</h:form>
The number property would look something like this:
package numbers;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.convert.NumberConverter;

@ManagedBean
@SessionScoped
public class NumbersBean {

private NumberConverter number;
private float numbery;

public float getNumbery(){
return this.numbery;
}

public void setNumbery(float numbery){
this.numbery=numbery;
}

public NumberConverter getNumber(){
return this.number;
}

public void setNumber(NumberConverter number){
number.setType("currency");
number.setCurrencySymbol("$");
this.number=number;
}
}
How it works...
In our example, the backing bean sets the formatting pattern within the convertNumber tag, which means that the user’s input will be constrained to this pattern. This time the numbers are formatted as currencies, without using specific attributes in convertNumber tag. Instead of this we use the binding attribute to reference the number property, which is a NumberConverter instance, offering us access to this class methods.

The above recipe is just an example of what you can find in the JSF 2.0 Cookbook from Packt.

Create a "Flea" Filter Using the RGBImageFilter Class


This tip demonstrates how to build a "flea" filter based on the RGBImageFilter class. The filtered picture will look like the image displayed on old TVs.
import java.awt.image.*;
import java.util.*;
import java.awt.*;

public class FleaFilter extends RGBImageFilter
{

ColorModel cm=ColorModel.getRGBdefault();

public FleaFilter()
{
canFilterIndexColorModel=true;
}

public int filterRGB(int x, int y, int rgb)
{
Random Rred=new Random();
Random Rgreen=new Random();
Random Rblue=new Random();
Color backup=new Color(Rred.nextInt(255),
Rgreen.nextInt(255),Rblue.nextInt(255));
return rgb|backup.getRGB();
}
}

Validating an XML Document


The following code shows you how to use the DOMImplementationLS and DOMConfiguration classes to validate an XML document only when an XML Schema is present:
DOMImplementationLS DOMiLS=null;

//get a LSParser
LSParser LSP=DOMiLS.createLSParser(
DOMImplementationLS.MODE_SYNCHRONOUS,
"http://www.w3.org/2001/XMLSchema");

//get a DOMConfiguration
DOMConfiguration DOMc=LSP.getDomConfig();

//validating
if(DOMc.canSetParameter("schema-type","http://www.w3.org/2001/XMLSchema"))
DOMc.setParameter("schema-type","http://www.w3.org/2001/XMLSchema");
else System.out.println("Error...");

//use validate-if-schema
if(DOMc.canSetParameter("validate-if-schema",true))
DOMc.setParameter("validate-if-schema",true);
else System.out.println("Error...");

Determine Prime Numbers with XQuery


Did you know you can determine if a number is prime by calling an XQuery query? Here's the code:
<prime_numbers>
{
for $a in (1 to 50)
return(
if(not(some $counter in (2 to ($a - 1)) satisfies $a mod
$contor=0)) then {$a}
else {$a}
)
}
</prime_numbers>

And here's a fragment of the result:

<prime_numbers>
<prime>1</prime>
<prime>2</prime>
<prime>3</prime>
<not_prime>4</not_prime>
<prime>5</prime>
<not_prime>6</not_prime>
<prime>7</prime>
<not_prime>8</not_prime>
...

Insert an XML Schema into an XQuery Query

Use the following code to insert an XML Schema into an XQuery query. The following code assumes that the XML Schema is:
file:///C://Data_Local//xml//docs//AirWings_xslt_xmlschema.xsd
and the XML file is:
file:///C://Data_Local//xml//docs//AirWings_xpath_xslt.xml
Import the schema default element namespace "" at:
file:///C://Data_Local//xml//docs//AirWings_xslt_xmlschema.xsd
Here's the code:
declare variable $xml as schema-element(xml_root_element) := 
doc(file:///C://Data_Local//xml//docs//AirWings_xpath_xslt.xml)/*;
for $a in $xml/available-aircrafts
return $a/aircraft

Friday, March 26, 2010

Passivation/Activation of a Stateful Bean in EJB 3.0


As you know, the EJB container offers strong support for "save/load" the state of a stateful bean. The problem arises when you have to deal with nonserializable objects like open sockets, JDBC connections, etc. In these cases, the containter needs a little help. You can provide this by implementing two callback methods, as follows:

//passivation callback method for EJB 3.0
@Stateful
public class any_bean_name{
@PrePassivate
public void passivate(){
//here close JDBC connections, socket connections, ...
//...
}
...
}

//activation callback method for EJB 3.0
@Stateful
public class any_bean_name{
@PostActivate
public void activate(){
//here open JDBC connections, socket connections, ...
//...
}
...
}

Thursday, March 25, 2010

What Image Formats Does Your Java Application Support?


Use this application to determine what image formats you can load and save in J2SE.

import javax.imageio.*;

class picture{

public picture(){}

void RWF()
{
//read image formats
System.out.println("R-IF:");
String[] readFormats=ImageIO.getReaderFormatNames();
for(int i=0;i<readFormats.length;i++)
System.out.println(readFormats[i]);

//write image formats
System.out.println("W-IF:");
String[] writeFormats=ImageIO.getWriterFormatNames();
for(int i=0;i<writeFormats.length;i++)
System.out.println(writeFormats[i]);
}
}

public class ReadWriteFormats{
public static void main(String[] args)
{
picture t=new picture();
t.RWF();
}
}

Using the FOP-to-AWT Viewer


When you want to use the FOP-to-AWT Viewer from a Java application, you can use the ExampleAWTViewer.java. This application is available in the \fop-0.20.5\examples\embedding\java\embedding directory. Using this class, you don't have to develop the application from scratch. Just copy the application, rename it, and make the following replacements:

//code to be replaced
...
//Setup directories
File baseDir = new File(".");
...
//Setup input and output files
File fofile=new File(baseDir, "xml/fo/helloworld.fo");
...

//code for replacement
...
//Setup directories
File baseDir = new File("YOUR_DIRECTORY");
...
//Setup input and output files
File fofile=new File(baseDir, "YOUR FO FILE");
...

Determine Your Network Interfaces and IP Names


Use this to determine the names of your network interfaces and IPs. Of course, it can be used only for machines that have more than one network interface.

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

public class NetInterfaces{
public static void main(String argv[]) throws Exception {

Enumeration enumInterfaces=NetworkInterface.getNetworkInterfaces();
while(enumInterfaces.hasMoreElements())
{
NetworkInterface net=(NetworkInterface)enumInterfaces.nextElement();
System.out.println("NetworkInterface name: "+net.getDisplayName());
Enumeration enumIP=net.getInetAddresses();
while(enumIP.hasMoreElements())
{
InetAddress ip=(InetAddress)enumIP.nextElement();
System.out.println("IP address:"+ip);
}
}
}
}

How to Use Oracle Java XQuery API


This code outlines the main steps involved in using the Oracle Java XQuery API (OJXQI). If you are familiar with the DataDirectXQuery - XQuery for Java (DDXQ-XQJ), you may notice a some similarities.

XQueryContext XQC=new XQueryContext();

try
{
//the XQuery query is in a file called Q.xquery
//the XML file must be specified into the
//Q.xquery by the fn:doc XPath function - of course
//if you are using an XML Reader R=new FileReader("Q.xquery");

//"prepare" the query
PreparedXQuery PXQ=XQC.prepareXQuery(R);

//getting the results
XQueryResultSet XQRS=PXQ.executeQuery();
while(XQRS.next())
{
XMLNode node=XQRS.getNode();
node.print(System.out);
}
}
catch (Exception e)
{

}

Wednesday, March 24, 2010

A Proxy Servlet for AJAX GET requests


The below class is an usual Java Servlet that can resolve AJAX GET requests. As you know, AJAX cannot directly access absolute URLs. But, AJAX can "forward" its request to a proxy component, as a servlet, and that component can access the final resource, instead of AJAX, and return the response to AJAX. The below Servlet accepts only GET requests.

package com.extensions;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AjaxProxyServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

final Log log = LogFactory.getLog(AjaxProxyServlet.class);

String line = "";
URL new_url = null;
HttpURLConnection httpURLConnection = null;
HttpsURLConnection httpsURLConnection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;

log.debug("An foreign domain call from AJAX...");

response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);

PrintWriter out = response.getWriter();

String url = request.getParameter("url");
System.out.println("URL=" + url);
//using this script behind a proxy server
//InetAddress inetAddress=InetAddress.getByName("put the proxy name here");
//e.g. www.proxy.com
//InetSocketAddress inetSocketAddress=new InetSocketAddress(inetAddress, port);
//port is an integer (e.g. 8080)
//java.net.Proxy proxy=new java.net.Proxy(java.net.Proxy.Type.HTTP,inetSocketAddress);
try {
if (url.indexOf("https") != -1) {
log.info("Resolving your HTTPS connection...");

new_url = new URL(url);

if (url != null) {
httpsURLConnection = (HttpsURLConnection) (new_url.openConnection());

//or, if you are behind a proxy server
//httpsURLConnection=(HttpsURLConnection)(new_url.openConnection(proxy));
} else {
log.error("Unable to create the URL...");
}

if (httpsURLConnection != null) {
inputStream = httpsURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

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

try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
log.error("Unable to close the beffered stream ...");
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
log.error("Unable to close the beffered stream ...");
}

} else {
log.error("Unable to create the HTTPS connection with the required server...");
}

} else if (url.indexOf("http") != -1) {

log.info("Resolving your HTTP connection...");

new_url = new URL(url);

if (url != null) {
httpURLConnection = (HttpURLConnection) (new_url.openConnection());

//or, if you are behind a proxy server
//httpURLConnection=(HttpURLConnection)(new_url.openConnection(proxy));
} else {
log.error("Unable to create the URL...");
}

if (httpURLConnection != null) {
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

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

try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
log.error("Unable to close the beffered stream ...");
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
log.error("Unable to close the beffered stream ...");
}

} else {
log.error("Unable to create the HTTP connection with the required server...");
}

} else {
log.error("The used protocol is not supported ...");
}

} catch (Exception e) {
log.error("Can't access this URL... please, provide another path...");
} finally {
if (out != null) {
out.close();
}
}

}

/** Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
}

Batch Processing in Hibernate


Suppose you need to insert 200,000 records into a database in Hibernate. You'll need to adjust the following settings:

//set the JDBC batch size (it is fine somewhere between 20-50)
hibernate.jdbc.batch_size 30

//disable second-lavel cache
hibernate.cache.use_second_level_cache false

//and now do your job like this
Session S=SF.openSession(); //SF = SessionFactory object
Transaction T=S.beginTransaction();

for (int i=0;i<200000;i++)
{
record r=new record(...);
S.save(record);
if(i % 30==0)
{
//30, same as the JDBC batch size
//flush a batch and release memory
session.flush();
session.clear();
}
}
//clean
T.commit();
S.close();

Inject an EJB 3.0 into the init() Method of a Servlet


This tip shows you how to inject an EJB 3.0 into the init() method of a servlet:

//place all the required imports here
import package.to.EJB.interface.myInterface;

public class EJB30Servlet extends HttpServlet {

@EJB
myInterface myobj;

public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
//get the inital context
Context ctx = new InitialContext();

myobj=(myInterface) ctx.lookup(myInterface.class.getName());
} catch (Exception e) { e.printStackTrace(); }
}
Now you can call the EJB methods through the myobj object!

Validate an XML Document Only When a DTD Exists


See how to use the DOMImplementationDS and DOMConfiguration classes to validate an XML document only when a DTD document can be found:

DOMImplementationLS DOMiLS=null;

//get a LSParser object
LSParser LSP=DOMiLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,
"http://www.w3.org/TR/REC-xml");
//get a DOMConfiguration object
DOMConfiguration DOMc=LSP.getDomConfig();

//use validate-if-schema option
if(DOMc.canSetParameter("validate-if-schema",true))
DOMc.setParameter("validate-if-schema",true);
else System.out.println("Error...");

Using the <idbag> Element in Hibernate


Hibernate's <idbag> facility allows you to map many-to-many associations and collections of values to a single table with a surrogate key. The following code shows an example of mapping:

<idbag name="cars" table="CARS">
<collection-id column="car_id" type="long">
<generator class="sequence"/>
</collection-id>
<key column="car_I"/>
<many-to-many column="car_II" class="Car" outer-join="true"/>
</idbag>

Declare the Coolest XQuery Variables


Here's how to declare some important variables in XQuery:

Use this variable to pass an XML tree to a XQuery query.
declare variable $v as document-node(element(*,xdt:untyped)) external;:
These declare an XQuery variable into a namespace.
declare namespace nameSpace="http://nameSpace.org";
declare variable $nameSpace:v as xs:decimal:= 0.19;
This declares an XQuery variable that acts as an XML node.
declare variable $v as node() := ...:
Declares an XQuery variable that acts as an XML attribute.
declare variable $v as attribute() := ...: 
Declares an XQuery variable that acts as a XML element.
declare variable $v as element() := ...: 

Destroy a Java Logger using the contextDestroyed Method


I have used this code in a real web application and it works perfect:

public void contextDestroyed(ServletContextEvent e) {

//get the servlet context
ServletContext servletContext = e.getServletContext();

//get the real path
String root = servletContext.getRealPath("/");

//get all handlers
Handler[] handlers = logger.getHandlers();

//remove all handlers
for(int i = 0; i < handlers.length; i++)
{
logger.removeHandler(handlers[i]);
handlers[i].close();
}

//delele all the files related to the logging process
File logFiles = new File(root+"WEB-INF//logs//");
String[] fileNames = logFiles.list();

for(int i = 0; i < fileNames.length; i++)
{
File currentFile=new File(root+"WEB-INF//logs//"+fileNames[i]);
currentFile.delete();
}

//reset the logger
logger = null;
}

Monday, March 22, 2010

Look Up a Bean Interface in EJB 3.0


In principle, in EJB 3.0, you can access a bean from another bean by looking it up in the interface (local or remote). Here are two solutions for doing that:

1. Through the JNDI, you still have the portability:

//get the default JNDI initial context
Context ctx=new InitialContext();
//get the bussiness interface
Object obj=ctx.lookup(BusinessInterface.class.getName());
//convert obj
BusinessInterface bi=(BusinessInterface)obj;

Through the @EJB annotiation:
@EJB BusinessInterface bi; //cooool !

Convert "Little-Endian" to "Big-Endian"


This tip outlines two simple methods that help you to convert a number from the "little-endian" format to the "big-endian" format:

// 2-byte number
int SHORT_little_endian_TO_big_endian(int i)
{
return ((i>>8)&0xff)+((i << 8)&0xff00);
}

// 4-byte number
int INT_little_endian_TO_big_endian(int i)
{
return((i&0xff)<<24)+((i&0xff00)<<8)+((i&0xff0000)>>8)+((i>>24)&0xff);
}

Traverse All the Nodes of a DOM Tree


This is just a litle method that illustrates how to get the minimum of information from all nodes of a DOM tree. The key of this method is the "old-school" recursive style:

private void traverseAllNodes(Node node)
{
if(node.hasChildNodes())
{
NodeList NL=node.getChildNodes();
for(int i=0;i<NL.getLength();i++)
{
Node childnode=NL.item(i);

System.out.print("Name:"+childnode.getNodeName());
System.out.print("Value:"+childnode.getNodeValue()+"\n");

traverseAllNodes(childnode);
}
}
}

Sunday, March 21, 2010

Use an XMLReporter for Report Customizable Errors in StAX Applications


To customize error reports in StAX applications (except fatal errors), you can configure an XMLReporter like this:

XMLInputFactory XMLif=null;

//get an XMLInputFactory object
XMLif=XMLInputFactory.newInstance();

//setting an XMLReporter
XMLif.setXMLReporter(new XMLReporter() {
public void report(String message, String error_type, Object info, Location location)
{
System.err.println("L: "+location.getLineNumber()+",
C: "+location.getColumnNumber());
System.err.println(message);
}
});
...

Convert a java.util.Date Object to a java.sql.Date Object


The following code demonstrates how to convert a java.util.Date object to a java.sql.Date object:

import java.sql.*;
import java.util.*;

public class cs{
public static void main(String[] args)
{
GregorianCalendar date_1=(GregorianCalendar)Calendar.getInstance();
System.out.println(date_1.getTime());
java.sql.Date date_2= new java.sql.Date((date_1.getTime()).getTime());
System.out.println(date_2);
}
}

Does Your RDBMS Support Savepoints?


Before using savepoints in your application, you need to be sure that your RDBMS supports this facility. To do this, call the DatabaseMetaData.supportsSavepoints method, like this (this tip applies to JDBC 3.0 and higher drivers):

Connection conn=null;
DatabaseMetaData dmd=null;
...
try{
dmd=conn.getMetaData();
if(dmd.supportsSavepoints())
System.out.println(TRUE);
else
System.out.println(FALSE);
}catch(SQLException e)
{System.out.println(e.getMessage());}
...

Find the C.M.M.D.C of an array of integers


The below method gets an array of integers and returns its C.M.M.D.C:

public int cmmdc(int[] x) {

int rest = 0;
int flag = 0;
int minim = x[0];

for (int i = 0; i < x.length; i++) {
if (x[i] < minim) {
minim = x[i];
}
}

int aux = 1;
for (int i = 2; i < minim; i++) {
flag = 0;
for (int j = 0; j < x.length; j++) {
rest = x[j] % i;
if (rest != 0) {
flag = 1;
break;
}
}
if (flag == 0) {
aux = i;
}
}
return aux;
}

Using the unparsed-entity-uri XSLT Function


This tip shows how to insert an image into the result-tree of an XSLT transformation using the unparsed-entity-uri function.Suppose you have this element:
<sigla SF="SiglaFirma"/>
And an unparsed entity such as a bitmap:
<!ENTITY SiglaFirma SYSTEM "sigla.bmp" NDATA bmp>
You can "load" sigla.bmp into a XSLT result tree like this:
<img src="{unparsed-entity-uri('SiglaFirma')}" />

Solving Eclipse (Ganymede) and PermGem Out-of-Memory Errors


First, launch Eclipse with increased memory options, which you can do as follows (increase
these values as needed, but don't exceed your available memory):


eclipse.exe -vmargs -Xmx512M -XX:MaxPermSize=256M

Sometimes, the preceding solution has a limited effect, and the errors don't go away.
In that case, try starting Eclipse from ECLIPSE_HOME by double-clicking on the
eclipsec.exe application rather than the main executable.

Saturday, March 20, 2010

Calling a SOCKS Proxy Server from Java


This tip shows you how to call a SOCKS proxy server from Java code using the Socket class:

SocketAddress addr=new InetSocketAddress(socks_server_proxy, socks_port);
Proxy proxy=new Proxy(Proxy.Type.SOCKS,addr);
Socket socket=new Socket(proxy);
InetSocketAddress final_addr=new InetSocketAddress(final_server, final_port);
socket.connect(final_addr);

Friday, March 19, 2010

Setting Logger Output with FOP


The following code demonstrates how to set a logger for FOP. You can send the logger's messages to the System.out or in a file like this:

//to System.out
Logger logger=new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
fop.setLogger(logger);
MessageHandler.setOutputMethod(MessageHandler.SCREEN);
MessageHandler.setScreenLogger(logger);

//to a file (the log.txt file)
MessageHandler.setOutputMethod(MessageHandler.FILE);
MessageHandler.setLogfileName("log.txt",true);

Force Attribute Value Inheritance in XSL-FO


To force an XSL-FO attribute to inherit the value of another attribute, use the inherited-property-value:

<fo:block color="blue">
Hello
<fo:block color="yellow" background-color="inherited-property-value(color)">
to you!!!
</fo:block>
</fo:block>

Writing a Parameterized SQL Query in EJB 3.0


Follow this DELETE statement example to write parameterized SQL queries in EJB 3.0.:

protected EntityManager manager;
...
String ejbqlDelete = "delete from ClientTicket p where " +
"p.closed = :paramClosed and " +
"p.department = :paramDepartment and " +
"p.ticketUserID = :paramTicketUserID and " +
"p.ticketName = :paramTicketName";

int deletedEntities = manager.createQuery(ejbqlDelete).
setParameter("paramClosed", Boolean.TRUE).
setParameter( "paramDepartment", adminid).
setParameter( "paramTicketUserID", userID ).
setParameter( "paramTicketName", delTicket ).
executeUpdate();

Manipulate the Components of a JNDI Composite Name


This following code shows you how to list, add, and remove components from a JNDI composite name (javax.naming.CompositeName):

import javax.naming.*;

class jndiCompositeName{

public static void compositeComponents(CompositeName cn)
{
for(int i=0;i<cn.size();i++)
System.out.println(cn.get(i));
}

public static void main(String[] args){
try {
CompositeName composite = new
CompositeName("cn=Anghel Leonard/ o=cv.txt");

//list all components
System.out.println("All components before any operation:");
compositeComponents(composite);

//add a new component
System.out.println("All components after
adding a new component:");
composite.add(2, "site=mysite.com");
compositeComponents(composite);

//remove a new component
System.out.println("All components after
removing a component:");
composite.remove(1);
compositeComponents(composite);

}catch (NamingException e)
{System.out.println(e.getMessage());}
}
}

Maximum of a matrix


The below method returns the maximum of a matrix of integers:

public int MatrixMaxValue(int[][] x, int n, int m) {

int i = 0;
int j = 0;
int maxim = x[0][0];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (maxim < x[i][j]) {
maxim = x[i][j];
}
}
}
return maxim;
}

Thursday, March 18, 2010

Sort a matrix exacly as sorting an array


The below method sorts a matrix of integers exactly as sorting an array. You must pass to it the un-sorted matrix(x), the number of lines(n) and the number of columns(m). The method returns the sorted matrix.

public int[][] sortMatrix(int[][] x, int n, int m) {

int i = 0;
int j = 0;
int p = 0;
int t = 0;
int aux = 0;

for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
for (p = 0; p < n; p++) {
for (t = 0; t < m; t++) {
if (x[i][j] < x[p][t]) {
aux = x[i][j];
x[i][j] = x[p][t];
x[p][t] = aux;
}
}
}
}
}
return x;
}

Load an Image Using the JAI API


This tip shows you how to use the JAI API to load an image named myimage.jpg in just three lines of code:

ParameterBlock parameterBlock=new ParameterBlock();
parameterBlock.add("myimage.jpg");
myimage=JAI.create("fileload",parameterBlock);
...

Authenticate to a Proxy Server


To provide a user's password to a proxy server, use the following code:

URLConnection URLcon=null;
URLcon = url.openConnection();
byte[] x="name:password".getBytes();
//coding in Base64
String s = new sun.misc.BASE64Encoder().encode(x);
URLcon.setRequestProperty( "Proxy-Authorization",s);

Copy a matrix of integers into an array


The below method copies an matrix of integers into an array of integers. You must pass to the method: the matrix (y), the number of lines(n) and columns(m) to be copied. The method returns the desired array.

public int[] copyMatrixIntoArray(int[][] y, int n, int m) {

int[] x = new int[n * m];

int i = 0;
int j = 0;
int p = 0;

for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
x[p] = y[i][j];
p = p + 1;
}
}
return x;
}

Verify if an array has mount aspect


The below method checks if an array of integers has a mount aspect (per example, an array containing the elements 2 3 4 5 6 4 3 is a mount with has the peak at 6). It returns true if the array has a mount aspect.

public boolean isMountArray(int[] x) {

int i = 0;
int flag = 0;
for (i = 0; i < x.length - 1; i++) {
if (x[i] > x[i + 1]) {
flag = 1;
break;
}
}

if (flag == 1) {
for (int j = i; j < x.length - 1; j++) {
if (x[j] < x[j + 1]) {
flag = 2;
break;
}
}
}
if (flag == 0) {
flag = 2;
return false;
}
if (flag != 2) {
return true;
}
return false;
}

Wednesday, March 17, 2010

Call a Java Method from XQuery


This tip shows you how to develop XQuery queries that may call any other method. The method called in this tip is java.lang.Math.random:

declare namespace m="java:java.lang.Math";

let $r:=m:random()
return $r

Load a default picture when the original is not found


By default, when a web application cannot load an image it displays an ugly rectangle with a "X" in it. You can fix this by using the onerror JavaScript event. Like this, you can find out when an image is not loaded, and you can try to load another one instead. Per example, I have the following situation: on a web site you can load a picture as your avatar, but this is optional, which means that you can skip selecting an avatar - in this case a default picture should be displayed. You can choose between the user avatar or the default picture in the <img> tag, like this:

<img src="./resources/scripts/web/avatars"+email+"
onerror="this.onerror=null;
this.src='./resources/scripts/web/avatars/noavatar.jpg';"
width="50" height="50">

Note The email variable identifies the user avatar by its e-mail.

Verify if a number is palindrome


The below method checks if the passed number is palidrome or not. If the number is palindrome (of type 12344321) then it returns true.

public boolean palindrome(int number) {

int split = 1;
int aux = 0;
int split1 = number;
int split2 = number;
int copyOfnumber = number;

while (split > 0) {
split = number / 10;
number = split;
aux = aux + 1;
}

int counting = 1;
int aux1 = 1;
int aux2 = aux;
int flag = 0;
while (counting <= aux / 2) {
int nr1 = 1;
int nr2 = 1;
split1 = copyOfnumber;
for (int j = 1; j <= aux1; j++) {
nr1 = split1 % 10;
split1 = split1 / 10;
}
aux1 = aux1 + 1;
split2 = copyOfnumber;
for (int j = 1; j <= aux2; j++) {
nr2 = split2 % 10;
split2 = split2 / 10;
}
if (nr1 != nr2) {
flag = 1;
break;
}
aux2 = aux2 - 1;
counting = counting + 1;
}
if (flag == 1) {
return false;
}
if (flag == 0) {
return true;
}
return false;
}

Tuesday, March 16, 2010

Create a "Fog" Filter Using the RGBImageFilter Class


This following code shows you how to create a "fog" filter for an image using the RGBImageFilter class:

import java.awt.image.*;
import java.awt.*;
public class FogFilter extends RGBImageFilter
{
int fogg;

//0<=t<=255
public FogFilter(int t) {
canFilterIndexColorModel=true;
fogg=t;
}

public int filterRGB(int x, int y, int rgb) {
int red=ColorModel.getRGBdefault().getRed(rgb);
int green=ColorModel.getRGBdefault().getGreen(rgb);
int blue=ColorModel.getRGBdefault().getBlue(rgb);

Color col=new Color(red,green,blue,fogg);
return col.getRGB();
}
}

Monday, March 15, 2010

Sort a java.util.Vector of doubles


This method shows you how to sort a Vector of doubles:
  
public Vector ordonare(Vector x) {

double auxi = 0;
double auxj = 0;

for (int j = 0; j <= x.size(); j++) {
for (int i = j + 1; i <= x.size() - 1; i++) {
auxi = ((Double) x.get(i)).doubleValue();
auxj = ((Double) x.get(j)).doubleValue();
if (auxi > auxj) {
x.remove(i);
x.add(i, auxj);
x.remove(j);
x.add(j, auxi);
}
}
}
return x;
}

Build an Entity Resolver to Redirect a SAX Parser


This tip shows you how to bulid an entity resolver to "change" a public indentifier into a system identifier. The idea is to override the resolveEntity method of the EntityResolver interface:
public InputSource resolveEntity(String id_public,String id_system)
{
if (id_public.equals("-//W3C//DTD XHTML 1.0 Transitional//EN"))
return(new InputSource("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));

return null;
}