Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, September 16, 2017

Basics of Java Garbage Collection

It’s an old joke from the time when Java was new and slow compared to other languages. Over time, Java became a lot faster. Today it powers many real-time applications with hundreds of thousands of concurrent users. These days, the biggest impact on Java’s performance comes from its garbage collection. Fortunately, in many cases, it can be tweaked and optimized to improve performance.

For most applications, the default settings of the JVM work fine. But when you start noticing performance issues caused by garbage collection and giving more heap memory isn’t possible, you need to tune and optimize the garbage collection. For most developers, it’s a chore. It requires patience, good knowledge garbage collection works and an understanding of application’s behavior. This post is a high-level overview of Java’s garbage collection with some examples of troubleshooting performance issues.

Continue reading here

Thursday, August 24, 2017

TLS 1.0 has been disabled - Salesforce

First things first: What's TLS and why did Salesforce moved to 1.x and had to disable TLS 1.0?

TLS 1.0

What kind of improvements brings to the table TLS 1.1?

  1. Added protection against cipher-block chaining (CBC) attacks.
  2. Support for IANA registration of parameters.
Clearly TLS 1.1 is more secure (compared to 1.0).

The things that can be affected in your instances are as below:

  • Web requests to Salesforce URLs that require authentication. 
  • Web requests to the login page of a My Domain.
  • Web requests to Community or Force.com sites.
  • Web requests to Customer and Partner portals.
  • Web to lead, web to case, and web to custom object requests API requests to Salesforce Callouts using Apex to a remote endpoint.
  • Workflow outbound messaging callouts to a remote endpoint Callouts using Lightning Connect to a remote endpoint AJAX proxy callouts to a remote endpoint.
  • Delegated authentication callouts to a remote endpoint Mobile apps developed with Salesforce Mobile SDK need to upgraded to SDK v4.


That's a big list and if you are an enterprise org, then I am sure you would have at least one of the above things in your org and you may find it to be broken if you don't take any action.


So below are some of the suggestions to fix this issue:
  • If you are using force.com migration tool and ANT process be on a latest ANT version. 
  • If you are using Java 7, upgrade to Java 8 since Java 8 by default uses 1.2
  • If have an integration running, like WebMethods, there will be setting to disable TLS 1.0 or to enable TLS 1.2 (see -Dhttps.protocols=TLSv1.1,TLSv1.2). 
  • You can disable TLS 1.0 in your browser, but I'd rather upgrade :) 
  • Also look for specific configuration if you want to explicitly force tools to use TLS 1.1 or TLS 1.2


Hopefully this sheds some light and helps you reduce the pain of dealing with this.


Saturday, June 24, 2017

Setup Lombok with STS/Eclipse based IDE

For those of you who haven't heard about boilerplate code, you can check this link
Now that you already know what's that we found this little library

You can add it to your Maven projects easily, however adding it to your Eclipse is a challenge, especially if you are not using barebones Eclipse like me, who happens to use STS and initially it didn't work:


Why it doesn’t generate getter and setter like in the video? I already installed that thing like 3 times and nothing :(

Well, the solution for me was this:

Paste the JAR manually into MacOS folder

Add the option
to the file STS.ini

Finally you NEED to close the STS/eclipse and start again. (Restart doesn’t take effect)

Once you’ve done close and start STS. You’ll see the getter and setter is autogenerated.
In case you see any compilation errors, just clean and build your project.


Voila!

Friday, December 19, 2014

JBoss AS 7 not accepting remote connections

For those who use JBoss AS 7 and want to connect to your application using the IP or server name from a computer in the intranet, you need to do this:
This is for Dev Environments only!
The answer is... Change the 127.0.0.1 (localhost) to 0.0.0.0 in standalone.xml

Monday, October 13, 2014

Invoke a SOAP API written in Salesforce using Axis

I had to consume an API written by someone else in Salesforce. I got the WSDL and the EndPoint.

Essentially what I had to do is to replace existing code I wrote a year ago to perform User Provisioning in Salesforce and rely on this API to perform that logic.

Now the interesting part is how to write my client, the obvious answer was to use WSDL2Java (Axis), because I don't want to write much code. And this is my final code: This is a simple Cooking recipe with the exception of these lines: Things to keep in mind (otherwise you'll get "INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session"):
  1. Open a session in Salesforce (that's how get permission to invoke the API)
  2. Populate SessionHeader object (with Salesforce sessionId)
  3. Set the Header to your Port before making your call

Monday, August 25, 2014

Java Code Refactoring


I recently browsed again the excellent book Code Complete from Steve McConnell while in the middle of several Java code reviews. Although the book is nor specifically dedicated to Java code, I still found it quite useful and inspiring.

The chapter on refactoring in particular offers a very practical perspective that all programmer should have in mind when it comes to infuse a dose of evolution in the life cycle of their software.

What I found particularly valuable are the checklists that the author has put together: reasons to refactor, specific re-factorings (data level, statement level, routine-level, class-implementation, class-interface, system-level), refactoring safely, strategies, summary.

Since I do not have time to comment every item in these checklists, I decided to pick-up those that are not trivial or obvious and might bring the best return on your refactoring investment.

In a future post, I would like to illustrate some of these refactoring techniques with java code snippets, but that will be later :)


Checklist: Reasons to Refactor
  • Code is duplicate
  • A routine is too long
  • A loop is too long or too deeply nested
  • A class/interface/method has poor cohesion ⇐
  • A class interface does not provide a consistent level of abstraction ⇐
  • A parameter list has too many parameters ⇐
  • Changes within a class tend to be compartmentalized
  • Changes require parallel modifications to multiple classes ⇐
  • Inheritance hierarchies have to be modified in parallel
  • Related data items that are used together are not organized into classes ⇐
  • A routine uses more features of another class than of its own class
  • A primitive data type is overloaded
  • A class doesn't do very much
  • A chain of routines passes tramp data ⇐
  • A middle man object isn't doing anything
  • One class is overly intimate with another
  • A routine has a poor name
  • Data members are public
  • A subclass uses only a small percentage of its parents' routines
  • Comments are used to explain difficult code
  • Global variables are used
  • A routine uses setup code before a routine call or takedown code after a routine call
  • A program contains code that seems like it might be needed someday

Checklist: Summary of Refactorings
  • Data Level Refactoring
  • Replace a magic number with a named constant ⇐
  • Rename a variable with a clearer or more informative name
  • Move an expression inline
  • Replace an expression with a routine
  • Introduce an intermediate variable
  • Convert a multi-use variable to a multiple single-use variables ⇐
  • Use a local variable for local purposes rather than a parameter
  • Convert a data primitive to a class
  • Convert a set of type codes to a class
  • Convert a set of type codes to a class with subclasses
  • Change an array to an object
  • Encapsulate a collection ⇐
  • Replace a traditional record with a data class
  • Statement Level Refactorings
  • Decompose a boolean expression
  • Move a complex boolean expression into a well-named boolean function
  • Consolidate fragments that are duplicated within different parts of a conditional
  • Use break or return instead of a loop control variable
  • Return as soon as you know the answer instead of assigning a return value within nested if-then-else statements
  • Replace conditionals with polymorphism (especially repeated case statements) ⇐
  • Create and use null objects instead of testing for null values
  • Routine Level Refactorings
  • Extract a routine
  • Move a routine's code inline
  • Convert a long routine to a class
  • Substitute a simple algorithm for a complex algorithm
  • Add a parameter
  • Remove a parameter
  • Separate query operations from modification operations
  • Combine similar routines by parameterizing them
  • Separate routines whose behavior depends on parameters passed in ⇐
  • Pass a whole object rather than specific fields
  • Pass specific fields rather than a whole object
  • Encapsulate downcasting ⇐ 


Class Implementation Refactorings

  • Change value objects to reference objects
  • Change reference objects to value objects
  • Replace virtual routines with data initialization
  • Change member routine or data placement
  • Extract specialized code into a subclass ⇐
  • Combine similar code into a superclass
  • Class Interface Refactorings
  • Move a routine to another class
  • Convert one class to two
  • Eliminate a class
  • Hide a delegate ⇐
  • Replace inheritance with delegation
  • Replace delegation with inheritance
  • Remove a middle man ⇐
  • Introduce a foreign routine
  • Introduce a class extension
  • Encapsulate an exposed member variable
  • Remove Set() routines for fields that cannot be changed
  • Hide routines that are not intended to be used outside the class
  • Encapsulate unused routines ⇐
  • Collapse a superclass and subclass if their implementations are very similar
  • System Level Refactorings
  • Duplicate data you can't control ⇐
  • Change unidirectional class association to bidirectional class association
  • Change bidirectional class association to unidirectional class association
  • Provide a factory routine rather than a simple constructor
  • Replace error codes with exceptions or vice versa



Friday, October 18, 2013

How does Facebook set cross-domain cookies for iFrames on canvas pages?

I was browsing Facebook's documentation reading about canvas applications and I came across an example application: http://developers.facebook.com/docs/samples/canvas. As I read through their example, however, I got very confused about their use of cookies in the iframe application.

A little backstory...

I had already played around with using iframes for embeddable widgets (unrelated to Facebook) and I found out a few browsers (Chrome, Safari, etc.) have strict cookie policies and don't allow cross-domain cookies set in iframes (Firefox, on the other hand, allows iframes to set cross-domain cookies in iframes). For example, if foo.com has an iframe with src="http://bar.com/widget" the iframe widget will not be able to set any cookies for bar.com and therefore will have trouble persisting state within the iframe: bar.com will interpret every request (including ajax requests) from the widget as a fresh request without an established session. I struggled, and found a way around this by using JSONP and javascript to set cookies for foo.com instead...

... and so?

Well, I was looking at the example canvas iframe Facebook application and I noticed that their application (hosted on runwithfriends.appspot.com) is able to set a cookie, u, with the current user's id along with a few other parameters for the runwithfriends.appspot.com domain. It sends this cookie with every request... and it works in both Chrome and Firefox! WTF? How does Facebook get around the cross-domain cookie restrictions on Chrome?

(I already know the answer now, but I thought this might be helpful for anyone struggling to figure out the same thing)

So the iFrame isn't actually setting the u cookie for the runwithfriends.appspot.com domain. What Facebook does is it creates a form, and uses javascript to submit the form on page load. Since the form's target is the iframe, it doesn't reload the page... it just loads the iframe with the POST's response. Apparently even Chrome and other browsers with strict cookie policies set cookies for cross domain requests if they are POST requests...


As you can see the answer is simple, and could be implemented by just creating a handler (could be a Servlet or anything that can catch some parameterts and transform them into cookies), like this:

Sunday, December 16, 2012

New features in JDBC 3.0

This article provides an introduction to the array of core new features available in JDBC 3.0. More specifically, the features ‘supporting save points’, ‘using parameter metadata’, ‘updating large objects’ and ‘auto generated keys’ are discussed. Wherever possible, to get a hang of it, relevant code samples have been provided in the respective sections.

Defining savepoints
It is possible to programmatically control the creation and releasing of save points through JDBC 3.0. But before doing it, one must check whether the underlying database supports the concepts of savepoints. Save points provide multiple-level-control of database commit or rollback operations within a single transaction. For example, if two unrelated database operations have to happen with a single transaction, these two save points can be created for the very purpose. Then based on various business conditions, commit/rollback can be done to any of these save points within the same transaction. To illustrate the usage, consider the following example: As seen from the above example, the program checks whether save points are supported by the target database by querying methods available in DatabaseMetadata. Note for save points are created by calling the method setSavePoint() defined on the Connection object. A save point can be given a name so that at a later point of time, a transaction can be made to commit or rollback based on the name. In the example code, to illustrate the usage of save point, we deliberately rollback the operation related to customer table, whereas, the changes made to country table are committed.

Parameter Metadata
Construction of queries for statements such as prepared statements might involve specifying dynamic values through ‘?’. Previously, there was no support for the tools or for the applications to identify the parameter information embedded in the queries. Now, support has been added to retrieve the parameter information that is passed to prepared statements. Please refer the below code that illustrates the usage: Auto Generated Keys
Execution of queries sometimes results in the automatic generation of fields or values for tables. The behavior is entirely dependent on the underlying database implementation. Previously, there was no standard mechanism for retrieving such information once the query is executed. Application developers are forced to use non-standard mechanisms for fetching information that happens outside the scope of query execution. For example, consider a table column containing a particular column, say ‘name’, and an equivalent upper column, let’s say ‘upper_name’. The value for the ‘upper_name’ will be automatically populated as soon as the value is populated for the ‘name’ column. This is one of the examples of auto generation feature and the newer specification supports this feature. Refer the code sample below: Note that, while executing the statement, the application has to provide indication to the underlying engine that, if any auto generation columns are applicable once the query is executed, those information have to be made available in the equivalent statement object. This is done through the method Statement.execute() where the second parameter specifies this option. Next, the method getGeneratedKeys() is added to the Statement object which returns a ResultSet containing the desired values. Because, this feature may or may not be supported by the database engine, the API supportsGeteGeneratedKeys() can be used to check the feature availability.

Updating clob/blob objects
The support to update clob objects is directly available on the Clob/Blob objects. The method updateClob() is added to the ResultSet object. Previously, there is no standard way to update large data objects. Note to ensure that this works and because the operation is defined on the ResultSet, the underlying ResultSet object should support updating the record. This is possible if the ResultSet is a flavor of CONCUR_UPDATABLE. Please refer the below code Conclusion
The new features in JDBC 3.0 have addressed most of the common problems that tools or developer community is encountering, thereby providing a unified way of solution. There are other minor updates done to JDBC 3.0, such as ‘configuring connection pools’, ‘adding of new data types as Boolean, Datalink, URL’ etc.

Saturday, November 3, 2012

Load Properties File with ClassLoader

For those who want to load a Properties file located in the classpath (could be the classpath of your server: Far from your artifact), this is how a Properties Files is loaded "like a Sir!"


Simple! Instead of using the traditional way
getClass().getResourceAsStream(propertiesFile);

By doing it in that way, we make sure the ClassLoader will look further into the classpath other than just look in the near surroundings :P

Monday, October 29, 2012

Interacting with Facebook using Java

If it's your first time interacting with Facebook, probably you haven't found many examples in Java, have you?
On my case I'm working with something really simple, I just need to create a simple app that will be configured as Canvas. There are 2 important steps in order to work with Facebook by using Canvas:

1. Authorization 
When Facebook calls your webpage (on my case a jhtml using SEAM - it could be a JSP as well), it will send through POST something called signed_request, for more details please read this The signed_request parameter is the concatenation of a HMAC SHA-256 signature string, a period (.), and a base64url encoded JSON object. It looks something like this (without the newlines):

vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso
.
eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIn0

Just by receiving this parameter, it means that you (as facebook user) just authorized this app on your account, otherwise you'll get the classic mesage asking for your permission to use this app.

Next, we need to retrieve from the JSON object 2 parameters that we need to do the authentication: oauth_token and expires).
However, in order to play around with JSON object, we need to decode it, and this will do the trick: It's very important to use sun.misc.BASE64Decoder in order to avoid missing few characters when decoding with other classes. Belive me, this save you from a lot of headeaches. I'm a big fan of Commons, however, it didn't work out really good when decoding this JSON object. FYI, this is my method.

2. Authentication 
This step is really easy, because based on attributes oauth_token and expires, we have a to make a http call to https://graph.facebook.com/me in order to authenticate into FB.
As result of my http call, by using the JSON object returned, I'm able to get more details about this FB account, such as email, first name, last name, age, languages, among others. The next steps depend how deep you want to go.
Good luck!

Saturday, September 15, 2012

Keep parameter in session with Injection and Outjection

This time something kind of weird happened to me.

To be honest, each time I have to work with Jboss Seam, I always say to myself: "I wonder what kind of surprise waits for me this time". Because I'm a Spring Framework dude, and JBoss Seam documentation, well, is not really clear at all.

This is my case:
I have a page that receives a parameter from an external source, the page is displayed, user pays around with it, page gets refreshed a lot of times. And then, user submits page and everything and goes away, then is when I need that parameter received at the beginning. Because after the submit I have to pass it to another page which need it

The solution will be something like: come on dude! that's Servlets 101. Just set the parameter in the session the first time and that's it! Now the question is, what happens to that value set into the session? Because I want to use it on my pages.xml file to redirect the request to another page though!
And, very important, I want to write as less code as possible (by using Seam Annotations)

But better if we see some code:

The param received (passed by an external caller) is:
By doing this I'm keeping in Session this variable:
Very important to keep the parameter stored in session only once during page Creation!

This is my pages.xml, where I'm passing as param resume the value of my In/Outjected variable resumePersistentParam


Monday, August 20, 2012

Hibernate – Fetching Strategies Examples

Hibernate has few fetching strategies to optimize the Hibernate generated select statement, so that it can be as efficient as possible. The fetching strategy is declared in the mapping relationship to define how Hibernate fetch its related collections and entities.

Fetching Strategies

There are four fetching strategies
  • fetch-”join” = Disable the lazy loading, always load all the collections and entities.
  • fetch-”select” (default) = Lazy load all the collections and entities.
  • batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
  • fetch-”subselect” = Group its collection into a sub select statement.

For detail explanation, you can check on the Hibernate documentation.

Fetching Strategies Examples

Here’s a “one-to-many relationship” example for the fetching strategies demonstration. A stock is belong to many stock daily records.

Lets explore how fetch strategies affect the Hibernate generated SQL statement.

Fetch=”Select” Or @Fetch(FetchMode.SELECT)

This is the default fetching strategy. it enabled the lazy loading of all it’s related collections.

Output:
Hibernate: 
    select ...from mkyong.stock
    where stock0_.STOCK_ID=?
 
Hibernate: 
    select ...from mkyong.stock_daily_record
    where stockdaily0_.STOCK_ID=?

Hibernate generated two select statements
1. Select statement to retrieve the Stock records -session.get(Stock.class, 114)
2. Select its related collections – sets.iterator()

Fetch=”Join” Or @Fetch(FetchMode.JOIN)

The “join” fetching strategy will disabled the lazy loading of all it’s related collections.

Output:
Hibernate: 
    select ...
    from
        mkyong.stock stock0_ 
    left outer join
        mkyong.stock_daily_record stockdaily1_ 
            on stock0_.STOCK_ID=stockdaily1_.STOCK_ID 
    where
        stock0_.STOCK_ID=?

Hibernate generated only one select statement, it retrieve all its related collections when the Stock is initialized. -session.get(Stock.class, 114)
1. Select statement to retrieve the Stock records and outer join its related collections.

Batch-Size=”10″ Or @BatchSize(Size = 10)

This ‘batch size’ fetching strategy is always misunderstanding by many Hibernate developers.

What is your expected result, is this per-fetch 10 records from collection? See the Output
Hibernate: 
    select ...from mkyong.stock
    where stock0_.STOCK_ID=?
 
Hibernate: 
    select ...from mkyong.stock_daily_record
    where stockdaily0_.STOCK_ID=?

The batch-size did nothing here, it is not how batch-size work. See this statement.
The batch-size fetching strategy is not define how many records inside in the collections are loaded. Instead, it defines how many collections should be loaded.
— Repeat N times until you remember this statement —

You want to print out all the stock records and its related stock daily records (collections) one by one.
No batch-size fetching strategy
Output:
Hibernate: 
    select ...
    from mkyong.stock stock0_
 
Hibernate: 
    select ...
    from mkyong.stock_daily_record stockdaily0_ 
    where stockdaily0_.STOCK_ID=?
 
Hibernate: 
    select ...
    from mkyong.stock_daily_record stockdaily0_ 
    where stockdaily0_.STOCK_ID=?
 
Keep repeat the select statements....depend how many stock records in your table.

If you have 20 stock records in the database, the Hibernate’s default fetching strategies will generate 20+1 select statements and hit the database.

1. Select statement to retrieve all the Stock records.
2. Select its related collection
3. Select its related collection
4. Select its related collection
….
21. Select its related collection
The generated queries are not efficient and caused a serious performance issue.


Enabled the batch-size=’10′ fetching strategy
Let see another example with batch-size=’10′ is enabled.
Output:
Hibernate: 
    select ...
    from mkyong.stock stock0_
 
Hibernate: 
    select ...
    from mkyong.stock_daily_record stockdaily0_ 
    where
        stockdaily0_.STOCK_ID in (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )

Now, Hibernate will per-fetch the collections, with a select *in* statement. If you have 20 stock records, it will generate 3 select statements.
1. Select statement to retrieve all the Stock records.
2. Select In statement to per-fetch its related collections (10 collections a time)
3. Select In statement to per-fetch its related collections (next 10 collections a time)

With batch-size enabled, it simplify the select statements from 21 select statements to 3 select statements.

Fetch=”Subselect” Or @Fetch(FetchMode.SUBSELECT)

This fetching strategy is enable all its related collection in a sub select statement.

Output:
Hibernate: 
    select ...
    from mkyong.stock stock0_
 
Hibernate: 
    select ...
    from
        mkyong.stock_daily_record stockdaily0_ 
    where
        stockdaily0_.STOCK_ID in (
            select
                stock0_.STOCK_ID 
            from
                mkyong.stock stock0_
        )

With “subselect” enabled, it will create two select statements.
1. Select statement to retrieve all the Stock records.
2. Select all its related collections in a sub select query.



Conclusion The fetching strategies are highly flexible and a very important tweak to optimize the Hibernate query, but if you used it in a wrong place, it will be a total disaster (You're screwed dude!).


Tuesday, July 31, 2012

OneToMany Relation with Non PK Columns

While goofing around @ my office my Boss told me about an issue he was facing while trying to map a OneToMany relation, but instead of using the classical PK on one side and FK on the other side, he wanted to define the relationship between tables with nonKey columns. I still don't know why but this situation reminded me when I was having a hard time playing with 1:1 relations.
Anyway the fact is that we need find a workaround for this, and as is well known if you don't define anything on Hibernate (Annotations), by default is going to use the default values, right?

My approach is simple, by just defining after the OneToMany annotation which columns I'll join, in order to get this Set. Probably my Child table has a PK which doesn't have anything to do with the column I'm using to do the join with the Parent (which is a valid scenario - and BTW is what's happening now) Why don't you give it a try! On my case one of colleagues tried and I got another satisfied customer ;)

Friday, April 13, 2012

Delegate to Seam the management of my JBPM4 engine

The problem was really simple, it's just implement a Singleton without writing it :P

I have a simple class, but I just need it to be loaded when the app starts, because my class will load the JBPM4 engine (and that should be done only once - this process may take up to 4 seconds, which will make really slow the first request coming to my End-Point)
But let me write more code and less words
Just add to your class these tags
Define which method will be your Creation method (Initialization method), on my case the one which will load the Engine
Now the one which will Destroy your class (shutdown my JBPM4 engine) and release resources
and optionally, your Constructor

Simple, Isnt' it?
Now you can inject this Seam Component using Injection into another Seam Component, just like this


Wednesday, March 21, 2012

Fix javax.ejb.NoSuchEJBException: Could not find stateful bean on Seam and JBPM4

When I was using Google to look for answers to my problem, I found a lot of posts asking for a solution, just like me, but not a concrete answer (IMHO, JBoss has really poor documentation, compared with Spring, even their forums have less information), like this case

But I got a solution!!! (u_u)
Let me tell you my story...

On one of my Handlers I was using a ServiceImpl, just like this:
This is my ServiceImpl
And my getSeamComponentInstance method

As you can see, this doesn't have anything really weird, I just injecting a Bean into another class, and invoke one its methods! Simple (pure DI)

When you test it, it works! After it's been deployed, it works again, but...

After some period of inactivity... Boooom! The same line of code (the one where I invoke one of the methods of my ServiceImpl) was throwing an this
javax.ejb.NoSuchEJBException: Could not find stateful bean: 4sg5nl-4371oh-gsvwkdiv-1-gsvwst2j-1b
 at org.jboss.ejb3.cache.simple.SimpleStatefulCache.get(SimpleStatefulCache.java:492)
 at org.jboss.ejb3.cache.simple.SimpleStatefulCache.get(SimpleStatefulCache.java:443)
 at org.jboss.ejb3.stateful.StatefulInstanceInterceptor.invoke(StatefulInstanceInterceptor.java:61)
 at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
 at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:77)
 at org.jboss.ejb3.security.Ejb3AuthenticationInterceptor.invoke(Ejb3AuthenticationInterceptor.java:106)
 at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
 at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:46)
 at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
 at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
 at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
 at org.jboss.ejb3.stateful.StatefulContainer.localInvoke(StatefulContainer.java:204)
 at org.jboss.ejb3.stateful.StatefulLocalProxy.invoke(StatefulLocalProxy.java:117)
 at $Proxy81.afterTransactionRollback(Unknown Source)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
 at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
 at org.jboss.seam.intercept.ClientSideInterceptor$1.proceed(ClientSideInterceptor.java:76)
 at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
 at org.jboss.seam.intercept.ClientSideInterceptor.invoke(ClientSideInterceptor.java:54)
 at org.javassist.tmp.java.lang.Object_$$_javassist_seam_5.afterTransactionRollback(Object_$$_javassist_seam_5.java)
 at org.jboss.seam.transaction.UTTransaction.rollback(UTTransaction.java:70)
 at org.jboss.seam.util.Work.workInTransaction(Work.java:68)
 at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91)
 at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
 at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
 at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
 at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
 at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
 at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
 at com.kaplan.service.impl.StudentDetailsServiceImpl_$$_javassist_seam_11.updateStudentDetails(StudentDetailsServiceImpl_$$_javassist_seam_11.java)
 at com.kaplan.jbpm.action.integration.jbpm4.UpdateStudentActionHandler.execute(UpdateStudentActionHandler.java:44)
 at org.jbpm.pvm.internal.wire.usercode.UserCodeActivityBehaviour.execute(UserCodeActivityBehaviour.java:42)
 at org.jbpm.pvm.internal.model.op.ExecuteActivity.perform(ExecuteActivity.java:60)
 at org.jbpm.pvm.internal.model.ExecutionImpl.performAtomicOperationSync(ExecutionImpl.java:672)
 at org.jbpm.pvm.internal.model.op.ExecuteActivityMessage.executeVoid(ExecuteActivityMessage.java:45)
 at org.jbpm.pvm.internal.job.MessageImpl.execute(MessageImpl.java:46)
 at org.jbpm.pvm.internal.job.MessageImpl.execute(MessageImpl.java:32)
 at org.jbpm.pvm.internal.cmd.ExecuteJobCmd.execute(ExecuteJobCmd.java:79)
 at org.jbpm.pvm.internal.cmd.ExecuteJobCmd.execute(ExecuteJobCmd.java:41)
 at org.jbpm.pvm.internal.svc.DefaultCommandService.execute(DefaultCommandService.java:42)
 at org.jbpm.pvm.internal.tx.StandardTransactionInterceptor.execute(StandardTransactionInterceptor.java:50)
 at org.jbpm.pvm.internal.svc.EnvironmentInterceptor.executeInNewEnvironment(EnvironmentInterceptor.java:53)
 at org.jbpm.pvm.internal.svc.EnvironmentInterceptor.execute(EnvironmentInterceptor.java:40)
 at org.jbpm.pvm.internal.svc.RetryInterceptor.execute(RetryInterceptor.java:56)
 at org.jbpm.pvm.internal.svc.SkipInterceptor.execute(SkipInterceptor.java:43)
 at org.jbpm.pvm.internal.jobexecutor.JobParcel.run(JobParcel.java:48)
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
 at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
 at java.lang.Thread.run(Thread.java:619)

WTF!!!

What!!! I'm not even using stateful beans!!!, I'm using plain POJO's not even stateless!
This is how it works Seam, when you inject a Component using Components.getInstance, you just get a Proxy, and that proxy references the REAL instance of the class you want to invoke, but for any weird reason, that instance it has been removed! Then, why the freaking Proxy points to a nonexistent object? No idea (u_u).

Let's force Seam to create a new instance if it doesn't exist and specify that I don't want a Stateful bean by passing the scope Stateless (you can try with another one, but Stateless seems to be working just fine) and this is it


And after 1 night of inactivity, the error was gone (one for the team!)

Wednesday, January 18, 2012

Migrating to JBPM4

As you well know, I was using for one of my projects JBPM3, but then I decided to to jump into something more stable and even cool! (which will give me more automatization and the ability to recover from server crashes - in other words, restart a process previously interrupted :) )

The API changed completely, some classes were renamed others were removed, methods are not the same, configuration is different, in a few words "It doesn't have any relation with the previous version"

Cons:


You won't be able to keep your logs or comments on your tables, no more Transient variables, no more stoping process due to Exceptions, no more suspend or resume process (using the API), poor history of each execution - but it really helps what you see (if you want more details, I recommend you to use wisely your Log4J), if you don't believe me, look at my base handler after I migrated


Pros:


Process definition is the same file which describes de Diagram spec (no more hidden files), configuration file is much simpler (the default params work really nice - It's almost ready for production out of the box), hibernate configuration is much easy to read, process could be started easily by using code (FEWER lines that in JBPM3), ASYNC process really work!, resume processes interrupted, you can define a business key for each execution - look into table JBPM4_HIST_PROCINST, Timer really works! - you'll see it on my process definition

This is how I started my process (due to my process is ASYNC, it doesn't wait until process is completed to return a response - which is great for Fire and Forget, obviously the first request will be the one which takes longer, because it will have to wait until everything is loaded but the next request will be super fast! - I've seen and Avg. of 70ms)

My process definition is cleaner and I really like it


Finally, let me show you a couple of Handlers, except for a few changes, I didn't change them a lot compared with my original JBPM3 code :) Cool beans!

Saturday, December 3, 2011

ClassCastException with Hibernate: org.hibernate.type.DateType cannot be cast to org.hibernate.type.VersionType

I ran into a weird error when starting a Seam App with JPA (Hibernate) on JBoss

2011-08-03 14:30:17,938 [main] ERROR [org.jboss.deployment.scanner.URLDeploymentScanner] Incomplete Deployment listing:

--- MBeans waiting for other MBeans ---
ObjectName: persistence.units:ear=mainsite.ear,jar=kaptest_domain.jar,unitName=commonDatabase
  State: FAILED
  Reason: java.lang.ClassCastException: org.hibernate.type.DateType cannot be cast to org.hibernate.type.VersionType
  I Depend On:
    jboss.jca:service=DataSourceBinding,name=jdbc.CommonTransactionDS
  Depends On Me:
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=AdobeMeetingDAO_Seam_Impl,service=EJB3
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=AdobeProductDAO_Seam_Impl,service=EJB3
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=AdobeUserDAO_Seam_Impl,service=EJB3
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=AverageRatingServiceImpl,service=EJB3
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=BookstoreProductServiceImpl,service=EJB3
    jboss.j2ee:ear=mainsite.ear,jar=kaptest_domain.jar,name=BookstoreSearchServiceImpl,service=EJB3
...
...
WHAT??? java.lang.ClassCastException: org.hibernate.type.DateType cannot be cast to org.hibernate.type.VersionType

Anyway, for some reason, hibernate reverse engineer puts the @Version annotation to fields called timestamp as it expects it to be of type java.sql.Timestamp
Unfortunatly, my property was of type java.util.Date which is incomaptible with the @Version annotation.
I removed the @Version and it worked!

Saturday, October 15, 2011

My first encounter with jBPM


Long story, short story. When I was working in one of my projects in Mexico, somebody mentioned something about BPM or BPEL and how practical de idea/concept was, because now we can mix the knowledge of the Business People with the Developers, by using some kind of cool diagrams to do Process Modeling.

And now I had to create a project which essentially it's a WorkFlow but we need some features like keeping the state of each execution (so we can trace it easily and resume the process if by any chance is stopped) "et all" and then, when I saw that One of the requirements was to integrate this miniworkflow with an existing App deployed on jBoss 4 with Seam 2.1 (I'd talk later about this framework, for all those like me who love Spring Framework), then I have to use jBPM 3 instead of 4 or 5 OUCH :'(
"But then, I realize that JBPM4 can work flawlessly on JBoss 4"
What do we need???
No much, Eclipse Helios (3.6)
Install these features:

  • JBoss Tools - http://download.jboss.org/jbosstools/updates/development/helios (don't forget to install jBPM support!)
  • Graphiti - http://download.eclipse.org/graphiti/updates/0.7.1
  • BPMN2 - http://codehoop.com/bpmn2


The concept is really simple, we just need to model the flow (I'll use the Designer to do this)


But it needs some logic inside its guts, so I'll add something called Handlers and some personalized tags (which is a really cool feture)
This is our model translated into XML
On my implementation, the process will run by itself, it's going to be a "FIRE AND FORGET";

On my case the process will wait for a certain amount of time and the it will start, it'll make one decision and it will execute something and then the End :)

The logic will be implemented by Implementing some Interfaces:



And Voila!!!

Soon I'll talk a little bit about jBoss SEAM! (How I implemented a REST Service FACILITO!)

Thursday, October 6, 2011

Debugging App Server Remotely

When I was working with an external/existing jBoss App Server Instance, I had an issue and I needed to debug something, so I had 2 options in my head:

  1. Create an internal instance (managed by my IDE: Eclipse) and do all the work there, for example like in Spring Source Tool Suite aka STS (which has its own App Server Integrated) or IBM RAD (which has its own version embedded of WebSphere)
  2. Put a bunch of DEBUG's on my Log4'j config and trace them through my Console

And then playing around with my IDE, I found something really cool on the Debugging perspective of my Eclipse:

Click on Debug Configurations and you'll see a window like this one (Bind this configuration to your project)




Then, go to Remote Java Application, create a new Configuration
On the Connect tab, give a name select the Standard Connction type and in the Connection Properties give the location of your server and the "debugging" port (on my case is 5005)

Why port 5005? Well, on my jBoss setup I found this option on its configuration:
JAVA_OPTS="$JAVA_OPTS -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
By doing this, you'll enable debugging port on your JVM :D (Cool isn't it?)


On "source tab", select Add your project (the one which is running on your App Server)
And in "common tab" check the Debug option, finally, Apply and you're ready to rock!


Now, after you'd started your App Server you can debug your current (running) App in your Eclipse by clicking on Debug Icon and selecting the configuration we just created!

Good luck and have fun!