Archive for the ‘en-US’ Category
Why “contract first” approach won’t work with CXF or SpringWS for Axis-generated WSDLs
Case
My previous subject was the following: considering a WSDL that was generated by Axis 2, develop a webservice with CXF and/or SpringWS in “contract first” (ie the contract seen as an API is given, Java code comes afterwards) approach.
It cannot work easyly, unless you are ready to spend time, money and energy in creating adapters and adding layers in your application architecture.
CXF
With CXF, the first step is to generate Java code with the wsdl2java embeded in Maven CXF plugin. The output is explicit:
[java]Failed to execute goal org.apache.cxf:cxf-codegen-plugin:2.6.1:#wsdl2java on project PocEjb3: Rpc/encoded wsdls are not supported with #CXF[/java]
(cf my tweet)
RPC vs Encoded
Actually, the SOAP envelope has two ways to transport the message: RPC and Document. More detail is available here: Which style of WSDL should I use?
Axis 2 generates RPC/encoded webservice ; this method is deprecated, CXF does not support it.
Spring WS
I then tried to use Spring WS. I thought “Spring WS is only contract-first, it should work”. The first pitfall I fell on was that SpringWS bases on XSD files, not on actual WSDL. For instance, if you follow SpringWS tutorial, you will find such a block:
[xml] <sws:dynamic-wsdl id="holiday" portTypeName="HumanResource" locationUri="/holidayService/"
targetNamespace="http://mycompany.com/hr/definitions">
<sws:xsd location="/WEB-INF/hr.xsd"/>
</sws:dynamic-wsdl>
[/xml]
To workaround, you can specify use tag, such as:
[xml]<sws:static-wsdl id="precomputed-holiday" location="/WEB-INF/precomputed-holiday.wsdl"/>[/xml]
Anyway, the next issue appears: SpringWS expects to deal with document webservices, ie blocks like:
[xml]<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://mycompany.com/hr/schemas">
<soapenv:Header/>
<soapenv:Body>
<sch:HolidayRequest>
<!–You may enter the following 2 items in any order–>
<sch:Holiday>
<sch:StartDate>?</sch:StartDate>
<sch:EndDate>?</sch:EndDate>
</sch:Holiday>
<sch:Employee>
<sch:Number>?</sch:Number>
<sch:FirstName>?</sch:FirstName>
<sch:LastName>?</sch:LastName>
</sch:Employee>
</sch:HolidayRequest>
</soapenv:Body>
</soapenv:Envelope>>
[/xml]
whereas Axis-generated WSDL look like:
[xml]<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:int="http://interfaces.api.lalou.jonathan">
<soapenv:Header/>
<soapenv:Body>
<int:sayHello soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</soapenv:Body>
</soapenv:Envelope>
[/xml]
In other words, I have just fallen on the exact same issue as with CXF: SpringWS cannot support RPC/encoded WSDLs.
[DevoxxFR2012] JavaServer Faces: Identifying Antipatterns and Embracing Best Practices for Robust Applications
Lecturer
Kito Mann leads as Principal Consultant at Virtua, Inc., focusing on enterprise architecture, training, and mentoring in JavaServer Faces (JSF), HTML5, portlets, Liferay, and Java EE. Editor-in-chief of JSFCentral.com, he co-hosts the Enterprise Java Newscast and hosts the JSF Podcast series. Author of “JavaServer Faces in Action” (Manning), Kito participates in JCP expert groups for CDI, JSF, and Portlets. An international speaker at events like JavaOne and JBoss World, he holds a BA in Computer Science from Johns Hopkins University.
Abstract
This article probes Kito Mann’s exploration of common pitfalls in JavaServer Faces (JSF) development, juxtaposed with recommended strategies for optimal performance and maintainability. It scrutinizes real-world antipatterns, from hardcoded IDs and database accesses in getters to broader issues like inconsistent standards and improper API usage. Embedded in JSF’s component-based framework, the analysis reviews techniques for dependency injection, state management, and view optimization. Via code illustrations and case studies, it evaluates consequences for scalability, team onboarding, and application longevity, advocating principled approaches to harness JSF’s strengths effectively.
Common Pitfalls in Component and Bean Management
JSF’s strength lies in its reusable components and managed beans, yet misuse breeds inefficiencies. Kito identifies hardcoding IDs in backing beans as a cardinal error—components autogenerate IDs, risking conflicts. Instead, employ bindings or relative references.
Database operations in getters exacerbate performance: invoked multiple times per request, they overload servers. Solution: Fetch data in lifecycle methods like init() or use lazy loading:
@PostConstruct
public void init() {
users = userService.getUsers();
}
Lack of standards fragments codebases; enforce conventions for naming, structure. Wrong APIs, like FacesContext in non-UI layers, violate separation—inject via CDI.
Optimizing State and View Handling
State management plagues JSF: View-scoped beans persist unnecessarily if not destroyed properly. Kito advises @ViewScoped with careful serialization.
Large views bloat state; mitigate with for partial renders or for modularization. c:if toggles subtrees but beware quirks—prefer rendered attributes unless tree pruning is essential.
Dependency lookups in getters repeat calls; leverage CDI injection:
@Inject
private UserProvider userProvider;
This ensures singletons are fetched once, enhancing efficiency.
Enhancing Performance Through Best Practices
Ajax integrations demand caution: Overuse swells requests. Optimize with execute/render attributes.
Navigation rules clutter; use implicit navigation or bookmarkable views with GET parameters.
Testing antipatterns include neglecting UI tests—employ JSFUnit or Selenium for comprehensive coverage.
Implications: These practices yield responsive, scalable apps. By avoiding antipatterns, teams reduce debugging, easing onboarding. In enterprise contexts, they align JSF with modern demands like mobile responsiveness.
Kito’s insights empower developers to refine JSF usage, maximizing framework benefits.
Links:
Blog Upgrade onto WordPress 3.3.1 on Free.fr
Yesterday I upgraded the blog to WordPress 3.3.1. Last version was a but old (2.8 branch), I installed it in october 2009.
Being hosted on Free.fr, I had to use a customized version of WordPress, released by Gaetan Janssens on his blog Petit Nuage’s Stunning World.
The process I followed is basic:
- back up database via PhpMyAdmin
- export the blog full content
- backup current state of (former) remote WordPress code
- upload WordPress 3.3 via FTP
- reupload once more (I often happened to have files that Free.fr FTP “missed” to receive, or received partially ; I don’t think FileZilla is the root cause)
- add a
.htaccess(the former one vanished in outer space, I ignore why) - login to admin
- disable all plugins
- restore default them
- display the blog
- enable theme
- enable each plugin one per one
I encountered some issues, that I fixed after a short look in PHP code. Well… I was a PHP expert ; I am no more :-D. I may speak Spanish better than PHP.
Now it seems to work. So far, having kept the same theme, almost no differences are visible. I only added links and social sharing sections on the left column. Anyway I’d like to change the theme (even though I enjoy it and its Tux 😉 , and I’d like to keep a Linux-oriented style)
Akismet does not work anymore (more information on Pascal Ledisque’s bloc, in French). I may use Antispam Bee instead.
I also was unable to display Twitter flow: this issue is linked to the previous one: Free.fr prevents WordPress from accessing external HTML, XML and/or RSS flows.
[DevoxxFR2012] Android Development Essentials: A Comprehensive Introduction to Core Concepts and Best Practices
Lecturer
Mathias Seguy founded Android2EE, specializing in Android training, expertise, and consulting. Holding a PhD in Fundamental Mathematics and an engineering degree from ENSEEIHT, he transitioned from critical J2EE projects—serving as technical expert, manager, project leader, and technical director—to focus on Android. Mathias authored multiple books on Android development, available via Android2ee.com, and contributes articles to Developpez.com.
Abstract
This article examines Mathias Seguy’s introductory session on Android development, designed to equip Java programmers with foundational knowledge for building mobile applications. It explores the Android ecosystem’s global context, core components like activities, intents, and services, and practical implementation strategies. Situated within the rapid evolution of mobile IT, the analysis reviews methodologies for UI construction, resource management, asynchronous processing, and data handling. Through code examples and architectural patterns, it assesses implications for application lifecycle management, performance optimization, and testing, providing a roadmap for novices to navigate Android’s intricacies effectively.
Positioning Android Within the Global IT Landscape
Android’s prominence in mobile computing stems from its open-source roots and widespread adoption. Mathias begins by contextualizing Android in the IT world, noting its Linux-based kernel enhanced with Java libraries for application development. This hybrid architecture leverages Java’s familiarity while optimizing for mobile constraints like battery life and varying screen sizes.
The ecosystem encompasses devices from smartphones to tablets, supported by Google’s Play Store for distribution. Key players include manufacturers (e.g., Samsung, Huawei) customizing the OS, and developers contributing via the Android Open Source Project (AOSP). Mathias highlights market dominance: by 2012, Android held significant share, driven by affordability and customization.
Development tools integrate with Eclipse (then primary IDE), using SDK for emulation and debugging. Best practices emphasize modular design to accommodate fragmentation—diverse API levels and hardware. This overview underscores Android’s accessibility for Java developers, bridging desktop/server paradigms to mobile’s event-driven model.
Core Components and Application Structure
Central to Android apps are activities—single screens with user interfaces. Mathias demonstrates starting with a minimal project: manifest.xml declares entry points, main_activity.java handles logic, and layout.xml defines UI via XML or code.
Code for a basic activity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Intents facilitate inter-component communication, enabling actions like starting activities or services. Explicit intents target specific classes; implicit rely on system resolution.
Services run background tasks, unbound for independence or bound for client interaction. Content Providers expose data across apps, using URIs for CRUD operations. Broadcast Receivers respond to system events.
Mathias stresses lifecycle awareness: methods like onCreate(), onPause(), onDestroy() manage state transitions, preventing leaks.
Handling Asynchronous Operations and Resources
Mobile apps demand responsive UIs; Mathias introduces Handlers and AsyncTasks for off-main-thread work. Handlers post Runnables to UI thread:
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
// UI update
}
});
AsyncTask abstracts background execution with doInBackground(), onPostExecute():
private class DownloadTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
// Download
return result;
}
protected void onPostExecute(String result) {
// Update UI
}
}
Resources—strings, images, layouts—are externalized in res/ folder, supporting localization and densities. Access via R class: getString(R.string.app_name).
Data persistence uses SharedPreferences for simple key-values, SQLite for databases via SQLiteOpenHelper.
Advanced Patterns and Testing Considerations
Patterns address lifecycle challenges: Bind threads to activity states using booleans for running/pausing. onRetainNonConfigurationInstance() passes objects across recreations (pre-Fragments).
For REST services, use HttpClient or Volley; sensors via SensorManager.
Testing employs JUnit for units, AndroidJUnitRunner for instrumentation. Maven/Hudson automate builds, ensuring CI.
Implications: These elements foster robust, efficient apps. Lifecycle mastery prevents crashes; async patterns maintain fluidity. In fragmented ecosystems, adaptive resources ensure compatibility, while testing mitigates regressions.
Mathias’s approach demystifies Android, empowering Java devs to innovate in mobile spaces.
Links:
(long tweet) Increase choice with mvn archetype:generate
By default, mvn archetype:generate offers ~50 template projects. How to offer more templates?
Actually, Maven bases itself on a archetype-catalog.xml file, in Maven’s local repository. Updating this file is possible, by mvn archetype:crawl (and/or archetype:update-local-catalog ?).
Anyway, Maven can base on a remote repository, using archetypeCatalog, such as:
[java]mvn archetype:generate -DarchetypeCatalog=http://download.java.net/maven/2[/java]
You can hint at the remote repository available in settings.xml file, for instance.
(long tweet) JOnAS / GenIC / Method … of interface … should NOT throw RemoteException
Case
On generating Locals and Remotes of EJBs (let’s say JonathanBean) to be deployed on JOnAS, the GenIC raises:
[java]GenIC.fatalError : GenIC fatal error: Cannot read the Deployment Descriptors from /foo/goo/jonathan-server.jar: Method foo of interface lalou.jonathan.JonathanLocal should NOT throw RemoteException[/java]
Within the EJB2, the method foo is declared to be Local and to throw RemoteException
Quickfix
The error is explicit.
A Local EJB cannot throw RemoteException.
Especially, the considered method can be declared with the right XDocLet tag, ie:
[java]* @ejb.interface-method view-type="remote"[/java]
but can with neither:
[java]* @ejb.interface-method view-type="both"[/java]
nor:
[java]* @ejb.interface-method view-type="local"[/java]
As a quickfix, I suggest to surround with a try/catch block a throw a RuntimeException if needed.
(long tweet) Tip: How to know the location of a resource?
Case:
You have many files with the same names (log4.xml, applicationContext.xml, etc.), you need know which of them is loaded.
Tip:
On the debugger and/or in the logs, use an instruction similar to:
getClass().getClassLoader().getResource("log4j.xml")
(long tweet) JOnAS / no security manager: RMI class loader disabled
On server side:
an EJB2 packaged in a JAR within an EAR, deployed on JOnAS 5.
On client side:
java.lang.ClassNotFoundException: org.ow2.jonas_gen.com.clam.indice.api.interfaces.JOnASHelloWorldService150707405Home_Stub (no security manager: RMI class loader disabled)]
Explanation:
This means there is some kind of issue with generated Stubs on client side. Should check whether the Stubs depended on are available in classpath.
Problems when invoking main method from GenIC … error in fastrmic
Case
Trying to deploy an EAR on JOnAS, I got the following error:
[java]Problems when invoking main method from GenIC: java.lang.RuntimeException: error in fastrmic (null)[/java]
More detail:
[java]JOnASEJBService.__checkGenIC : Cannot apply GenIC on the file ‘C:\jonathan\jonathan_2012.05.11-13.47.29.ear\jonathan-server.jar’ with the args ‘[-classpath, C:\jonathan\jonathan_2012.05.11-13.47.29.ear\jonathan-server.jar, -protocols, jrmp, -invokecmd]’.
org.ow2.jonas.service.ServiceException : Problems when invoking main method from GenIC: java.lang.RuntimeException: error in fastrmic (null)
at org.ow2.jonas.generators.genic.wrapper.GenicServiceWrapper.callGenic(GenicServiceWrapper.java:79)
at org.ow2.jonas.ejb2.internal.JOnASEJBService.__callGenic(JOnASEJBService.java:2017)[/java]
Quickfix
Edit $JONAS_BASE/conf/jonas.properties.
The properties jonas.services and jonas.service.ejb2.auto-genic must be consistent.
Especially, if GenIC is enabled (jonas.service.ejb2.auto-genic true), then check ejb2 is among the services pointed at by jonas.services, eg:
jonas.services jtm,db,security,resource,ejb2,web,ear.
IntelliJ IDEA / Unsupported classpath format eclipse
Case
The project on which I work is built on Eclipse and Ant. I am trying to migrate it to Maven 3.0. I thought to do this within IntelliJ IDEA.
Once the pom.xml was created, I wanted to revert to a configuration based on Eclipse’s .classpath file.
Then IntelliJ IDEA crashes. On starting up again, I get the following error
[java]Cannot load module file ‘jonathanModule’ Unsupported classpath format eclipse[/java]
Quick Fix
For a reason I ignore, Eclipse integration plugin was disabled. To restore Eclipse compatibility, simply do enable Eclipse integration in the plugin preference menu of IntelliJ IDEA.