Friday, March 28, 2008

Reebok Boxing Any Good

TestNG - provider of data

As mentioned in the article TestNG - first steps . TestNG Framework lets you define the parameters in the configuration file, which then can be used as arguments to methods of testing.
But TestNG is also available in a much more powerful mechanism for parameterization testing data. It is called. supplier data - data provider.
Data Provider is defined as a method denoted DataProvider annotation . This method should return a two-dimensional array of objects ( Object [] [] ) or the iterator after the one-dimensional arrays of objects (Iterator \u0026lt;Object[]> ). And the following array of objects returned by the iterator (or those in two-dimensional array) containing the arguments to the next call (as many times as these tables) of the test method.
method of data provider may be bezargumentowa or have an argument of type java.lang.reflect.Method , which defines tester method, for which the data will be provided.
To assign a data provider to the test method, you must properly set the parameter dataProvider for the annotation test, which is marked with the Testing Method. Optionally, if the method is a test on a different class than the method to provide data, set the parameter yet dataProviderClass annotations Test. In addition, the test method argument types must be compatible with the types of objects in the arrays returned by the data provider.
Unfortunately you can not use the provider, including data and parameters defined in the configuration file. You also can not pass these parameters to the methods of data providers. Below
stir example of using the data provider TestNG:
 pl.dwalczak.jpapg2 package, import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.DataProvider imports, org.testng.annotations.Test imports, pl.dwalczak.jpapg2.model.Address imports, pl.dwalczak.jpapg2.model.User; @ public class Test extends UserTest JpaTestCase {private static final Logger LOG = Logger.getLogger (UserTest.class) @ DataProvider (name = "address") public Object [] [] createTestData () {LOG.debug ("createTestData"); return new Object [] [] {{"Heniek", new Address ("Poznan", "11-111", "Hedwig", "12c/23")}, {"Manny", new Address ("Wroclaw, "22-222", "Kosciuszko", "14b ")}};} @ Test (dataProvider =" address ") public void createuser (String user, Address address) {LOG.debug (" create user "+ user) ; em.persist (new User (user, address, address));} @ Test (dependsOnMethods = {"createuser"}, dataProvider = "address") public void findUser (String user, Address address) {LOG.debug (" find user: "+ user); User u = (User) em.createNamedQuery (user.findByNickName"). setParameter ("nickname" user). getSingleResult (); LOG.debug ("Found user:" + u); Assert.assertNotNull (u); Assert.assertEquals (address, u.getAddress ());}} 

Resources

Example Source Files
TestNG documentation - 5.5.2 - From DataProviders

Thursday, March 27, 2008

Pokemon Red Play Game

JPA - Embedded objects (components)

Introduction

embedded objects used in the event of conflict the object model and physical model database. For example, the user is being linked to being address. The object model of these entities will be implemented by separate objects, but in a relational database in order to achieve better performance can be implemented using a single table, containing data from both user and his address. In this example, the URL will be built and will be subject to belong to the permanent facility user. An important feature is the built-in objects that are not sustained its identity (its identifier) \u200b\u200band can not be shared by different objects and equipment. Built Class

embedded object class must be marked with a note Embeddable . This does not mean it as an entity, the more determined not to her table in the database, or ID. In addition to wbudowywanej this class to be specified as the field mapping for simple entities. Below is an example of a class definition wbudowywanej - Address:
 pl.dwalczak.jpapg2.model package imports, javax.persistence.Column imports, javax.persistence.Embeddable; @ Embeddable public class Address {private String city; private String postcode; private String street; private String number; @ Column (length = 50, Nullable = false) public String getCity () {return city;} public void setCity (String city) {this.city = city;} @ Column (length = 6, Nullable = false) public String getPostcode () {return postcode;} public void setPostcode (String postcode) {this.postcode = postcode;} @ Column (length = 50, Nullable = false) public String getStreet () {return street;} public void setStreet (String street) {this.street = street;} @ Column (length = 10, Nullable = false) public String getNumber () {return number;} public void setNumber (String number) {this.number = number;}} 

wbudowywanych Placing objects on the premises and equipment

Class fields of the type designated as a bear in a built Embedded in a note . But it is not necessary, since the specification requires that the JPA EntityManager to seek out the same matter on the basis of annotations Embeddable , which bears the class of the field. The fields are mapped to an object embedded in the columns of the table entity to which it belongs. Overriding attributes
JPA mapping allows to overwrite the attributes defined in the mapping class wbudowywanej. For this purpose the annotation AttributeOverrides , which contains a list of endorsements AttributeOverride . And these only serve to override the mapping of each field class. Mechanism to override the mapping of attributes are big opportunities in the context of reusable class definitions wbudowywancyh. Below is an example of an entity, which includes two buildings built on the type of address (permanent residence address and mailing address.)
 pl.dwalczak.jpapg2.model package imports, javax.persistence.AttributeOverride; javax.persistence.AttributeOverrides import, import javax.persistence.Column imports, javax.persistence.Embedded; javax.persistence.Entity import, import javax.persistence. GeneratedValue; javax.persistence.GenerationType import, import javax.persistence.Id; javax.persistence.NamedQuery import, import javax.persistence.SequenceGenerator imports, javax.persistence.Table; @ NamedQuery (name = "user.findByNickName", query = "select u from User u WHERE u.nickName =: nickname") / / Define a sequence of "users_seq" used to generate the primary key table "users". @ SequenceGenerator (name = "users_seq") / / mapping table "users". @ Entity @ Table (name = "users") public class User {private Long id; private String nickname; private Address address; private Address mailingAddress; @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "users_seq") @ Column (name = "usr_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id;} @ Column (name = "usr_nickname", unique = true, Nullable = false, length = 24) public String getNickName ()  {
return nickName;
}
public void setNickName(String name) {
this.nickName = name;
}

@Embedded
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}

@Embedded
@AttributeOverrides({
@AttributeOverride(name="city", column=@Column(name="ma_city")),
@AttributeOverride(name="postcode", column=@Column(name="ma_postcode")),
@AttributeOverride(name="street", column=@Column(name="ma_street")),
@AttributeOverride(name="number", column=@Column(name="ma_number"))
})
public Address getMailingAddress() MailingAddress {return;} public void setMailingAddress (Address mailingAddress) {this.mailingAddress = mailingAddress;}}

Resources

example source files
Hibernate Annotations - 2.2.2.3. Embedded objects (aka components)
JPA specification

Tuesday, March 18, 2008

Borderless Printing Laser

TestNG - first steps

example of the way of writing the article "JPA - first steps," I decided that I would do well to learn the first steps to assist framework'u perform unit tests - TestNG. My first impression is very positive. Compared to the JUnit is simpler and more accessible interface, but is more powerful and is also much better documented. Hierarchy

tests in TestNG we doczycznienia with the following hierarchy of tests: suite (set), Test, Class (class containing test methods) and Method (Testing Method). While the Test Suite and are purely logical entities (defined in the configuration level), the Class and Method are units that contain the physical implementation of the tests. In addition, TestNG allows marking Class and Method marker group. At the same time it is possible to assign them to multiple groups. For all of these entities hierarchy and groups can set out the methods that will be called before or after the tests.

dependencies between tests

TestNG allows you to define dependencies between tests. You can specify that the execution of a method of testing organization or a class of tests will depend on successful implementation of the other test methods or test groups. Test Configuration

Tests in TestNG are configured in a xml file conforming to the DTD: http://testng.org/testng-1.0.dtd and through endorsements. In one configuration file can define a Suite (\u0026lt;suite> marker), within which is defined by any number of Test'ów (\u0026lt;Test> tags), or you can import the configuration files for other sets of tests. On the test, in turn, may consist of any number of groups (tag \u0026lt;groups>), class (\u0026lt;classes> marker), and you can specify the Java packages (\u0026lt;pakages> marker), within which the class will be searched for testing. For class, you can also specify which methods are to be executed and which not. Both individuals and Test Suite, you can define parameters that can be transferred In Test methods (marker \u0026lt;parameter>). With the use of annotations can include determine such things as: - whether the class includes the tests (Test annotation), - if the method is a method of testing (including the endorsement test) - the term the group owning class or the method (parameter groups for the endorsement test), and - Testing method or class containing the tests is dependent on other tests (parameter dependsOnGroups dependsOnMethods and annotations test) - identify ways to call before or after the tests (annotate Before and After * *), - define the parameters for the transmission method testing (annotation Parameters)

Example The following example is a unit tests developed for the article "JPA - first steps." It consists of a configuration file, the abstract base class and two classes containing a specific test method.
configuration file configuration file contains the definition of course test (implemented in two classes) and methods used by the majority of testing parameters.
 \u0026lt;suite name="Suite1"> \u0026lt;parameter name="user1" value="heniek" /> \u0026lt;parameter name = "user2" value = "Frank" /> \u0026lt;test Name="Test"> \u0026lt;classes> \u0026lt;class name="pl.dwalczak.jpapg1.UserTest" /> \u0026lt;class name="pl.dwalczak.jpapg1.MessageTest" /> ; \u0026lt;/ classes> \u0026lt;/ test> \u0026lt;/ suite> 
abstract base class
This class defines the basic services needed for testing the model mapping JPA. First of all, provide the EntityManager, which initiates and begins a transaction before executing each test method. However, after performing the test method and to approve the transaction closes EntityManager'a. After completing the entire test suite (Suite) is closed EntityManagerFactory.
 pl.dwalczak.jpapg1 package; javax.persistence.EntityManager import, import org.apache.log4j.Logger; org.testng.annotations.AfterMethod import, import org.testng.annotations.AfterSuite imports, org.testng.annotations.BeforeMethod imports, pl.dwalczak.jpapg1.util.JpaUtil; abstract public class {private static JpaTestCase final Logger LOG = Logger.getLogger (JpaTestCase.class) protected EntityManager em; @ BeforeMethod beginWorkUnitAndTransaction public void () {try {em = JpaUtil. getEntityManager (); em.getTransaction (). begin ();} catch (RuntimeException e) {LOG.error ("Can not  beginWorkUnitAndTransaction", e);
}
}

@AfterMethod
public void closeWotkUnitAndCommitTransaction() {
try {
if (false == em.getTransaction().getRollbackOnly()) {
em.getTransaction().commit();
} else {
em.getTransaction().rollback();
}
} catch (RuntimeException e) {
LOG.error("Can't closeWotkUnitAndCommitTransaction", e);
} finally {
if (null != em) {
try {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
} catch (RuntimeException e) {
LOG.error("Can't close entity manager!", e);
}
} I = null;}} @ AfterSuite public void closeEntityManagerFactory () {JpaUtil.closeEntityManagerFactory ();}}
UserTest
Class This class contains all tests for entity "you" and is provided with a suitable marker groups ("user") . It includes examples of passing parameters to methods of testing and determining the relationship between methods of Test.
 pl.dwalczak.jpapg1 package, import java.util.List; import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.Parameters; org.testng.annotations.Test import, import pl.dwalczak.jpapg1.model.User; @ Test (groups = "user") public  class UserTest extends JpaTestCase{

private static final Logger LOG = Logger.getLogger(UserTest.class);

@Test
@Parameters({ "user1" })
public void createUser1(String user) {
LOG.debug("create user: " + user);
em.persist(new User(user));
}

@Test
@Parameters({ "user2" })
public void createUser2(String user) {
LOG.debug("create user: " + user);
em.persist(new User(user));
}

@Test(dependsOnMethods={"createUser1", "createUser2"})
@SuppressWarnings(value="unchecked")
public void list() {
LOG.debug("get user list");
em.getTransaction().setRollbackOnly();
List list = em.createNamedQuery (user.findAll "). getResultList (); LOG.debug (" user list: "+ list); Assert.assertEquals (list.size (), 2);} @ Test (dependsOnMethods = { "createUser2"}) @ Parameters ({"user2"}) public void findUser (String user) {LOG.debug ("find user" + user); User u = (User) em.createNamedQuery (user.findByNickName " ). setParameter ("nickname", user). getSingleResult (); LOG.debug ("Found user:" + u); Assert.assertNotNull (u);}}
MessageTest
Class This class contains all tests for entity " Message. " Execution of all testing methods This class is subject to a positive test result from the group "user".
 pl.dwalczak.jpapg1 package, import java.util.List; import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.Parameters; org.testng.annotations.Test import, import pl.dwalczak.jpapg1.model.Message imports, pl.dwalczak.jpapg1.model.User; @ Test (dependsOnGroups = "user") public class extends MessageTest JpaTestCase {private static final Logger LOG = Logger.getLogger (MessageTest.class) ; @ Test @ Parameters ({"user1" "user2"}) public void user1SendToUser2 (String user1, String user2) {LOG.debug ("user1SendToUser2") SendMessage ("title1", "content1"  user1, user2);
}

@Test
@Parameters({ "user2", "user1" })
public void user2SendToUser1(String user1, String user2) {
LOG.debug("user2SendToUser1");
sendMessage("title2", "content2", user1, user2);
}

private void sendMessage(String title, String content, String userFrom, String userTo) {
User uFrom = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", userFrom).getSingleResult();
User uTo = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", userTo).getSingleResult();
Message message = new Message(title, content, uFrom, uTo);
LOG.debug("send a message: " + message);
em.persist(message);
}

@Test(dependsOnMethods={"user1SendToUser2", "user2SendToUser1"})
@Parameters({"user1"})
@SuppressWarnings(value="unchecked")
public void viewUser1Messages(String user) {
LOG.debug("view messages of: " + user);
User u = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", user).getSingleResult();
Assert.assertNotNull(u);
List received = em.createNamedQuery("message.findReceived").setParameter("user", u).getResultList();
LOG.debug("received messages: " + received);
Assert.assertEquals(received.size(), 1);
Letter em.createNamedQuery send = ("message.findSend"). SetParameter ("user", u). GetResultList (); LOG.debug ("send messages:" + send); Assert.assertEquals (send.size (), 1);}}

Resources

source files
TestNG documentation

Monday, March 17, 2008

Broken Cappileries In Breasts

JPA - Getting Started

longish introduction

Since the publication of the final specifications EJB3 lot of time has elapsed, and there are more and more implementation of this technology - more or less complete. This probably means that EJB3 will be increasingly popular as the technology base for new projects. So I thought that it's time to explore this technology a little closer. I would like to begin by defining the specifications of the lowest layer of the average webaplikacji - a model of persistent data and interface with a database (or perhaps with JDBC), a Java Persistence API - JPA. In fact, JPA is nothing revolutionary. SFE rather on concepts proven in the most popular ORM framework unless - Hibernate. I enjoy it more that the last two years with Hibernate I had a lot to do. What is more out of Hibernate is an implementation of JPA - and I'm going to use it. Undoubted advantage of JPA is that in a compact and relatively easy way to standardize the basic mechanisms of ORM. JPA interface is not too extensive and advanced applications may prove to be insufficient. The JPA will not find many of the advanced elements of existing frameworks ORM. It has no API to dynamically create search criteria, or it is not possible to define the class as a field enumerated SQL formula. Therefore, JPA implementations available to provide extensions to the basic specification. However, this means that a transparency of the implementation of the JPA specification may be only illusory. From a user perspective Hibernate knowledge JPA is inevitable, and so if you want to use the mapping annotations. However, in the style of the application configurations and EntityManager'a JPA is not necessary - at least for now. Another advantage of JPA is that you can use not only in the EJB3 container, but also in the normal JSE. But no longer have enough of these digressions, so move on to describe a specific example using JPA.

matter problem

to do is a model in which the center is being Message - Message, which contains in itself: the subject - title, content - content, and links to the entity User - User in the role of sender and recipient.

JPA Configuration

JPA specification specifies that the configuration file should be in your META-INF/persistence.xml. Listing the configuration file of my sample application:
 \u0026lt;persistence version = "1.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns: xsi = "http://www.w3.org/ 2001/XMLSchema-instance "xsi: schemaLocation =" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd "> \u0026lt; persistence-unit name = "jpapg1"> \u0026lt;! - Identify suppliers that implements JPA. -> \u0026lt;Provider> Org.hibernate.ejb.HibernatePersistence \u0026lt;/ provider> \u0026lt;! - \u0026lt;class> \u0026lt;/ Class> You can specify a list of classes of mapping model database. The EJB3 container is completely unnecessary, because the JPA specification imposes the obligation to implement an automatic search classes. This feature however, is not defined when you run in the normal environment JSE. However, Hibernate can be parameterized in order to search for these classes also in the JSE. -> \u0026lt;properties> \u0026lt;! - Bed configuration parameters JPA - Hibernate -> \u0026lt;property name = "hibernate.archive.autodetection" value = "class" /> \u0026lt;property name="hibernate.show_sql" value="true" /> \u0026lt;property name="hibernate.format_sql" value="true" /> \u0026lt;! - Parameters access to the database. -> \u0026lt;property Name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" /> \u0026lt;property name = "hibernate.connection.url" value = "jdbc: HSQLDB file: jpapg1db "/> \u0026lt;property name="hibernate.connection.username" value="sa" /> \u0026lt;property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> \u0026lt;! - Parameter specifying the database schema generation from mapingów. -> \u0026lt;property Name="hibernate.hbm2ddl.auto" value="create" /> \u0026lt;/ properties> \u0026lt;/ persistence-unit> \u0026lt;/ persistence> 

data model and mapping

confine myself Listing only on presentation of an example source code, which - at least I hope so - it is enough okroszony comments.
User - User
 pl.dwalczak.jpapg1.model package, import java.util.List; javax.persistence.Column import, import javax.persistence.Entity; javax.persistence.GeneratedValue import, import javax.persistence.GenerationType; javax.persistence.Id import, import javax.persistence.JoinColumn imports, javax.persistence.NamedQueries; javax.persistence.NamedQuery import, import Javax . persistence.OneToMany; javax.persistence.SequenceGenerator import, import javax.persistence.Table; @ NamedQueries (value = {@ NamedQuery (name = "user.findAll", query = "select u from User u order by asc u.nickName "), @ NamedQuery (name =" user.findByNickName ", query =" select u from User u WHERE u.nickName =: nickname ")}) / / Define a sequence of" users_seq "for the generation primary key table "users". @ SequenceGenerator (name = "users_seq") / / mapping table "users". @ Entity @ Table (name = "users") public class User {private Long id; private String nickname; private letter  receivedMessages; private letter  sendMessages / / availability of default constructor is required by the JPA. public User () {} public User (String nickname) {this.nickName = nickname;} / / Primary key table (column "usr_id"), / / \u200b\u200bwhose value is determined by the sequence "users_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "users_seq) @ Column (name = "usr_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id;} / / mapping column usr_nickname "which must have a unique value / / and have a maximum length of 24 characters. @ Column (name = "usr_nickname", unique = true, Nullable = false, length = 24) public String getNickName () {return nickname;} public void setNickName (String name) {this.nickName = name;} / / mapping connections to the table "messages" in the role of the recipient. / / Definition of columns in the table "messages" which is the concatenation (Msg_to "). / / Select the record for being the "User" has nothing to do with the "Message" / / associated by the association. @ OneToMany @ JoinColumn (name = "msg_to", insertable = false, updatable = false) public List  getReceivedMessages () {return receivedMessages;} public void setReceivedMessages (Letter  receivedMessages) {this.receivedMessages = receivedMessages;} / / Definition connection to the table "messages" in the role of the sender. @ OneToMany @ JoinColumn (name = "msg_from", insertable = false, updatable = false) public List  getSendMessages () {return sendMessages;} public  void setSendMessages(List   sendMessages) {
this.sendMessages = sendMessages;
}
}
Wiadomość - Message
 package pl.dwalczak.jpapg1.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@NamedQueries(value={
@NamedQuery(
name="message.findReceived",
query="select m from Message WHERE m.to m =: user "), @ NamedQuery (name =" message.findSend ", query =" select m from Message m WHERE m.from =: user ")}) / / Define a sequence of" messages_seq "for the generate the primary key table "messages". @ SequenceGenerator (name = "messages_seq") / / mapping table "messages". @ Entity @ Table (name = "messages") public class Message {private Long id; private String title; private String content; User from private, private to User / / availability of default constructor is required by the JPA public Message () {} public Message (String title, String content, User from, the User) {this.title = title; this.content = content; this.from = from; this.to = this;} / / Primary key table (column 'msg_id'), / / \u200b\u200bwhose value is determined by the sequence "messages_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "messages_seq") @ Column (name = "msg_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id; } / / mapping column msg_title "whose value can be up to 64 characters. @ Column (name = "msg_title", length = 64) public String getTitle () {Return title;} public void setTitle (String title) {this.title = title;} / / mapping column msg_content "whose value can be up to 1024 characters. @ Column (name = "msg_content", length = 1024) public String getContent () {return content;} public void setContent (String content) {this.content = content;} / / Mapping to the table "users" - the message sender. / / This link is mandatory - it must be set - and is implemented by the / / foreign key to table "users", which stores the value of column "msg_from. / / This is equivalent to the relationship defined on User.sendMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_from" Nullable = false) public User getFrom () {return from;} public void setFrom (User from) {this.from = from;} / / Mapping to the table "users" - the message recipient. / / This is equivalent to the relationship defined in the User.receivedMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_to" Nullable = false) public User ghetto () {return this;} public void Setto (User to) {this.to = this;}}

Entity Manager

Entity Manager is that in the JPA, which is in the Hibernate Session. The JSE You can obtain it as follows:
 javax.persistence.Persistence.createEntityManagerFactory ($ PERSISTANCE_UNIT_NAME). createEntityManager (); 
In EJB3, you can do this by injecting (the container) to the field in the beanie EJB:
 javax.ejb.Stateless import; import javax.persistence.PersistenceContext; @ Stateless public class Example implements ExampleBean {@ PersistenceContext EntityManager em; ... 
} Entity Manager is the starting point to perform such operations as: - the consolidation of the object (the method persist) - queries execution (method and find methods of family group createQuery) - manulnego determining transaction - beginning, acceptance and withdrawal (method getTransaction ())

Query Language query language in the JPA is a JPA-QL (EJB-QL extension) and is very similar to Hibernate'owego HQL'a. I think I used the example queries are simple enough that it does not require comment. Resources

example source files
Java Persistence with Hibernate - Sample Chapter 2
JPA - javadoc
Hibernate Annotations
Hibernate EntityManager