Archive for the ‘General’ Category
[DevoxxFR2012] Advanced Android Patterns: Mastering Services, Content Providers, and Asynchronous Operations
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 delves into Mathias Seguy’s continuation of essential Android development concepts, emphasizing services for background tasks, content providers for data sharing, and patterns for lifecycle synchronization. Building on foundational elements, it analyzes implementation strategies for bound/unbound services, CRUD operations in providers, and thread management with handlers/AsyncTasks. Within Android’s resource-constrained environment, the discussion evaluates techniques for internationalization, resource optimization, and database integration. Through detailed code examples, it assesses implications for application responsiveness, data integrity, and cross-app interoperability, guiding developers toward efficient, maintainable architectures.
Implementing Services for Background Processing
Services enable persistent operations independent of UI, running in the application’s main thread—necessitating offloading to avoid ANRs. Mathias distinguishes unbound (started via startService(), autonomous) from bound (via bindService(), allowing communication).
Lifecycle binding is critical: Align service states with calling components using booleans for running/pausing. Code for an unbound service:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start task
return START_STICKY; // Restart if killed
}
@Override
public void onDestroy() {
// Cleanup
}
}
Bound services use Binder for IPC:
public class MyBoundService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyBoundService getService() {
return MyBoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
These ensure tasks like downloads persist, enhancing user experience without freezing interfaces.
Crafting Content Providers for Data Exposure
Content providers standardize data access across apps, using URIs for queries. Mathias outlines creation: Extend ContentProvider, define URIs via UriMatcher.
CRUD implementation:
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(DBHelper.MY_TABLE);
if (matcher.match(uri) == ITEM) {
qb.appendWhere(DBHelper.ID + "=" + uri.getLastPathSegment());
}
return db.query(qb.getTables(), projection, qb.getWhere(), selectionArgs, null, null, sortOrder);
}
Manifest declaration:
<provider
android:name=".MyProvider"
android:authorities="com.example.provider"
android:exported="true"
android:readPermission="com.example.READ"
android:writePermission="com.example.WRITE" />
This facilitates secure sharing, like contacts or media, promoting modular ecosystems.
Asynchronous Patterns and Resource Management
Asynchrony prevents UI blocks: Handlers for UI updates, AsyncTasks for background work. Pattern: Bind threads to activity lifecycles with flags.
onRetainNonConfigurationInstance() passes objects across rotations (pre-Fragments):
@Override
public Object onRetainNonConfigurationInstance() {
return myThread;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myThread = (MyThread) getLastNonConfigurationInstance();
if (myThread == null) {
myThread = new MyThread();
}
}
Resources: Externalize strings in values/strings.xml for localization; use qualifiers like values-fr for French.
These patterns optimize for device variability, ensuring fluid performance.
Database Integration and Permissions
SQLite via SQLiteOpenHelper manages schemas:
public class DBHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + MY_TABLE + " (_id INTEGER PRIMARY KEY, name TEXT);");
}
}
Permissions in manifest control access, balancing security with functionality.
Testing and Project Management Strategies
Unit tests with JUnit; instrumentation via AndroidJUnitRunner. Maven for builds, Hudson/Jenkins for CI.
Implications: These foster reliable apps, mitigating fragmentation. In enterprise mobility, they enable scalable, secure solutions.
Mathias’s methodical breakdown equips developers for real-world challenges.
Links:
[DevoxxFR2012] 55 Lesser-Known Features of Java 7: Unveiling Hidden Enhancements Across the Platform
Lecturer
David Delabassee serves as a Director of Developer Relations in the Java Platform Group at Oracle, where he champions Java technologies worldwide through presentations, technical articles, and open-source engagements. Previously at Sun Microsystems for a decade, he focused on end-to-end Java implementations, from smart cards to high-end servers. A member of the Devoxx Belgium steering committee, David co-hosts the Inside Java Podcast and maintains a blog at delabassee.com. He holds Belgian nationality and has spoken at numerous conferences and Java User Groups.
Abstract
This article investigates David Delabassee’s rapid-fire presentation on 55 underappreciated features of Java 7, released in 2011, extending beyond well-known additions like Project Coin, Fork/Join, NIO.2, and invokedynamic. It categorizes enhancements across core libraries, security, internationalization, graphics, and more, analyzing their practical utilities and implementation details. Positioned as a post-Sun acquisition milestone under Oracle, the discussion evaluates how these refinements bolster platform stability, performance, and developer productivity. Through code demonstrations and comparisons to prior versions, it assesses implications for migration, legacy code maintenance, and modern application design, emphasizing Java 7’s role in bridging to future iterations like Java 8.
Core Language and Library Improvements
Java 7 introduced subtle yet impactful tweaks to foundational elements, addressing longstanding pain points. David highlights enhanced exception handling: multi-catch clauses consolidate try-catch blocks for related exceptions, reducing redundancy:
try {
// Code
} catch (IOException | SQLException e) {
// Handle
}
String switches leverage interned strings for efficient comparisons, useful in parsing:
switch (input) {
case "start": // Action
break;
// ...
}
Underscores in numeric literals improve readability for large numbers: long creditCard = 1234_5678_9012_3456L;.
Library updates include Objects class utilities like requireNonNull() for null checks, and BitSet enhancements with valueOf() for byte/long array conversions. These foster cleaner, more maintainable code, mitigating common errors in enterprise applications.
Security and Cryptography Advancements
Security received substantial bolstering, crucial amid rising threats. David details elliptic curve cryptography integration, offering stronger keys with smaller sizes for SSL/TLS. Algorithm disabling via jdk.security.provider.disabledAlgorithms property enhances compliance.
SChannel provider on Windows improves native integration, while JSSE updates support SNI for virtual hosting. These fortify networked applications, essential for cloud and web services, reducing vulnerability exposure without external libraries.
Internationalization and Locale Refinements
Java 7 refined locale handling for global apps. Unicode 6.0 support adds scripts like Batak, enhancing text processing. Locale enhancements include script, variant, and extension keys:
Locale loc = new Locale.Builder().setLanguage("fr").setRegion("FR").setScript("Latn").build();
Currency updates reflect ISO 4217 changes, with getAvailableCurrencies() listing supported ones. NumberFormat improvements allow custom symbols, aiding financial software. These ensure accurate, culturally sensitive representations, vital for international markets.
Graphics and UI Toolkit Upgrades
Swing and AWT saw usability boosts. Translucent/shaped windows via GraphicsDevice enable modern UIs:
window.setOpacity(0.5f);
Nimbus look-and-feel, now default in some contexts, provides scalable, themeable components. JLayer adds decoration layers for effects like blurring. These empower richer desktop apps, aligning Java with contemporary design trends.
Performance and JVM Optimizations
JVM internals evolved for efficiency. Tiered compilation combines client/server compilers for faster startups and peak performance. G1 garbage collector, experimental in Java 7, targets low-pause collections for large heaps.
Compressed oops extend 32-bit addressing to 64-bit, reducing memory footprint. These optimizations benefit server-side applications, improving throughput and responsiveness in high-load scenarios.
Migration Considerations and Ecosystem Impact
Adopting Java 7 involves assessing compatibility, given end-of-life for Java 6. David notes seamless transitions for most code, but highlights needs like updating deprecated APIs. Tools like javac -Xlint warn of issues.
Ecosystem-wise, Java 7 paved for Java 8’s lambdas, solidifying Java’s enterprise dominance. Implications include smoother upgrades, enhanced security postures, and broader internationalization, encouraging developers to leverage these for robust, future-proof systems.
Links:
Depart de Sungard Global Services
Apres plusieurs annees au sein de Cadextan puis Sungard Consulting Services et enfin Sungard Global Services, j’ai souhaite donner une nouvelle impulsion a ma carriere et affronter de nouveaux challenges. Voila pourquoi, corollairement a ma fin de mission chez Amundi AM, j’ai quitte Sungard Global Services vendredi dernier.
7 annees, 4 missions (Sungard-Finance / GP3, Ixis CIB, BNP Arbitrage, Amundi AM), des dizaines d’heures de formations dispensees, des douzaines de CVs recus/tries/selectionnes/forwardes, des centaines de jours de travail, des centaines de kilometres parcourus et une seule passion: Java!
Je tiens a remercier les equipes de Sungard Global Services -consultants, administratifs, managers, direction, etc.- pour ces 7 annees passees a travailler a leurs cotes. J’ai appris enormement de choses et rencontre beaucoup de personnes ayant de grandes qualites humaines. Sungard Global Services est une belle reussite, passee en quelques annees de 100 personnes en France a plus de 500 en Europe, dans des conditions macro-economiques pas toujours les plus favorables. Je suis fier des accomplissements effectues et d’avoir apporte ma contribution a cette aventure.
Leaving Sungard Global Services
After seven years in Cadextan, then Sungard Global Services, I wanted to give new impetus to my career and face new challenges. That is why, at the end of my position in Amundi AM, I left Sungard Global Services last Friday.
I’d like to thank the staff of Sungard Global Services-consultants, administrators, managers, etc. – for these seven years spent working on their sides. I learnt much and met many people with great human qualities. Sungard Global Services is a great success, that changed in a few years from a 100-people company in France to than 500-people in Europe. I am proud to have been part of these successful achievements and adventure.
Leaving Amundi AM
After a couple of months spent as technical expert, transverse architect and manager of project “Reliability and Stabilization”, I left Amundi AM last Friday. I faced exciting and arduous subjects, such us OSGi, JOnAS, JVM customization, EJB2 to EJB3 migration, webservices upgrade, Decalog AS leaks, etc.
I would like to thank the whole teams that greeted me, and especially among them Antoine BODY and Jean-Guillaume BATTAGLIA.
[DevoxxFR2012] Jazz Platform: Fostering Collaborative Software Development Through Integrated Tools
Lecturer
Florent Benoit leads the OW2 EasyBeans open-source project and contributes significantly to the OW2 JOnAS application server. An expert in OSGi and Java EE, he provides architectural guidance on major Bull projects. Member of the Java EE 6 expert group for EJB 3.1 specifications, Florent holds a Master’s in Computer Engineering from Joseph Fourier University, Grenoble. He speaks at open-source conferences like JavaOne and Solutions Linux. Alexis Gaches specializes in automating software development lifecycles. Joining the Jazz movement in 2008, he architects Jazz solutions for IBM Rational, collaborating with French enterprises on agile practices for application management.
Abstract
This article assesses Florent Benoit and Alexis Gaches’s overview of IBM’s Jazz platform, aimed at streamlining collaborative software development from requirements to deployment. It dissects tools for requirements management, architecture modeling, implementation, building, testing, and project oversight. Positioned as a response to fragmented processes, the analysis reviews integration mechanisms, open-source alignments, and deployment options. Through demonstrations, it evaluates benefits for agility, traceability, and efficiency, alongside implications for organizational adoption and tool interoperability in diverse environments.
Rationale and Architecture of Jazz Platform
Jazz addresses silos in development by promoting unified collaboration. Florent outlines its genesis: enhancing processes across lifecycle stages—requirements, design, coding, builds, tests, management. Core philosophy: Tools should interconnect, enabling traceability from user stories to code commits.
Architecture leverages Eclipse for IDE integration, with Rational Team Concert (RTC) as hub. RTC supports SCM, work items, builds via Jazz Team Server. Open Services for Lifecycle Collaboration (OSLC) standardizes integrations, allowing third-party tools like Jira to link.
Alexis emphasizes agility: Iterative planning, dashboards for metrics, reducing manual handoffs.
Key Tools and Functionalities
Requirements Composer manages specs, linking to work items. Quality Manager handles testing, integrating with RTC for defect tracking.
Implementation uses Eclipse with RTC plugins for code management, supporting SVN/Git via bridges. Builds automate via Ant/Jenkins, with traceability to changesets.
Demonstrations showcase scenarios: From story creation to code delivery, highlighting real-time updates and approvals.
Deployment options: On-premise or cloud (JazzHub), with free tiers for small teams/academia.
Integration with Open-Source and Legacy Systems
Jazz embraces open-source: Eclipse foundation, OSLC for extensibility. Migrations from ClearCase/SVN use connectors, preserving history.
Challenges: Cultural shifts toward transparency; tool learning curves. Benefits: Reduced cycle times, improved quality via automated traceability.
Future Directions and Community Engagement
IBM’s openness: Public development on jazz.net, inviting contributions. Academic JazzHub fosters education.
Implications: Enhances enterprise agility, but requires commitment. In global teams, it bridges geographies; for startups, free tools lower barriers.
Jazz exemplifies integrated ALM, driving efficient, collaborative delivery.
Links:
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.
Hot Redeploy EJBs on JOnAS
Case
I ogten have to redeploy my JEE application on JOnAS. Basically, I stopped the server, copied the files (EAR, JAR, etc.), then started up again the server. I was fed up with implementing this method.
How to speed up?
Solution
Below is a proposal of solution, without any pretention (I am not fond of JOnAS…), based on an Ant script running under Maven. The code is commented, in a summary: build the EAR (or JAR, WAR, etc.), then copy it to JOnAS deploy folder, undeploy the beans, check which beans are still deployed, deploy the new version of the beans, check which beans are deployed:
[xml] <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>copyToJonas</id>
<phase>install</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="jonas.root" value="${env.JONAS_ROOT}"/>
<property name="jonas.base" value="${env.JONAS_BASE}"/>
<echo>Copy files</echo>
<copy todir="${jonas.base}/deploy" overwrite="true">
<fileset dir="${build.directory}/">
<include name="*.*ar"/>
</fileset>
</copy>
<echo>Undeploy beans</echo>
<exec executable="${jonas.root}/bin/jonas.bat">
<arg line="admin -r ${jonas.base}/deploy/${artifactId}-${version}.${packaging}"/>
</exec>
<echo>Currently deployed beans:</echo>
<exec executable="${jonas.root}/bin/jonas.bat">
<arg line="admin -j"/>
</exec>
<echo>Deploy beans:</echo>
<exec executable="${jonas.root}/bin/jonas.bat">
<arg line="admin -a ${jonas.base}/deploy/${artifactId}-${version}.${packaging}"/>
</exec>
<echo>Currently deployed beans:</echo>
<exec executable="${jonas.root}/bin/jonas.bat">
<arg line="admin -j"/>
</exec>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>[/xml]
At first glance I assume I should swap the phases of copying file and undeploying beans. Anyway, this scripts works for me and allows to redeploy after each mvn clean install 😉
[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.