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

Thursday, October 24, 2013

Setting a timeout on an Apache CXF webservice call

In this short post, I'll provide the code for setting a timeout on a webservice call. The client has been generated by Apache CXF 2.6.1, and the webservice is accessed by an HTTP call.

Client client = ClientProxy.getClient(yourPortType);

HTTPConduit httpConduit = (HTTPConduit) client.getConduit();

HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(5000);
httpClientPolicy.setReceiveTimeout(5000);

httpConduit.setClient(httpClientPolicy);

You should add this chunk of code before you call the method on yourPortType. The connectionTimeout is how long it may take to connect to the service, the receiveTimeout is how long it may take for the webservice to respond.


Friday, June 14, 2013

Eclipse cannot run program javaw.exe

Yesterday, I checked out a project from SVN, I ran mvn eclipse:eclipse and imported it into my IDE. So far so good, everything compiled, Maven could run all the tests, all was well.

But then I tried to run a JUnit test in Eclipse. I kept getting a strange error about Eclipse not being able to run javaw.exe in my project-folder. After some Googling, I found that the underlying error that causes this problem, was of an entirely different nature: Windows has a character limit to command line statements. And since Eclipse assembles the classpath itself to pass it on as a launch parameter, the command line character limit got violated.

I now knew what was causing the error, but fixing it didn't seem that simple. I tried to remove all unnecessary libraries (there weren't a lot), but the problem persisted. So I changed to drastic measures: I moved my Maven repository to a folder directly at my C:\ disk. The path was about 30 characters shorter than before, but since Eclipse was adding a whole lot of Maven libraries to my classpath, it made a huge difference.

After that, I could run my JUnit test without any problems. I suppose I'm safe for now, but what will happen when we add even more libraries to the project? It's possible that at a given point, the classpath will be too long for even the shortest possible repo-path you can get. And then what? Switching to Linux could be an option, but during my quest to solve this problem, I also read that IntelliJ has better support for this. So going there could be an option too. Or I could just write/wait for an Eclipse plugin that deals with this problem...

Monday, December 3, 2012

Special character encoding

If you have ever created a custom language bundle, you'll know special characters can be very annoying. When they're not displaying correctly, but instead showing a diamond with a question mark or a white rectangle, it's sometimes difficult and frustrating to find the origin of the problem.

When you're building a website that has to come with a language with a lot of special characters (French, German, ...), you can run these encoding problems. In fact, there only has to be one of those special characters anywhere in your site, and it'll be messed up. When working with resource bundles (.properties files),  I've found that these few steps often resolve a lot of issues, so try to follow these simple guidelines.

  • Make sure your general encoding is set to UTF-8. In Eclipse, you do this in Window -> Preferences -> General -> Workspace
  • Each file can have a seperate encoding as well. Check the properties of your .properties files. In Eclipse, you do this by right-clicking, then selecting Properties. Under Resource, you can set the encoding to UTF-8.
Redeploy your application with this correct settings, and your problems should dissolve! Bear in mind, though, that if you had an incorrect encoding first, switching to the correct encoding may break your file and replace the special characters by the 'not found' characters (diamond or rectangle). Check your file before deploying!

Thursday, October 4, 2012

Oracle Open World - thursday

Last day of the conference... Not a lot of sessions today (only 1 and the Java community keynote), but we've subscribed to a trip to Oracle HQ this afternoon. We're getting a tour in their usability labs.

But first things first. I started my day with the Java community keynote. It was mainly about innovation, and some cool demos of robots (by Perrone Robotics) were given. In the end, James Gosling entered the stage and showed us what he is currently doing: Liquid Robotics. Medium-sized robots that roam the seas and gather data.

Then I went to an ADF session by Eugene Fedorenko. He took us through the process of developing an ADF application. During his 'deep dive', he showed us how to programatically create entities and view objects, end display them on the screen. I found it a bit odd to do everything programatically, instead of using the declarative strength of the framework, but I'm sure that in some cases this will turn out to be the best way.

On to Redwood City then. Oracle took us on a tour in their usability labs. They showed us how their apps are tested and evaluated using some advanced eye-reading techniques. An interesting afternoon, as closure for a very interesting conference. I learned a lot, saw some very nice demos and met interesting people. All in the lovely setting of San Francisco.


Monday, October 1, 2012

Oracle Open World - monday

This year, I have the privilege of going to one of the biggest conferences in the world: Oracle Open World. If you look at the numbers... they're pretty huge! During this week, I'll try to keep you posted on the most interesting sessions I followed. There'll be a short summary, and my personal thoughts and views.

Why should you switch to Java 7 (David Keenan, Staffan Friberg)

Summary

The presentation was a summary of, as the title says, why you should switch to Java 7. I'll just sum them up again!

JCommands
Garbage First
Runtime compiler improvements
Sockets Direct Protocol
Performance benefits to
  •    Date
  •    BigDecimal
  •    Crypto
  •    String to byte conversion
  •    concurrency API
  •    Hotspot JVM
  •    PermGen
  •    Internal strings
  •    XML API
Backwards compatibility (source, binary, behavioural)
Heap retuning

My thoughts

Not really a very innovating session, just a sum up of what's new in Java 7 and what's to come in Java 8. A good review, though, and makes you think of upgrading.

Future of development for Oracle Fusion (Chris Tonas)

Summary

Chris gave a demo using ADF Faces. It was a  typical ADF application with fancy graphs and components. Then he showed us the same app, but on an iPad. It had the same functionality, but HTML5 instead of Flash. It also had a slightly different layout and supported gestures and touch. The pagination in tables we so liked in ADF 10g has returned (in an  im:proved way), to avoid scrollbars.

He then talked about the iOS and Android SDK support in JDeveloper, and the visual preview of the app you're building. Apparantly, you build an ADF app once, and then deploy it to Android and/or iOS (and any other vendor Oracle decides to support). Pretty convenient! Further, Chris discussed offline support and gave an ADF Mobile demo. This time, it was a native iOS app, which I thought was pretty impressive.

To end the Mobile part, Thomas Quilligan presented a real-life case. He is from Accenture, an ADF Mobile Beta Program Partner. It was nice to see the Oracle ADF Mobile technology being used in a real-life project.

After that, we moved on to the Cloud part of the talk., with a strong focus on Developer Cloud Service. These are some of the out of the box services that the Developer Cloud offers:
  • Source control
  • Maven support
  • Issue tracking
  • Continuous Integration (Hudson) 
  • Wiki




The demo of the Developer Cloud Service that followed, was very nice. It showed the full development lifecycle, all brought to the cloud, organized in neat dashboards.






My thoughts

This was a very nice presentation. The ADF Mobile still looks promising, and appears to be finally released soon. The cloud part really surprised me. I've been waiting for Oracle Cloud for quite a while now, but I didn't know they were going to offer something like the Developer Cloud. I really liked that. If it all integrates as well as in the demos, this will definitely be a product I'd want and like to use!

Oracle's public cloud strategy (Abhay Parasnis)

I'm writing an article about this session on Cloudspring. I'll update the link as soon as it gets published.

Classic mistakes with ADF (Frank Nimphius, Duncan Mills)

This was a nice light session about some of the most made errors with ADF. Driven by real examples and questions, Duncan and Frank guided us through. I'll add the slides as soon as they're available, since writing it all out seems a little pointless.

I'll just give a bit more details about one of the errors discussed. It's one we ran into as well, and Frank and Duncan categorized it as 'silent, but deadly' (as opposed to 'unforgiveable' and 'bear traps'). It's about using a bean that is not request scope, but that contains references to UI components. The problem here is that UI components only last as long as a request. They are therefore not serializable, and any bean with a scope higher than request, will want to serialize all it's variables.

Friday, April 13, 2012

ADF 11g: Using Application Module outside ADF Application context

Earlier this week, I had to refactor an existing project, and extract some functionality. The goal was that this code could run outside of our Weblogic server, in a crontab job. So I created a new project, containing a class with a main method. The original code was based on Business Components, so I wanted to use this Oracle ADF specific technology as well.

After all the extraction was done, I created a JAR file of my new project and tried to run my main class. The fist problem I encountered was not having all the necessary JARs on my classpath. Therefor, I created a batch-script (could be Unix as well, but I was working in a Windows environment), setting all necessary JARs on my classpath and launching my main method

set JAVA_HOME=C:\Oracle\Middleware\jdk160_18\jre

set PATH=%JAVA_HOME%\bin;%PATH%
set CLASSPATH= YOUR_CLASSPATH

java -classpath %CLASSPATH% my.MainClass


Where YOUR_CLASSPATH is a semicolon-seperated list of all JARs you need. Now the code would compile! But then I ran into the next issue: creating an application module.

I used the default way of creating an Application Module, ie. Configuration.createRootApplicationModule(). While this works inside an ADF application, running a JAR standalone does not provide you with enough context. So I tried a new approach, and manually initialized a context:

String jdbcURL = "jdbc:oracle:thin:@HOST:PORT:SID";

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, JboContext.JBO_CONTEXT_FACTORY);
env.put(JboContext.DEPLOY_PLATFORM, JboContext.PLATFORM_LOCAL);

Context ic = new InitialContext(env);


But of course, creating a Context isn't enough to use the Application Module. We need to create that as well, and I did that in the following manner:

// 'defName' is the JNDI name for the application module
// definition from which the root application module is to
// be created
String defName = "my.AppModule";

ApplicationModuleHome home = (ApplicationModuleHome)ic.lookup(defName);
ApplicationModule = (ApplicationModule)home.create();
mbApplicationModule.getTransaction().connect(jdbcURL, dbUser, dbPassword);


DefName is the JNDI name of your application module. This can be found in bc4j.xcfg. Now we can use the ApplicationModule just like we would in an ADF Application context!

Friday, March 23, 2012

The Cloudbees cloud solution

A few weeks ago, I blogged about getting your app online with Google App Engine. While this is a very easy process, it is far from the only cloud solution available. I have tried another one, Cloudbees, and will tell you about my experience now.

Cloudbees offers more then just a deployment platform. It has Repositories, Continuous Itegration and an Application Server for you to play around with. It also offers database services, and has plugins for numerous other things (like Sonar, Sauce Labs and many others). For this next example, I used SVN as repository, Jenkins as CI and Tomcat as app server.

Signing up

Signing up for Cloudbees is easy. Fill in your name and e-mailaddress, and create an account. That's it! Now that your account has been created, you can select which services to use. There are both free and paying options. To get started, I added the following:
  • Repository
  • Jenkins
  • Applications
I chose the free version of each. The idea was to simulate a real world working environment. I know there are a SDK and plugins available to build and deploy from within Eclipse/STS, but I wanted to have a continuous integration build my SVN repository whenever I checked in changes.

Configuration

First, I created a new code repository (in the Repositories service). I named it 'blogtryouts'.

Then I created a new application, naming it, again, Blogtryouts.


You now can configure the application server, which is in fact a Tomcat instance. You can define JDBC-connections, or upload a WAR file to be deployed.

Continuous integration

But we don't just want to upload a WAR file. We want our newly created SVN repository to be checked out, the project to be built and the resulting WAR-file to be automatically deployed. Therefore, we'll create a Jenkins service in Cloudbees. I created a DEV@Cloud free instance.

The Jenkins instance is immediately available. I added a new job ('Blogtryouts', who'd have guessed?), and made it a Maven 2/3 project. Once created, we can start configuring our Jenkins build!

Checkout, build, deploy

The configuration is pretty easy as well. The first thing we want Jenkins to do, is checkout our SVN repository. Under Manage sourcecode, you can select Subversion and then specify a URL. That URL is the one Cloudbees gave you when you created your repository. You can find it by going to Services -> Repositories and selecting your repository.

Since we told Jenkins it's a Maven project, it'll automatically try to build the pom.xml. You can add parameters and specify when it should be built. Under Building Activators check Build when a change is pushed to CloudBees Forge. This will start a build when someone commits code to SVN.

Last but not least ,we want to deploy the built artifact. Therefore, check Deploy to CloudBees under Actions after build. You can now specify the site and application ID to deploy to. The site is normally your username, application ID is the name you gave your application, prefixed with yoursite/. Cloudbees helps a lot by providing a dropdown with sites, and by telling you an application ID can't be found. They can even tell you which application IDs are valid.

If you now click 'build now', There will be a warning that your account hasn't been validated. This is an extra step required. Just click the link and enter your phone number (make sure you're near the phone with that number!). Seconds later, you'll receive a phone call with a computer voice telling you a PIN code. Enter the pin code, and you're good to go.

The webapp

So, now that our cloud is fully setup, we of course need a webapp to deploy. For demonstration purposes, we'll just use a general Maven archetype. As in some of my prvious blogposts, we'll create a Wicket project. We can do this quickly by executing this Maven command:

mvn archetype:generate -DarchetypeGroupId=org.apache.wicket -DarchetypeArtifactId=wicket-archetype-quickstart -DarchetypeVersion=1.5.5 -DgroupId=com.mycompany -DartifactId=myproject -DarchetypeRepository=https://repository.apache.org/ -DinteractiveMode=false

The magic

Now that our application has been created, we just have to import it into our SVN repository. I used TortoiseSVN to do an Import to my Cloudbees repository. It doesn't matter how you do it, but once the import's been done, you can watch the magic happen.

Jenkins will notice a new commit and will start a new build. When that's done, it'll deploy the generated WAR-file. When you now go to Services -> Applications, and click your application, you'll notice a new deploy has been done, with a Jenkins build message. This means your app is up and running! The URL is found on top of this page as well. Mine is available here.

Monday, March 19, 2012

Oracle Certified Professional (OCP), Java SE 7 Programmer

Oracle has announced a new certification, the Oracle Certified Professional, Java SE 7 Programmer. If you already are an Oracle Certified Professional (or a Sun Certified Java Programmer) for a previous version of Java, you can take an exam to upgrade your certification to the latest version.

If you're not yet certified, and want to become an OCP, you must first pass the Oracle Certified Associate (OCA) Java 7 Programmer exam.

Friday, March 16, 2012

Updated Java 6 EOL date

In its recently updated Java SE Support Roadmap, Oracle provides an updated date for Java 6 to go EOL (End Of Life). It used to be July 2012, but has now been postponed to November 2012.

Basically, it means that after November 201 Oracle will no longer post updates of Java SE 6 to its public download sites. Developers are encouraged to switch to the latest version.

Tuesday, March 13, 2012

JDeveloper: Code Template to show current class and method

For debugging purposes, I sometimes use a simple System.out.println statement to have some values displayed on the console. It's not the best or cleanest way, I know, but it works and is a lot faster than setting up a logging framework first. If you already have a logging framework configured, you might as well use that one, of course. Following method could also be used for quickly generating logging statements.

To keep an overview of the messages printed, I usually preceed every message with currentClass.currentMethod. In JDeveloper, there's an easy way to do this:

  • Open Tools -> Preferences...
  • Go to Code Editor -> Code Templates
  • Add a new one
  • Enter a shortcut (I use 'sopl'), and change the context to Java
  • In the code section, type System.out.println("$myCurClass$.$myCurMethod$(): $end$");
  • In the variables tab, map myCurClass to 'Class Name' and  myCurMethod to 'Method Name'
  • Leave end mapped to 'End Location'
Now you can use sopl in every Java class! Just type sopl and hit Ctrl+Enter.

Monday, March 12, 2012

How to use Uploadify in Spring MVC

What is Uploadify?

www.uploadify.com
"Uploadify is a jQuery plugin that integrates a fully-customizable multiple file upload utility on your website. It uses a mixture of Javascript, ActionScript, and any server-side language to dynamically create an instance over any DOM element on a page."

So, Uploadify is a JQuery lib which allows you to upload multiple files at once onto your webpage. Uses flash for fancy animations!

Implementation

Integration

You start by downloading Uploadify and integrate it into your project. Put them in a folder and add thaty folder to mvc:resources in je servlet-context.xml.

<mvc:resources location="/resources/" mapping="/resources/**">

Further, you need to tell Spring thatMultiPartFiles are possible:

<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
  <property name="maxUploadSize" value="500000"/>
</bean>


In a Maven project, get the required libraries by adding this to your POM:

<dependency>
 <groupid>commons-fileupload</groupid>
 <artifactid>commons-fileupload</artifactid>
 <version>1.2</version>
</dependency>


Upload page

Your upload page looks like this:

<link href="../resources/uploadify/uploadify.css" rel="stylesheet" type="text/css"></link>
<script src="../resources/js/jquery16.js"></script>
<script src="../resources/uploadify/jquery.uploadify.js"></script>
<script src="../resources/uploadify/swfobject.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var myFiles = new Array();
var myFileCnt = 0;
$('#file-upload').uploadify({
'swf': '../resources/uploadify/uploadify.swf',
'cancelImage': '../resources/uploadify/cancel.png',
'multi' : true,
'auto' : true,
'fileObjName' : 'filedata',
'checkExisting' : false
});
});
</script>

<input id="file-upload" name="file-upload" type="file" />


Handling

If you set auto to true, an automatic POST-request will be executed. We need to catch and handle it!

@Controller public class FileUploadController {

 @RequestMapping(method=RequestMethod.POST)
 public String handleFile(MultipartHttpServletRequest request)
 {
  MultipartFile file = request.getFile("filedata");
  //some code here
  return "fileupload/success";
 }
}


Extra parameters in request

You can add extra parameters to your request. This is not as easy as it sounds, because Uploadify creates and manages its own form. This is how I did it:
Add function to your JSP page
In Uploadify, there are a few events available that are triggered throughout the process. onSelect is one of them. It gets called every time files are selected.

onSelect : function(){
$('#file-upload').uploadifySettings(
'postData',
{'season':$('#season').val()}
);
}


Your entire script now looks as follows:

$(document).ready(function() {
var myFiles = new Array();
var myFileCnt = 0;
$('#file-upload').uploadify({
'swf': '../resources/uploadify/uploadify.swf',
'uploader': '',
'cancelImage': '../resources/uploadify/cancel.png',
'multi' : true,
'auto' : true,
'fileObjName' : 'filedata',
'checkExisting' : false,
onSelect : function(){
$('#file-upload').uploadifySettings(
'postData',
{'myParamName':$('#myFieldId').val()}
);
}
});
});


Get parameter in Controller
When you've added the parameter to the postData, as described above, you can easily get it in your Controller. Its value is now in the parametermap of your request.

String s = request.getParameter("myParamName");

If you have followed this guide and stumbled upon problems, please let me know. I'll try to keep it as correct and up-to-date as possible!

Saturday, March 3, 2012

Get your app online in 10 minutes with Google App Engine!

In this post I'll explain how to easily get an app online and running in under 10 minutes. There are a few thing we need before we can start, though:
The Google App Engine SDK can easily be installed from within STS itself.

So, once we have all these prerequisited, we can get started! First thing you have to do is tell Google you want to deploy a new application. To do this, go to the Google App Engine start page, and create an application.

I named my app blogtryouts.

Now we are ready to actually build an application. Springsource Toolsuite comes with Maven preconfigured, so we might as well use Maven and its rich collection of archetypes to get going. So, in STS, create a new Maven project (File -> New -> Other..., and then select Maven project)

A wizard starts to help you create a new Maven project. Make sure you leave the Create a simple project (skip archetype selection) UNCHECKED! We're going to select a Maven archetype to get started really fast. More information about Maven Archetypes can be found here. When you click next, you can select the maven archetype you want to use. Filter on gae, and select the archetype using the framework you desire. I chose Wicket, cause I like the way it works (and how you can have a web designer do the tedious HTML/CSS styling while you can focus on the real Java development). To use wicket, select gae-archetype-wicket.

Click Next. Now comes the screen where you enter your application information. Enter data concerning to your application in Group IdArtifact Id and package. In the gaeApplicationName field, you enter the name of the application you created on appengine.google.com. In our case, this was blogtryouts.

Also notice the gaeApplicationVersion field. It defaults to test. We'll change it to release, to deploy a release version of our app. Click Finish. Maven will now create an archetype!

Now, there are still some issues before you can deploy your application. You have to put the Google App Engine SDK to your buildpath. I have no idea why this isn't done by default, but it isn't, so we'll have to do it ourselves. Easiest way is by right clicking your project, and select Google -> App Engine Settings... Basically, you can just hit Ok, to accept all default values.

Now that the SDK has been added, there still is 1 problem to be addressed. I think it's a bug in either STS or the Maven Archetype, but the appengine-local-runtime artifact seems to be missing. You can just go to the pom, and delete the entry.

<dependency>
  <groupId>com.google.appengine</groupId>
  <artifactId>appengine-local-runtime</artifactId>
  <version>${gae.version}</version>
  <scope>test</scope>
</dependency>


Now, build the project by using the maven package command. The necessary files and folders will be created, and your application is ready to be deployed! When Maven has finished packaging, right click your application in STS, select Google -> Deploy to App Engine... and deployment will start. When it's finished, your application is available at yourAppname.appspot.com.

If you used test instead of release in the gaeApplicationVersion I mentioned earlier, it would deploy to test.yourAppname.appspot.com.

Good luck and have fun!


Friday, March 2, 2012

Java7 features

Java 7 has been released for a while now, but I thought I'd link to the most important new features, for future reference.

JDK7 Features

For us, developers, the most commonly used will be the ones made in Project Coin, I guess. Also take not of the features postponed to JDK 8 (at the bottom of the page)

Thursday, March 1, 2012

ADF @ KnowledgeBlackBelt

Ever heard of KnowledgeBlackBelt? It used to be BlackBeltFactory. Doesn't sound familiar either? Perhaps JavaBlackBelt then? I'm sure that rings a bell to a lot of Java-oriented developers. Well, it's all the same site, it just has changed name (and layout) a few times over the years.

 In short, KnowledgeBlackBelt is a Java Learning & Certification community. Everyone can join and take free exams to gain grades. There are even courses (both free and paid) that handle certain topics and prepare you to take those exams. New users start out with a white belt, and eventually, after taking courses, exams and contributing to the community, they can become a Black Belt.

 I'm a contributor to the KnowledgeBlackBelt community. I have earned a brown belt over the years, and I'm the leader and moderator of the ADF Business Components exam. Check out the exam, and the entire concept that is KnowledgeBlackBelt. Learn, gain experience and get better at what you do.

Tuesday, February 28, 2012

Google App Engine

Recently, I started building my own website. Since I'm a Java developer, I wanted to build a website in Java. For work, I usually build web applications using Oracle's ADF, so for now, I wanted to use some other technology.

Of course, building a website in Java offers a lot of possibilities, but it also has its drawbacks. For example, most free webhosting solutions don't support Java applications. Therefore I had to either put up my own server, or find some cloud solution.

I opted for the latter, and quickly encountered Google as a provider for my needs. And more specifically: Google App Engine. After some quick research, I found that there are plugins for Eclipse (or STS, in my case) to get started easily. After installing the Google App Engine SDK Plugin for Eclipse, creating and deploying an application to the web is a matter of a few clicks!

More information on how to build applications for Google Apps Engine will follow shortly, in upcoming posts.

Stay tuned!