Thank you for visiting! If you liked the site, please add a bookmark, else add a critical comment! Would you like to visit Greece? Traditional Greek flag This real estate site is only available in Greek! The holy mountain
Showing posts with label EJB 3. Show all posts
Showing posts with label EJB 3. Show all posts

Tuesday 17 May 2011

Migrating an EJB 3 application to the new JDeveloper version

This new post discusses several exceptions which have occurred because of migration to the current version of JDev. As far as I can remember the application was working well with the previous version. It seems that code rots!
The first has to do with populating a primary key field with a sequence in an entity EJB:

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BID_SEQUENCE" )
    @SequenceGenerator(name = "BID_SEQUENCE", sequenceName = "BID_SEQUENCE",
    allocationSize = 10)
       
If you get an:

 Exception Description: The sequence named [YOUR_SEQUENCE_NAME] is setup incorrectly. Its increment does not match its pre-allocation size.

 A way to avoid the exception is to  use 100 as a start value in sql create sequence statement. That will resolve the problem: by default the start value is 1, when Eclipselink attempts to use the first allocated sequence value it's negative 1 - 100 + 1, that causes the exception.

The second is more subtle to resolve, as the error message does not appear at once. If you get a mysterious error about a missing table which does not belong to the application db schema:

      Eclipse Persistence Services - 2.1.3.v20110304-r9073):
      org.eclipse.persistence.exceptions.DatabaseException Internal Exception:
      java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
      Error Code: 942 Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
      bind => [50, SEQ_GEN] Query: DataModifyQuery
      (sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")

a way to get rid of the exception is editing the persistense.xml as follows:


<?xml version="1.0" encoding="UTF-8" ?>
<persistence 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"
             version="1.0">
  <persistence-unit name="Model">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/ActionBazaarDS</jta-data-source>
    <class>actionbazaar.persistence.Category</class>
    <class>actionbazaar.persistence.BillingInfo</class>
    <class>actionbazaar.persistence.Order</class>
    <class>actionbazaar.persistence.User</class>
    <class>actionbazaar.persistence.Bid</class>
    <class>actionbazaar.persistence.Bidder</class>
    <class>actionbazaar.persistence.Seller</class>
    <class>actionbazaar.persistence.Item</class>
    <class>actionbazaar.persistence.ContactInfo</class>
    <class>actionbazaar.persistence.ShippingInfo</class>
    <properties>
      <property name="eclipselink.target-server" value="WebLogic_10"/>
      <property name="javax.persistence.jtaDataSource"
                value="jdbc/ActionBazaarDS"/>
      <property name="eclipselink.target-database" value="Oracle11"/>
      <!--Addon in case of
      Eclipse Persistence Services - 2.1.3.v20110304-r9073):
      org.eclipse.persistence.exceptions.DatabaseException Internal Exception:
      java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
      Error Code: 942 Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
      bind => [50, SEQ_GEN] Query: DataModifyQuery
      (sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")>
      -->
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>


Thus, the new SEQUENCE table will be automatically created and the application will at last commit the insert successfully.
The morale of the story is that frequent migrations due to upgrades can cause trouble. Perhaps, applying gradual patches instead, i.e. via the jdev online extensions way and waiting for a new full release would be safer. Otherwise you might spend hours searching about solutions on the internet, experimenting with each one and certainly overheating the computer. Always make sure you are in a well ventilated room, with full air conditioning when trying to migrate, or else high temperatures will cause your code to decay so much faster! Certain laptops such as Hewlett Packard Pavilion, overheat and power off immediately without prompting for save, very frequently at warm climates. After all, you don't want your code to go rot, do you?

Wednesday 8 September 2010

JDeveloper 11g:Using Log4j in stateful EJB

Since the use of log4j has proven to be a very popular subject for the readers, another code snippet for your Model project will be  given as an example. In case you prefer ADF business components, you can find an example too. If you 'd also like an example for a backing bean for your ViewController project this time, you  can have it here
First, one has to double click the project, so that the window of the libraries appears, in order to add the Log4j jar library. 
Second, navigate to C:\...\Model\src to create the log4j.properties file:

# **Set root logger level to DEBUG and its only appender to A.
log4j.rootLogger=DEBUG, A
# ***** A is set to be a ConsoleAppender.
log4j.appender.A=org.apache.log4j.ConsoleAppender
# ***** A uses PatternLayout.
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


Finally, if one 'd like to use log4j within a  stateful EJB class, the source code is similar:

...
import org.apache.log4j.Logger;

@Stateful(name = "PlaceOrder", mappedName = "ejb3inaction-Model-PlaceOrder")
@Remote
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)  
public class PlaceOrderBean implements PlaceOrder {
    Logger logger =Logger.getLogger(this.getClass().getSimpleName());
...
    @Remove                                                          
    @TransactionAttribute(TransactionAttributeType.REQUIRED)         
    public Long confirmOrder() {
      ...
      em.persist(order);            
      if (logger.isDebugEnabled())
         logger.debug("******************Order confirmed!**************");
      return order.getOrderId();
    }
...
}
Thus, one gets the following log output from the integrated Weblogic server:

Run startup time: 9656 ms.
[Application ejb3inaction deployed to Server Instance IntegratedWebLogicServer]
<2010-09-08 16:00:18.4--ServerSession(1576505)--EclipseLink, version: Eclipse Persistence Services - 2.0.2.v20100323-r6872>
<2010-09-08 16:00:18.416--ServerSession(1576505)--Server: WebLogic Server 10.3.3.0  Fri Apr 9 00:05:28 PDT 2010 1321401 >
<2010-09-08 16:00:18.837--ServerSession(1576505)--file:/C:/Users/Nick/AppData/Roaming/JDeveloper/system11.1.1.3.37.56.60/o.j2ee/drs/ejb3inaction/ModelEJB.jar/_Model login successful>
0    [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO  PlaceOrder_i7ibfi_Impl  - ******************Order confirmed!**************


In case you prefer working with Eclipse, the process is quite similar. See for example:
http://snippets.dzone.com/posts/show/3248
Finally, if you need more tips about appenders:
http://www.mobilefish.com/developer/log4j/log4j_quickguide_appenders.html

https://logging.apache.org/log4j/2.x/ 

Tuesday 13 July 2010

Getting the current date in your model layer

Besides the standard way of getting the current date as a String, one could come across the need of inserting in a database table column of date datatype. Thus, the well known code snippet won't be suitable:

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 
 java.util.Date date = new java.util.Date();
 
 String datetime = dateFormat.format(date);
 
 System.out.println("Current Date Time : " + datetime);
 
In case you use ADF business components for your Model project, you get the 
current date in a slightly different way. Consider for example the following code snippet,
from an adf business components, employees entity object: 
 
import oracle.jbo.domain.Date;
...

              
protected void doDML(int operation, TransactionEvent e) {
                if (operation == DML_UPDATE) {
    ...
               histStartDate = row.getEndDate();
              /*Check whether end date equals current date*/
              if (histStartDate.equals(new Date(Date.getCurrentDate()))){
                  System.out.println("End date equals current date!");
                  }
      
In case you need to convert  oracle.jbo.domain.Date to java.util.Date, please consult this:

http://forums.oracle.com/forums/thread.jspa?threadID=2185902&tstart=15

or

http://www.ecotronics.ch/webdesign/javadate.htm
  

Finally, in case you prefer EJB's for your Model project instead, you might consider the following example:

/*Typical current date for DB inserts */
java.util.Date today = new java.util.Date();
java.sql.Date bidDate = new java.sql.Date(today.getTime());
/* public void setBidDate(Date bidDate)*/
newBid.setBidDate(bidDate);

Which is in a sense, the most paradox way of all, since in order to get the current date, you actually need to call getTime()!

References

More help about: using timestamps
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Monday 12 July 2010

JDeveloper 11g:Using Log4j in EJB projects

Apart from the usual web client interface, a EJB 3 application can be accessed also by a plain Java Standard Edition client. This post clarifies the use of Log4j in the latter form of client. To add the Log4j jar library, double click the project, so that the window of the image appears. As for web based (view) client J2EE projects you can read it here:

All that 's written there is still valid. I would like to add a couple of things. First, you need to create the log4j.properties file in the following path:
C:\...\Model\src\
A copy of the log4j.properties file is given here for your convenience:
# **Set root logger level to DEBUG and its only appender to A.
log4j.rootLogger=DEBUG, A
# ***** A is set to be a ConsoleAppender.
log4j.appender.A=org.apache.log4j.ConsoleAppender
# ***** A uses PatternLayout.
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Secondly, when it comes to EJB model projects, you need to add the following code in italics, in order to avoid the expensive use of System.out.println() in your client classes:
...
import org.apache.log4j.Logger;


public class PlaceOrderClient {
static Logger logger =Logger.getLogger("PlaceOrderClient");
/* instead of Logger logger = Logger.getLogger(this.getClass().getSimpleName());*/

public static void main(String [] args) {
try {
final Context context = getInitialContext();
PlaceOrder placeOrder = (PlaceOrder)context.lookup("ejb3inaction-Model-PlaceOrder#actionbazaar.buslogic.PlaceOrder");
if (logger.isDebugEnabled())
             logger.debug("Exercising PlaceOrder EJB...");
// System.out.println("Exercising PlaceOrder EJB...");

The full source code is available on OTN:

http://www.oracle.com/technetwork/indexes/samplecode/jdeveloper-adf-sample-522118.html 
and is given without any guarantee of support whatsoever.
 
Finally, in case you prefer working with Eclipse, the process is quite similar. See for example:
http://snippets.dzone.com/posts/show/3248
If you need more tips about appenders:
http://www.mobilefish.com/developer/log4j/log4j_quickguide_appenders.html

https://logging.apache.org/log4j/2.x/ 

Tuesday 29 June 2010

Comments on EJB 3 in action, by Debu Panda, Reza Rahman, Derek Lane

On the bright side, the text is most of the times crystal clear, easy to understand and follow the code creation from scratch. The helpful appendix of the book guides the reader to setup the Sun Glassfish application server in minutes, without any trouble. Such easiness really tempts to switch your java integrated development environment (IDE ) to Sun Netbeans. The database scripts given are for Oracle though, not for Derby. The source code of the book runs correctly out of the box with only an exception as mentioned here:
http://www.manning-sandbox.com/thread.jspa?threadID=37203&tstart=0
Apart from Glassfish, there are also many code versions, suitable for the older Oracle Application Server (oc4j),JBoss and weblogic 10.
On the dark side, the text is IDE neutral, the deployment is done using ant scripts. Many spelling errors also appeared in the text and the huge errata page at Manning site.
All in all, the book is highly recommended, I am looking forward to reading its newer, updated edition!