miercuri, 2 septembrie 2009

Richfaces and JQuery

Richface is a JSF based framework which offers a large collection of "ajax-enabled" components. These components use prototype javascript library. This is the main reason you have to be really careful when you want to use JQuery. I needed JQuery to create a photo gallery and combine it with dataScroller component. I was really surprised when I saw that dataScroller component was not working(page links were raising a javascript error). After I had searched for the cause of the issue and I had read the official guide from Exadel/RedHat I found out that JQuery must be imported using the following syntax:


<a4j:loadScript src="resource://jquery.js" />

In javascript functions you cand use jQuery(...) function instead of $(...). This solution make both javascript libraries, JQuery and prototype, work together.

luni, 24 august 2009

Python SQLAlchemy ORM

A couple of days ago I implemented some Python classes which were supposed to map tables from an Oracle DB. In Java, we can use Hibernate for achieving this. In Python, I chose to use SQLAlchemy framework. In the beginning, I had found the syntax a little confusing but after I understood it everything went smoothly. In the following paragraphs, I'll show how a one-to-may relation can be implemented and also how to use composite keys in SQLAlchemy.
I assume that classes are implemented in da package.

1. In __init__.py file I instantiate sqlalchemy dependency objects.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

BaseEntity = declarative_base()
strDbURL = "oracle://db_tes:xxx@xe"
objDbEngine = create_engine(strDbURL, echo=False)

Session = sessionmaker(bind=objDbEngine)
Session.configure(bind=objDbEngine)

def getConnection():
return Session()

In this moment, we can start implementing the entities. Every entity can extend BaseEntity. Every time we need a database connection we use getConnection() method. A SQLAlchemy session is similar to a Hibernate session.

2. I define User class which has a composite chei(username and password ---- don't do this in practice: you can safely choose to use serial number as primary key). In this example, I want to show how composite keys are implemented.

from da import BaseEntity
from sqlalchemy import Column,Integer,String,Numeric,DateTime,ForeignKey,Sequence
from sqlalchemy.orm import relation, backref

class User(BaseEntity):
username = Column("username", String, primary_key=True)
password = Column("password", String, primary_key=True)
descriere = Column("descriere", String)

def __init__(self, strUsername, strPassword, strDesc):
self.username = strUsername
self.password = strPassword
self.descriere = strDesc

3. I implement the Address class.

from da import BaseEntity
from sqlalchemy import Column,Integer,String,Numeric,DateTime,ForeignKey,Sequence
from sqlalchemy.orm import relation, backref

class Adress(BaseEntity):
id = Column("id", Integer, Sequence("seq_xxx_id"), primary_key=True)
fk_username = Column("fk_username", String, ForeignKey("utilizatori.username"))
fk_password = Column("fk_password", String, ForeignKey("utilizatori.password"))
street = Column("street", String)
number = Column("number", String)

user = relation("User",
foreign_keys=[fk_username, fk_password],
primaryjoin="User.username == Address.fk_username and "
"User.password == Address.fk_password",
backref="adresses")

def __init__(self, strUser, strPasswd, strStreet, strNumber):
self.fk_username = strUser
self.fk_password = strPassword
self.street = strStreet
self.number = strNumber

Comments: in this example, I try to show the power and flexibility provided by SQLAlchemy. First of all, in every SQLAlchemy entity we'll define the mapped table structure to attributes of the class. Using relation function, we can implement links(foreign keys) to other entities:
  • one-to-one relation
  • one-to-many relation
  • many-to-many relation
We can also use the backref keyword argument to indicate that we want a reference at the other end of relation.

4. After we implemented all the entities, we have to use them. In the folloing example, I show several lines of code that prove the entities functionality:

import da
from da import User, Address

# I select all user from the database
objSes = da.getConnection()
for objUsr, in objSes.query(User).all():
print(objUsr.addresses)

# filter that returns the user with a specific address
for objUsr in objSes.query(User, Address).filter(User.username == Address.fk_username and User.password == Address.fk_password).filter(Address.id == 1).all():
print(objUsr.username)

In conclusion, SQLAlchemy easily maps relational logic to object logic(the scope of any ORM) but it doesn't require a configuration file or annotations(like Hibernate). In addition, writting a query is extremely easy. What was not covered in this tutorial but it is intuitive is entity saving(persist). We use add method of an opened session for adding and updating an entity.

luni, 10 august 2009

Java si Mocking - PowerMock

In previous posts I talked about testing python code through injected dependencies. The same idea can be achieved in Java even if it's a little trickier. After I had studied a couple of mocking libraries for java I decided to use PowerMock because it is very close to mocker library for python. This library improves EasyMock and in the latest release it supports integration with Mockito. It worth mentioning some unique features of this library:
  • mocking static functions/methods
  • mocking private functions/methods
These features are extremely important but hard to implement in other testing frameworks. For a better understanding of PowerMock I present a small example.

class Calculator {
public static int add(int a1, int a2) {
return a1 + a2;
}
}

class Operatii {
public int operatieComplexa(int a1, a2) {
int a = Calculator.add(a1, a2);
return ++a;
}
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calculator.class})
class TestOperatii {
@Test
public void testOperatieComplexa() {
PowerMock.mockStatic(Calculator.class);
EasyMock.expect(Calculator.add(1, 2).andReturn(3);

PowerMock.replayAll();

Operatii obj = new Operatii();
int ret = obj.operatieComplexa(1, 2);

PowerMock.verifyAll();

Assert.assertEquals(4, ret);
}
}

This is all. When you run the test the code will use an injected method instead of using the static method from Calculator class. Some elements need to be explained:

  • @RunWith(PowerMockRunner.class). It tells JUnit to use PowerMockRunner class for running the tests(it won't work without this line because PowerMock implements a custom class loader).
  • @PrepareForTest({Calculator.class}). This annotation describe the class which static methods will be mocked using mockStatic method.
In conclusion, PowerMock is a powerful testing framework which implements record/replay/verify phases in a similar manner as mocker. For more details, please visit: http://code.google.com/p/powermock/w/list

miercuri, 5 august 2009

Python invoking web services

Recently, I had to invoke a webservice method from python. One solution found was to build a SOAP request. After the request is built, I use httplib for sending request and receiving an answer from the webservice. For this demo, I'll use www.infovalutar.ro webservice(an exchange rate service from Romania).

------------------------------------------------------------------------------------------------
import httplib

HOST = "www.infovalutar.ro"
URL = "/curs.asmx"

def SOAP_GetMoneda(strMoneda):
strReq = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<getlatestvalue xmlns="http://www.infovalutar.ro/">
<Moneda>%s</Moneda>
</getlatestvalue>
</soap12:Body>
</soap12:Envelope>"""

return strReq % strMoneda

if __name__ == "__main__":
data = SOAP_GetMoneda("USD")

dctHeaders = {"Host" : HOST,
"Content-Type" : "text/xml; charset=utf-8",
"Content-Length" : len(data),
"SOAPAction" : "http://www.infovalutar.ro/getlatestvalue"}

con = httplib.HTTPConnection(HOST)

con.request("POST", URL, data, dctHeaders)
resp = con.getresponse()
print(resp.read())

con.close()
--------------------------------------------------------------------------------

What I don't show in this answer is how to parse the response. This should be a simple fact regarding the fact that soap response is a xml document. In the above presented code, I just print the response on the standard output.

vineri, 31 iulie 2009

JSF Localization

Localizations is the process through which an application(web or desktop) can present its' content in multiple languages. This is a hot subject nowadays and a standard is not yet defined for how to properly implement localization. In Java/JSF we can use ResourceBundle class from java.util. A simple example is shown below.

1. We create two resource files(english and romanian).
In each of them we add lbWelcome key with english(romanian) text.

2. We modify faces-config.xml for indicating the supported languages.

<application>
<locale-config>
<default-locale>ro< /default-locale>
<supported-locale>ro< /supported-locale>
<supported-locale>en< /supported-locale>
</ locale-config>
</application>

3. We create a jsp page for presenting the content.

<%@page pageEncoding="UTF-8" contentType="text/html; charset=ISO-8859-2" %>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

<f:view>


<h:form>
<h:commandLink action="#{languageBean.changeLanguage}" value="Romana">
<f:param name="lang" value="ro">
</h:commandLink>
|
<h:commandLink action="#{languageBean.changeLanguage}" value="English">
<f:param name="lang" value="en">
</h:commandLink><>

<h:outputText value="#{msg.lbWelcome}">
</h:form>
</f:view>

4. We create a backbean in which the method for changing the language is implemented


package ro.testlocalization.traduceri;

import java.util.Locale;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class LanguageBean {
public void changeLanguage() {
Map req = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String lang = req.get("lang").toString();

Locale newLocale = new Locale(lang);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);
}
}

5. We map the backbean in faces-config.xml.

miercuri, 29 iulie 2009

JAX-WS Webservices: Part 2

This post continues previous one for offering new information about jax-ws webservices. One issue which is often met is related to return types of the web service. For instance: We implement an EJB component which models a person. How can I return this? I might try to specify for one of the webservice methods the EJB as a return type. This is so wrong. The EJB might have a collection resulting from a OneToMany relation. When the client will try to access an element of this collections an exception will be raised complaining about "session closed". To avoid this, we implement a new class(wrapper) which will be serializable. We make sure we don't use Java Collection types like Set, List, Hash, ..... We'll use arrays instead([]). In the web service method we populate all attributes of the wrapper class. The following example demonstrates this:

@Entity
public class Persoana {
@Id
private long cnp;

@OneToMany(mappedBy="parinte")
private List rude;


//metode getter/setter
}


public class PersoanaWrapper implements Serializable {
private long cnp;

private PersoanaWrapper[] rude;

//metode getter/setter
}


Metoda din webservice care doreste sa returneze o persoana ar putea fi implementat de maniera urmatoare:

public PersoanaWrapper getPersoana(long cnp) {
//cod prin care incarc ejb-ul persoanei dorite. => Persoana persEJB;
PersoanaWrapper pers = new PersoanaWrapper();
int nrRude = persEJB.getRude().size();

pers.setCNP(persEJB.getCNP());
pers.setRude(new PersoanaWrapper[nrRude]);

for(int i = 0; i < nrRude; i++) {
PersoanaWrapper tmp = new PersoanaWrapper();
tmp.setCNP(persEJB.getRude().get(i).getCNP());
pers.getRude()[i] = tmp;
}

return pers;
}

One enhancement of the example is to add a new method/constructor which accepts an argument with the EJB type. Using wrapper classes you cand return whatever custom data type you want.
I mentioned in a previous post that when deploying a java web service in a container it will be exposed as a web service and as a Session bean. I strongly encourage you to invoke it as a web service or as a Session bean(not both). If you intend to make your application interoperable then use just web services.

How can we inject resources in a web service?

It is common to use resources in a web service. For instance, we might need to use a DataSource from the container. We might want to inject an EntityManager in the webservice. Both situation are easily solved in Java EE:

@PersistenContext(unitName="myPersistence")
private EntityManager em;

@Resource(mappedName="java:jdbc/MyDS")
private DataSource ds;

We can use @Resource annotation to inject various resources like:
  • Mail session
  • Custom data sources
  • Other resources

luni, 27 iulie 2009

JAX-WS Webservices

In one of the recent projects I worked on I was supposed to implement a SOA arhitectue. The business logic was exposed through web services. This solution was developed because one of its components was written in C# and the rest of components were written in Java. The chosen container for the business layer was JBoss 5(web services, ejb) and Tomcat 6 for front-end(web application). The first major issue was raised by the JBoss 5 version downloaded from the jboss.org site.

Obs: !!!!!!!!!If you use jre/jdk 6 download the jboss version compiled with jdk 6. Otherwise you will get weird errors when you try to access the webservice.

I assume that you downloaded the correct version of jboss on your computer. Java EE/jax-ws makes webservices creation a formality.

@WebService
@SOAPBinding(style=Style.RPC)
@Stateless
public interface ServiciuTest {
@WebMethod
public String sayHello(@WebParameter(name="message")String msg);
}

@Stateless
@WebService(endpointInterface="ServiciuTest")
public class ServiciuTestBean {
public String sayHello(String msg) {
return msg;
}
}

This is all you have to do for creating a functional web service. In this moment the webservice can be deployed on a container that supports jax-ws. In Java EE, the above mentioned class will be exposed as a web service and as a session bean. The interface described is an endpoint(spec) for the web service. The annotation used in the method declaration alter the way the wsdl file is generated. You must keep in mind that you won't be able to return classes which aren't serializable.

In the following paragraphs I present how a complex web service can be implemented. This web service downloads a file from server.

@WebService
@SOAPBinding(style=Style.RPC)
@Stateless
public interface ServiciuFilesTest {
@WebMethod
public byte[] getFile(@WebParam(name="file_name")String fName);
}

@Stateless
@WebService(endpointInterface="ServiciuFilesTest")
public class ServiciuFilesTestBean {
public byte[] getFile(String fName) {
   byte[] deRet = new byte[(int)(new File(fName)).length()];
try {
FileInputStream file = new FileInputStream(fName);
file.read(deRet);
file.close();
}
catch(IOException ioe) {
ioe.printStackTrace();
return null;
}
return deRet;
}
}

This is all you have to do. In this manner you can send files to a client through the web service. Usually, it is recommended that you encode the content sent using Base64.