A lot of folks new to Groovy quickly ask the question, "What's is the GDK?" or "What's the difference between the GDK and the JDK?"
If you take a look thru the GDK documentation, you will see that the GDK acts like an extension to the Java JDK. New methods are added to the GDK help remove the ceremony and allow Groovy code to be short and concise. Think of it as a big decorator pattern! Slight clarification: the JDK is used to build the GDK and referenced by the GDK but it is NOT part of the GDK and not shipped with the GDK.
Maybe a picture will help. You can see some of the new GDK methods added to the Java classes below.
Hope this helps!
Monday, July 16, 2012
Saturday, July 14, 2012
JBoss AS7 JNDI & EJB 3.1 Naming changes
As a result of the "feature train" continuing to march on and us not keeping our software stack up-to-date, our team finds ourselves in the un-enviable position of having to migrate:
AS7 and EJB 3.1
The EJB 3.1 spec has made some changes to mandate portable JNDI names for EJBs and you inherit this in AS 7.1.1. The other tricky thing I found was that I could no longer use the exact same lookup code from our remote clients and the server.
AS 7 now has two options for remote EJB invocation. The information you need can be found in the JBoss docs, it just didn't hit me over the head! After struggling with this issue for a couple days, I decided to create a small program to help make the differences (hopefully) very clear. Below is the program that I created to invoke a stateless session bean from a remote client. I deployed the "ejb-remote" sample from the 7.1 Quick Start samples. The code attempts to load the remote service using both remote methods. The expectation is that for the first set of lookups, the first lookup is successful and the second, using the "ejb:/" naming format fails. Then I add the Context.URL_PKG_PREFIXES property with a value of "org.jboss.ejb.client.naming" to the jndi properties passed to the InitialContext constructor and repeat the lookups. Now, both lookups should be successful. I have included all the JNDI properties in the code rather than relying on a copy of "jboss-ejb-client.properties" or "jndi.properties" being picked up from the classpath.
- JBoss 4.2.3 to AS 7.1.x (currently looking at 7.1.1)
- EJB 2.1 to EJB 3.1
- Hibernate 2 to Hibernate 3 or 4
in quick fashion. I mean, who wants to ship a new release with 8-10 year old software, not me!
The following is the result of some research I did while looking at upgrading from JBoss 4.2.3 with EJB 2.1 to AS 7.1.x with EJB 3.1. I am sure there will be more posts related to this migration in the near future, but this one is related to changes in the JNDI naming area.
In the past/current
In our current code, the JNDI naming has been very simple:
- We concatenated "ejb/" with the name of the remote Session Bean interface in the deployment descriptor to indicate the name that the service should be bound to.
- In the code, we use the following code to handle the JNDI lookup. The really nice part was that the same code could be used by remote clients AND on the server, within the container.
Current Code
Hashtable properties = new Hashtable();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url", "jnp://localhost:1099");
Context ctx = new InitialContext(properties);
Object ref = ctx.lookup(jndiName);
AS7 and EJB 3.1
The EJB 3.1 spec has made some changes to mandate portable JNDI names for EJBs and you inherit this in AS 7.1.1. The other tricky thing I found was that I could no longer use the exact same lookup code from our remote clients and the server.
AS 7 now has two options for remote EJB invocation. The information you need can be found in the JBoss docs, it just didn't hit me over the head! After struggling with this issue for a couple days, I decided to create a small program to help make the differences (hopefully) very clear. Below is the program that I created to invoke a stateless session bean from a remote client. I deployed the "ejb-remote" sample from the 7.1 Quick Start samples. The code attempts to load the remote service using both remote methods. The expectation is that for the first set of lookups, the first lookup is successful and the second, using the "ejb:/" naming format fails. Then I add the Context.URL_PKG_PREFIXES property with a value of "org.jboss.ejb.client.naming" to the jndi properties passed to the InitialContext constructor and repeat the lookups. Now, both lookups should be successful. I have included all the JNDI properties in the code rather than relying on a copy of "jboss-ejb-client.properties" or "jndi.properties" being picked up from the classpath.
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;
public class EJBClient {
private static String[] JNDINAME = {
"jboss-as-ejb-remote-app/CalculatorBean!org.jboss.as.quickstarts.ejb.remote.stateless.RemoteCalculator",
"ejb:/jboss-as-ejb-remote-app/CalculatorBean!org.jboss.as.quickstarts.ejb.remote.stateless.RemoteCalculator"
};
private Hashtable jndiProps;
public EJBClient() {
// setup 'base' jndi properties - no jboss-ejb-client.properties being picked up from classpath!
jndiProps = new Hashtable();
jndiProps.put("java.naming.factory.initial","org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(InitialContext.PROVIDER_URL, "remote://localhost:4447");
jndiProps.put("jboss.naming.client.ejb.context", true);
// needed for remote access - remember to run add-user.bat
jndiProps.put(Context.SECURITY_PRINCIPAL, "client");
jndiProps.put(Context.SECURITY_CREDENTIALS, "password");
}
public void doLookups() {
// the 'exported' namespace
for (int i = 0; i < JNDINAME.length; i++) {
lookup(JNDINAME[i]);
}
// This is an important property to set if you want to do EJB invocations via the remote-naming project
jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
// now with the ejb
for (int i = 0; i < JNDINAME.length; i++) {
lookup(JNDINAME[i]);
}
}
private void lookup(String name) {
System.out.println("Lookup name="+name);
Context ctx = null;
try {
ctx = new InitialContext(jndiProps);
Object ref = ctx.lookup(name);
System.out.println("...Successful");
} catch (NamingException e) {
System.out.println("...Failed");
//System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {}
}
}
}
public static void main(String[] args) throws Exception {
EJBClient client = new EJBClient();
client.doLookups();
System.out.println("Done!");
}
}
AS7 on the server-side
Now the easy part, doing the JNDI lookups on the server are very similar to the old way, except that you still need to format the JNDI name according to the new specs and the naming factory is no longer the jnp version!
Now the easy part, doing the JNDI lookups on the server are very similar to the old way, except that you still need to format the JNDI name according to the new specs and the naming factory is no longer the jnp version!
Hashtable jndiProps = new Hashtable();
jndiProps.put("java.naming.factory.initial", "org.jboss.as.naming.InitialContextFactory");
ctx = new InitialContext(jndiProps);
Object ref = ctx.lookup(jndiName);
Conclusion
As I said earlier, the information was/is in the JBoss documentation, but I probably read past it several times. What I was looking for was an example showing loading the EJBs from both the client and the server.
Hope this helps!
As I said earlier, the information was/is in the JBoss documentation, but I probably read past it several times. What I was looking for was an example showing loading the EJBs from both the client and the server.
Hope this helps!
Sunday, March 25, 2012
Ajax Examples upgraded to Grails 2.0.0
Overview
A little over a year ago, I wrote a blog posting providing a complete set of working code showing ajax examples for each of the Grails tags that supports Ajax. Now, I finally found time to upgrade that code to Grails 2.0.0 (from Grails 1.3.7). There are plenty of article out there helping point users in the right direction when upgrading to Grails 2.0.0 and most of them are helpful. Seems like no one wants to RTFM, we just want to get at it! My recommendation is RTFM, and checkout some of the helpful postings out there, especially when the upgrade includes as many changes and new features as Grails 2.0.0.
I have to confess, I tried to just "get at it" with my ajax application and Grails 2.0.0 and it got me part of the way there. To finish the job, I needed to read the excellent documentation produced by the Grails team and also the documentation accompanying some of the plugins.
Steps for my upgrade
In order to get my application running under Grails 2.0, I needed 5 basic steps:
Step 2
Follow Peter Ledbrook's instructions on upgrading the persistence layer to use H2 database instead of the HSQLDB. If you want to continue to use HSQLDB, there are instructions for that too!
Hope this helps!
A little over a year ago, I wrote a blog posting providing a complete set of working code showing ajax examples for each of the Grails tags that supports Ajax. Now, I finally found time to upgrade that code to Grails 2.0.0 (from Grails 1.3.7). There are plenty of article out there helping point users in the right direction when upgrading to Grails 2.0.0 and most of them are helpful. Seems like no one wants to RTFM, we just want to get at it! My recommendation is RTFM, and checkout some of the helpful postings out there, especially when the upgrade includes as many changes and new features as Grails 2.0.0.
I have to confess, I tried to just "get at it" with my ajax application and Grails 2.0.0 and it got me part of the way there. To finish the job, I needed to read the excellent documentation produced by the Grails team and also the documentation accompanying some of the plugins.
Steps for my upgrade
In order to get my application running under Grails 2.0, I needed 5 basic steps:
- Run the 'grails upgrade' against my project.
- Upgrade database to use H2 - instructions under Persistence here
- Install plugins: prototype and resources plugin.
- Modify the main.gsp layout to accommodate the plugins (resource, prototype).
- Modify Config.groovy to set the java script library to prototype.
Step 1
This step is required for any application being upgraded from an earlier version of Grails. I am not going to say anything else about this step.
Step 2
Follow Peter Ledbrook's instructions on upgrading the persistence layer to use H2 database instead of the HSQLDB. If you want to continue to use HSQLDB, there are instructions for that too!
Step 3
I consider myself 'javascript-challenged', so I decided to stick with the prototype library for javascript for this upgrade rather than attempting to use jQuery, which is the new default library. If all goes well and I get some free time, maybe I will upgrade the application to use jQuery too, but for now, I am sticking with prototype - less changes too!
Make sure the plugins are installed, and then verify that they all got installed successfully (last statement).
Make sure the plugins are installed, and then verify that they all got installed successfully (last statement).
grails install-plugin resources grails install-plugin prototype grails list-plugins -installed
Step 4
One of the tricky parts here was including plugin="prototype" on the javascript tag in the header section of this page. Below is a copy of my layout\main.gsp. (Be careful using cut/paste on the page below, I had problems with the syntax highligher or blogger (not sure which) adjusting my html tags as it sees fit). Best option, grab the code from GitHub. Also be sure to understand the changes needed for the Resources Plugin.
The project has been updated and now available on GitHub.One of the tricky parts here was including plugin="prototype" on the javascript tag in the header section of this page. Below is a copy of my layout\main.gsp. (Be careful using cut/paste on the page below, I had problems with the syntax highligher or blogger (not sure which) adjusting my html tags as it sees fit). Best option, grab the code from GitHub. Also be sure to understand the changes needed for the Resources Plugin.
<g:layoutTitle default="Grails" />
function showSpinner(visible) {
$('spinner').style.display = visible ? "inline" : "none";
}
Ajax.Responders.register({
onLoading: function() {
showSpinner(true);
},
onComplete: function() {
if(!Ajax.activeRequestCount) showSpinner(false);
}
});
Step 5
Update Config.groovy to define prototype as the javascript library to use.
Update Config.groovy to define prototype as the javascript library to use.
... grails.views.javascript.library = "prototype" ...
Hope this helps!
Monday, January 30, 2012
Book Review: Programming Concurrency on the JVM
Overview
Programming concurrency is a tough task to get right, just ask Venkat, he'll tell you so! I attended a presentation by Dr. Venkat Subramaniam on this very subject, Concurrency on the JVM, at my local Java user group a couple months ago and he really caught my attention. The presentation was a condensed version of the book, and needless to say, I bought the book to help fill in all the details.
Not only is Venkat a 'subject matter expert', but his presentation kept everyone engaged and laughing!
Contents:
The book is broken down in 5 parts, with 10 chapters total, at just over 250 pages. The main sections of the book are:
Summary
This is a good book to get you started on some of these newer concurrency concepts and libraries. It was an easy read, and I completed the reading fairly quickly, as opposed to the "Java Concurrency in Practice" book, which I started and stopped twice and still have not completed yet!
I would recommend this book to anyone looking to improve their programming skills in the concurrency area. The book provides you with some alternatives to the old standby of ' Synchronize and Suffer' model.
My last recommendation, if you get the opportunity, attend one of Venkat's presentations, you won't be sorry!
Programming concurrency is a tough task to get right, just ask Venkat, he'll tell you so! I attended a presentation by Dr. Venkat Subramaniam on this very subject, Concurrency on the JVM, at my local Java user group a couple months ago and he really caught my attention. The presentation was a condensed version of the book, and needless to say, I bought the book to help fill in all the details.
Not only is Venkat a 'subject matter expert', but his presentation kept everyone engaged and laughing!
Contents:
The book is broken down in 5 parts, with 10 chapters total, at just over 250 pages. The main sections of the book are:
- Strategies for Concurrency - this discusses the impact of multi-core machines and the three design approaches that are discussed throughout the rest of the book, Shared Mutability, Isolated Mutability and Pure Immutability.
- Modern Java/JDK Concurrency - covers the Java 1.5+ concurrency features and talks about how to use the newer concurrency classes, like ExecutorService, CountDownLatch, Locks and Fork/Join to solve concurrency problems.
- Software Transactional Memory - covers Software Transactional Memory (STM), popularized by Clojure, which places access to memory within transactions. STM is one option for getting away from the 'Synchronize and Suffer' model as Venkat call it. The intention is to make threaded code more deterministic. Using the JDK concurrency tools, there is no way to be sure you code is correct because it doesn't always fail when/where you need it to. By putting the memory access inside transactions, the transaction manager helps resolve the conflicts without explicit locking.
- Actor-based Concurrency - covers actor design approaches as another option for concurrency design without using synchronization. This section exercises actors from the Akka library from Scala, Actors from the Groovy library GPars, and mixing Actors and STM as a possible solution.
- Epilogue - is a short recap of the topics presented previously and points out the scenarios when each of the solutions would be appropriate.
Summary
This is a good book to get you started on some of these newer concurrency concepts and libraries. It was an easy read, and I completed the reading fairly quickly, as opposed to the "Java Concurrency in Practice" book, which I started and stopped twice and still have not completed yet!
I would recommend this book to anyone looking to improve their programming skills in the concurrency area. The book provides you with some alternatives to the old standby of ' Synchronize and Suffer' model.
My last recommendation, if you get the opportunity, attend one of Venkat's presentations, you won't be sorry!
Labels:
book review,
clojure,
concurrency,
Groovy,
java,
scala
Thursday, January 19, 2012
Passing parameters into Groovy script using Binding class
I recently saw a question posted on the Groovy/Grails group on LinkedIn asking about ways to pass in parameters to a Groovy script. There were several responses pointing to the CliBuilder class which is certainly one way to handle the problem. I had just finished reading an article by Ken Kousen in the November issue of GroovyMag where Ken mentioned another option: using the Binding class.
The example below shows a couple ways of setting variables in the binding, getting the variable values from the binding and how to capture standard output from the script. The one tricky part is the question "When is something in the Binding and when not?" The answer is: when it's not defined, it is in the binding! In the example below, variable c is placed in the binding, but since it is def'd in the script, the value for that variable comes from the local variable rather than the binding.
Hope this helps!
The example below shows a couple ways of setting variables in the binding, getting the variable values from the binding and how to capture standard output from the script. The one tricky part is the question "When is something in the Binding and when not?" The answer is: when it's not defined, it is in the binding! In the example below, variable c is placed in the binding, but since it is def'd in the script, the value for that variable comes from the local variable rather than the binding.
// setup binding
def binding = new Binding()
binding.a = 1
binding.setVariable('b', 2)
binding.c = 3
println binding.variables
// setup to capture standard out
def content = new StringWriter()
binding.out = new PrintWriter(content)
// evaluate the script
def ret = new GroovyShell(binding).evaluate('''
def c = 9
println 'a='+a
println 'b='+b
println 'c='+c
retVal = a+b+c
a=3
b=2
c=1
''')
// validate the values
assert binding.a == 3
assert binding.getVariable('b') == 2
assert binding.c == 3 // binding does NOT apply to def'd variable
assert binding.retVal == 12 // local def of c applied NOT the binding!
println 'retVal='+binding.retVal
println binding.variables
println content.toString()
Output
[a:1, b:2, c:3] retVal=12 [a:3, b:2, c:3, out:java.io.PrintWriter@1e0799a, retVal:12] a=1 b=2 c=9
Hope this helps!
Tuesday, January 17, 2012
Book Review: SQL Antipatterns Avoiding the Pitfalls of Database Programming
Overview
This is book for software developers that are either new to database programming (SQL) or those that may not have had any formal database education and may have learned 'on-the-job'.
The book is bit longer, approximately 300 pages, than some of the other titles I've read from The Pragmatic Programmers shelf, but it is a very easy read. The chapters all follow a similar format: Object, Antipattern, How to Recognize the Antipattern, Legitimate Uses of the Antipattern and Solution. Each chapter the author leads you through a problem that needs correcting within the scope of the database. Next the antipattern is laid out for you and the author shows the disadvantages of using the antipattern. Tips are provided to help identify the antipattern and he also suggests some possible legitimate uses of the antipattern. Finally, the author describes better solutions to the problem presented; ones without the disadvantages discussed previously and solutions that are considered 'best practices' and that will provide better database performance.
Contents
The book is broken down into 4 main sections:
Summary
This is a very good book for software developers just starting to 'cut their teeth' with databases and SQL. It also serves as a good refresher for those with a bit more database experience. In my case, I fall into the later scenario. You can view it as a book of short stories, showing what not to do in these cases.
This is book for software developers that are either new to database programming (SQL) or those that may not have had any formal database education and may have learned 'on-the-job'.
The book is bit longer, approximately 300 pages, than some of the other titles I've read from The Pragmatic Programmers shelf, but it is a very easy read. The chapters all follow a similar format: Object, Antipattern, How to Recognize the Antipattern, Legitimate Uses of the Antipattern and Solution. Each chapter the author leads you through a problem that needs correcting within the scope of the database. Next the antipattern is laid out for you and the author shows the disadvantages of using the antipattern. Tips are provided to help identify the antipattern and he also suggests some possible legitimate uses of the antipattern. Finally, the author describes better solutions to the problem presented; ones without the disadvantages discussed previously and solutions that are considered 'best practices' and that will provide better database performance.
Contents
The book is broken down into 4 main sections:
- Logical Database Design Antipatterns - planning database tables, columns and relationships
- Physical Database Design Antipatterns - defining tables, indexes and choosing datatypes
- Query Antipatterns - SQL command usage, for example, SELECT, UPDATE and DELETE
- Application Development Antipatterns - correct usage within the scope of a language
Some of that antipatterns described may make you laugh and wonder, "Who the heck would do something like that?" while others you may have run into previously and some might even hit very close to home from your work or personal projects.
There is also an appendix that covers the Rules of Normalization. I had heard of terms like Normalization, First Normal Form, and Second Normal Form before, but never actually read any explanations. The appendix includes discussions on normalization and first normal form through fifth normal form with examples to help clarify the topics.
This is a very good book for software developers just starting to 'cut their teeth' with databases and SQL. It also serves as a good refresher for those with a bit more database experience. In my case, I fall into the later scenario. You can view it as a book of short stories, showing what not to do in these cases.
Wednesday, October 26, 2011
Jars signed with mutliple code signing certificates?
For anyone that has built and maintained Web Start applications, you have probably been through this issue before. Your QA group or worse yet, a customer, calls to tell you that they cannot start your application because the download failed because "jar resources in jnlp are not signed by the same certificate".
If want your Web Start application to have full access permissions, then you need to sign all the jars that get downloaded. This generally presents the opportunity to encounter one of the following errors:
Groovy Script
If want your Web Start application to have full access permissions, then you need to sign all the jars that get downloaded. This generally presents the opportunity to encounter one of the following errors:
- None of the jars are signed. Most likely a build issue and generally only happens once, (I hope!)
- Single jar
is not signed. Again, most likely either a build or process error. - Not all jars signed with the same certificate.
The first two are easy to resolve. The last is a bit of a pain because Web Start doesn't bother to tell you exactly which jars where signed with different code signing certificates. Now, it's time to make some educated guesses as to what changed recently and look at the most likely/usual suspects. Another option is to get the list of download jars from the JNLP document and figure out which certificates(s) each jar has been signed with.
We have been through this at work once or twice and so I finally decided to make it easier for the next time this happens. The approach I took was to read all the jars in a deployment folder, open them and look for the signature files inside the jar file. For the results, I created a map keyed by the jar name and the value being a list of the signature file names (*.RSA, where the * represents our code signing certificate alias). Keeping a list in the map allows for cases where a jar may have multiple signature files, which was encountered when we switched over code signing certificates. Writing this in Java would be possible, but why write so much code? Why not write a script in Groovy, it would be some much shorter and concise.
Groovy Script
def dir = new File("C:\\MyDeployment\\jboss\\myserver\\deploy\\myserver.ear")
def jars = dir.list( { d, f-> f ==~ /.*.jar/ } as FilenameFilter)
def map = [:]
jars.each() {
def zipFile = new java.util.zip.ZipFile(new File(dir, it))
zipFile.entries().each { zipEntry ->
if (zipEntry.name.endsWith('.RSA')) {
if (map.containsKey(it)) {
def list = map[it]
list << zipEntry.name
} else {
map[it] = [zipEntry.name]
}
}
}
}
map.each{ println it}
Hope this helps!
Subscribe to:
Posts (Atom)

})

