Recent Posts
Archives

PostHeaderIcon (long tweet) Glassfish / Unsupported major.minor version 51.0

Case

On launching Glassfish 4 under Windows, I got the following error:

[java]asadmin.bat start-domain
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/glassfish/admin/cli/AsadminMain : Unsupported major.minor version 51.0[/java]

Quickfix

Glassfish 4 is JEE6-compatible, therefore run Glassfish 4 with JRE 7 instead of JRE 6.

As a reminder, here is the list of majors/minor versions:
[java]J2SE 8 = 52,
J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45[/java]

PostHeaderIcon (long tweet) Error injecting: org.codehaus.groovy.eclipse.compiler.GroovyEclipseCompiler

Case

On building a Groovy project with Maven, I got the following error:
[java]Error injecting: org.codehaus.groovy.eclipse.compiler.GroovyEclipseCompiler
java.lang.NoClassDefFoundError: org/codehaus/plexus/compiler/CompilerResult[/java]

Quick fix

Downgrade maven-compiler-plugin to version 3.0 instead of branch 2.3.X.

PostHeaderIcon Comment desactiver le NFC sur une carte bancaire?

Disclaimer: tout ce qui suit dans cet article est presente a des fins informatives. Toute action que vous pourrez entreprendre sera a vos risques et perils, et pourrait endommager votre carte de credit.

Cas

Les grandes banques francaises ont mis en place le NFC, ou “paiement sans contact” pour les marketteux. Les nouvelles cartes de credit, emises depuis fin 2012 apparemment, sont toutes equipees du NFC. Quel est le probleme? Eh bien tout simplement que la mise en place du NFC sur les cartes bancaires n’a pas ete securisee… Il s’agit d’un echec cuisant de la part des societes editrices (Visa, Master Card, etc.), qui n’ont pas ete capables d’entourer leur projet d’un peu de rigueur, technique et fonctionnelle, assurant un minimum de securisation : on ne demande pas non plus un coffre fort, mais juste qu’un quidam dans le metro ne puisse pas chipper les numeros de carte bleue des autres voyageurs.
Plus de details concernant les failles du NFC dans ces liens:

De mon cote, apres avoir joue avec du code librement telechargeable sur le net (comme readnfccc) sur mon telephone (un Nexus S de base avec “lecteur” NFC), la decision a ete claire, nette et immediate: pas de NFC sur ma carte!

J’ai donc informe mon banquier de mon refus il y a quelques mois. Las, lors du renouvellement de ma carte, la nouvelle comportait bien du NFC. J’ai bataille avec mon banquier, et j’ai meme demarre les demarches pour fermer mon compte. Cependant, meme s’il est desactive (Boursorama par exemple le propose), le module NFC sera present sur les cartes de toutes les banques. J’etais donc bien ennuye et j’ai donc refuse d’activer ma carte pendant plusieurs mois.

Trois choix s’offraient alors a moi: capituler en rase campagne, vivre de cheques et d’especes, ou bien faire le travail de messieurs les banquiers et securiser moi-meme ma carte: geek power!

Bobine, induction… Physique du NFC

En resume: la carte bancaire contient une puce NFC (je dirais meme RFID, mais je ne suis pas sur de mon coup), branchee a une bobine electrique plate, egalement integree a la carte bancaire. Lorsque la carte bancaire se trouve soumise a un champ magnetique, un courant est cree par induction (vecteur F = q * produitVectoriel(vecteur vitesse, vecteur champ magnetique), d’apres mes souvenirs).

Par consequent, pour desactiver le NFC, il suffit de detruire la puce NFC ou de casser l’induction, en coupant la bobine.

Suppression du NFC

Puce

La premiere solution est mentionnee par plusieurs sites americains: en effet, sur les cartes US (le “paiment sans contact” s’y appelle “PayWave”), il n’y a qu’une bande magnetique, et l’emplacement de la puce NFC est visible a l’oeil nu en inclinant la carte: la surface de la carte y est legerement creusee. Il suffit alors de detruire ou retirer la puce NFC, avec un cutteur, un compas, ou tout autre objet tranchant.

Sur une carte francaise cela n’est pas possible: en effet, nos cartes de credit comportent une puce (utilisee pour le paiment chez les commercants) en plus de la bande magnetique (utilisee pour les retraits d’especes en agences). Or, la puce NFC est physiquement superposee a la puce propre a la carte… Donc, a moins d’y aller au microscope, impossible de detruire la puce NFC sans rendre la carte inutilisable pour les achats.

Bobine

Reste donc la faille de la bobine.

La premiere etape consiste a reconnaitre le parcours de la bobine dans la carte, et identifier un endroit d’incision. Pour cela, se mettre dans le noir complet et utiliser une source de lumiere puissante, type torche. Le flash du Nexus S n’est pas parfait, mais il donne de bons resultats.
La photo suivante donne une idee du parcours de la bobine sur une carte Visa factice delivree par BNP Paribas:


Parcours de la bobine NFC (lien Google+)

Attention! les circuits varient selon les banques, les societes emetrices des cartes, voire meme le type de carte (Electron, classique, Gold, Black).

Il convient donc de couper le circuit en un endroit, quelconque, tout en prenant soin de ne pas toucher a la bande magnetique ni a la puce de la carte.

Dans l’image suivante est representee (en rouge gras) l’incision que j’ai faite a la carte, a l’aide d’une bete paire de ciseaux: du cote droit de la carte, d’une largeur de 10mm, parallelement a la longueur, et a un niveau de 38mm en partant de la base de la carte.


Incision dans la bobine NFC d’une carte de credit (lien Google+)

Pour rappel, une carte de credit standard obeit a la norme ISO-7810 ID-1 et sa taille est de 86mm sur 54mm.

Conclusion

Apres cette operation chirurgicale -n’exagerons pas non plus-, j’ai pu verifier que le NFC etait totalement desactive, mais que les retraits d’especes ainsi que les paiements classiques chez les commercants, c’est-a-dire en assurant un contact physique et en entrant le code PIN, continuaient a fonctionner en France. Pour l’heure, je n’ai teste ni aux USA ni en Inde :-D, mais j’ai bon espoir qu’il n’y ait pas de souci.

Toute personne de tendance paranoiaque en terme de securite informatique pourra egalement calfeutrer sa carte bancaire dans une feuille d’aluminium hermetique, operant l’effet d’une cage de Faraday.

Cela etant, je reste stupefait par l’enorme echec de Visa et Master Card dans la mise en place du NFC. Un tel manquement aux regles de securite elementaires est consternant. Comment peut-on pretendre developper le commerce en laissante beantes de telles failles de securite?

De meme, je reste stupefait de la legerete avec laquelle les banques traitent ce scandale du NFC: il est du ressort des banques de detail de fournir des moyens de paiement un minimum securises. A tout le moins, on aurait attendu des banques qu’elles laissent le choix d’avoir une carte avec ou sans NFC, et non d’imposer d’office un choix plus que contestable. Ce n’etait pas a moi de securiser ma carte, c’etait a ma banque de m’en fournir une suffisamment blindee ; de plus, je doute de la capacite de Mme Michu d’effectuer les memes operations que moi.

Bref: carton rouge pour toutes les institutions impliquees dans la diffusion des cartes NFC!

PostHeaderIcon [DevoxxFR2013] Arquillian for Simple and Effective Web Tests

Lecturer

Alexis Hassler is a Java developer with over fifteen years of experience. He operates as an independent professional, engaging in coding, training, and supporting enterprises to enhance their Java development and deployment practices. As co-leader of the Lyon Java User Group, he contributes to community events like the Mix-IT conference in Lyon.

Abstract

Alexis Hassler’s session explores Arquillian’s capabilities for testing web applications, extending beyond Java EE components to comprehensive integration testing. Demonstrating extensions like Drone, Graphene, and Warp, he illustrates client-side and server-side testing methodologies. The discussion analyzes setup, execution, and benefits, emphasizing real-world testing that verifies both client interactions and server states for robust applications.

Core Concepts of Arquillian: Integration Testing Reversed

Hassler introduces Arquillian as a tool for integration testing Java EE components, defining a component as an entity like an EJB with injected dependencies, transactional, and security contexts. Unlike embedding containers in tests, Arquillian packages the component with tests and deploys to a container, inverting the process for realistic environments.

A basic test class uses JUnit with an Arquillian runner. The @Deployment annotation creates a testable archive (e.g., WAR) containing classes and resources. Methods like @Test execute within the container, accessing injected resources seamlessly.

This approach ensures tests run in production-like settings, catching issues early. Hassler contrasts with traditional unit tests, highlighting Arquillian’s focus on integrated behaviors.

Extending to Web Testing: Drone and Graphene for Client-Side Interactions

For web applications, Hassler leverages Drone and Graphene extensions, combining Arquillian’s deployment with Selenium’s browser automation. Drone instantiates WebDriver instances; Graphene enhances with guards for AJAX handling.

In setup, specify a managed container like JBoss AS in arquillian.xml. Tests deploy the app, then use @Drone-annotated browsers to interact: navigate via @ArquillianResource URLs, fill forms, assert outcomes.

Graphene’s guards wait for requests, ensuring reliable tests amid asynchronous behaviors. This client-mode testing (@RunAsClient) simulates user interactions, verifying HTTP responses without server-side access.

Code example:

@Drone
WebDriver browser;

@ArquillianResource
URL deploymentUrl;

@Test
@RunAsClient
public void testLogin() {
    browser.get(deploymentUrl + "login.jsf");
    // Interact and assert
}

This deploys, browses, and validates, bridging unit and functional testing.

Advanced Verification with Warp: Bridging Client and Server States

To inspect server-side states during client tests, Hassler introduces Warp. It wraps requests with payloads, executing inspections on the server before/after phases.

Define inspections extending WarpInspection, annotating with @WarpTest. Use @BeforeServlet/@AfterServlet for timing. Deploy via @WarpDeployment.

Example: Verify session attributes post-login. Client triggers action; Warp asserts server-side.

public class SessionInspection extends WarpInspection {
    @AfterServlet
    public void checkSession() {
        // Assert session values
    }
}

Warp enables “real tests” by combining client simulations with server validations, detecting mismatches invisible to pure client tests.

Hassler notes Warp’s alpha status, advising community forums for issues.

Implications for Development Practices: Flexibility and Community Support

Arquillian’s modularity allows mixing modes: @RunAsClient for web, in-container for components. This flexibility suits diverse apps, from simple servlets to complex JSF.

Challenges include initial setup—choosing extensions, versions, resolving conflicts. Documentation is evolving; forums on JBoss.org are responsive, often from developers.

Hassler encourages adoption for effective testing, reducing deployment surprises. Community involvement accelerates learning, fostering better practices.

In essence, Arquillian with extensions empowers thorough, efficient web testing, aligning development with production realities.

Links:

PostHeaderIcon [DevoxxFR2013] NFC: Facilitating Mobile Interactions with the Environment

Lecturer

Romain Menetrier is a developer passionate about internet and mobile platforms. He co-organizes the Paris Android User Group and founded Macala for mobile solutions. Previously CTO at Connecthings, a European NFC leader, he now serves as NFC solutions architect at Orange.

Abstract

Romain Menetrier’s talk introduces Near Field Communication (NFC), tracing its RFID and smart card roots while focusing on mobile implementations, especially Android. He demonstrates practical uses like payments and data exchange, explaining standards, tag types, and Android APIs. Through live examples, he highlights NFC’s security via proximity and contextual potential, advocating its adoption for simplified interactions.

Origins and Fundamentals: From RFID to NFC Standards

Menetrier traces NFC to RFID and contactless cards, operating via magnetic field modulation at under 10cm for security—requiring physical presence. An antenna induces power in passive tags, enabling data return without batteries.

Standards: ISO 14443 (cards), 15693 (tags), with modes like reader/writer (phone reads/writes tags), peer-to-peer (device-to-device), and card emulation (phone as card). Frequencies at 13.56MHz allow small antennas in phones.

Tag types vary: Type 1-4 differ in capacity (48B to 32KB), speed, and protocols. NDEF (NFC Data Exchange Format) standardizes data as records with type, ID, payload—e.g., URLs, text, MIME.

Android drives diffusion: since Gingerbread, APIs handle intents on tag discovery, enabling apps to read/write without foreground requirements via tech-lists.

Practical Implementations: Android Apps for Tag Interaction and Peer-to-Peer

Menetrier demos Android apps: reading tags dispatches intents; apps filter via manifests for specific techs (e.g., NfcA). Reading parses NDEF messages into records, extracting payloads like URLs for browser launch.

Writing: create NDEF records (e.g., URI), form messages, write via NfcAdapter. Locking tags prevents overwrites.

Peer-to-peer uses Android Beam (SNEP protocol): share data by touching devices. Implement via CreateNdefMessageCallback for message creation, OnNdefPushCompleteCallback for confirmation.

Code snippet:

NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
adapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        return new NdefMessage(new NdefRecord[]{createUriRecord("http://example.com")});
    }
}, this);

This enables URL sharing.

Security: short range thwarts remote attacks; presence confirms intent. Contexts from tag locations enhance applications, like venue-specific info.

Everyday Applications and Future Prospects: Payments, Access, and Tracking

Common uses: payments (e.g., Cityzi in France, emulating cards via SIM-secured elements), transport (Navigo integration), access control (badges). Tags in ads track interactions, gauging interest beyond views.

Enterprise: unified NFC cards for canteen, entry—multiple IDs on one chip. Phones emulate cards, even off (via SIM linkage), blockable remotely.

Challenges: ecosystem fragmentation (operators control SIM), but growing adoption. Menetrier sees NFC simplifying interactions, with Android pivotal.

In summary, NFC’s proximity fosters secure, contextual mobile-environment links, poised for widespread use.

Relevant Links and Hashtags

Links:

PostHeaderIcon [DevoxxBE2012] When Geek Leaks

Neal Ford, a software architect at ThoughtWorks and author known for his work on enterprise applications, delivered a keynote exploring “geek leaking”—the spillover of deep expertise from one domain into another, fostering innovation. Neal, an international speaker with insights into design and delivery, tied this concept to his book “Presentation Patterns,” but expanded it to broader intellectual pursuits.

He defined “geek” as an enthusiast whose passion in one area influences others, creating synergies. Neal illustrated with examples like Richard Feynman’s interdisciplinary contributions, from physics to biology, showing how questioning fundamentals drives breakthroughs.

Neal connected this to software, urging developers to apply scientific methods—hypothesis, experimentation, analysis—to projects. He critiqued over-reliance on authority, advocating first-principles thinking to challenge assumptions.

Drawing from history, Neal discussed how paradigm shifts, like Galileo’s heliocentrism, exemplify geek leaking by integrating new evidence across fields.

In technology, he highlighted tools enabling this, such as domain-specific languages blending syntaxes for efficiency.

Origins of Intellectual Cross-Pollination

Neal traced geek leaking to Feynman’s life, where physics informed lock-picking and bongo playing, emphasizing curiosity over rote knowledge. He paralleled this to software, where patterns from one language inspire another.

He referenced Thomas Kuhn’s “Structure of Scientific Revolutions,” explaining how anomalies lead to paradigm shifts, akin to evolving tech stacks.

Applying Scientific Rigor in Development

Neal advocated embracing hypotheses in coding, testing ideas empirically rather than debating theoretically. He cited examples like performance tuning, where measurements debunk intuitions.

He introduced the “jeweler’s hammer”—gentle taps revealing flaws—urging subtle probes in designs to uncover weaknesses early.

Historical Lessons and Modern Tools

Discussing Challenger disaster, Neal showed Feynman’s simple demonstration exposing engineering flaws, stressing clarity in communication.

He critiqued poor presentations, linking to Edward Tufte’s analysis of Columbia shuttle slides, where buried details caused tragedy.

Neal promoted tools like DSLs for expressive code, and polyglot programming to borrow strengths across languages.

Fostering Innovation Through Curiosity

Encouraging geek leaking, Neal suggested exploring adjacent fields, like biology informing algorithms (genetic programming).

He emphasized self-skepticism, quoting Feynman on fooling oneself, and applying scientific method to validate ideas.

Neal concluded by urging first-principles reevaluation, ensuring solutions align with core problems, not outdated assumptions.

His keynote inspired developers to let expertise leak, driving creative, robust solutions.

Links:

PostHeaderIcon [DevoxxFR2013] FLATMAP ZAT SHIT: Monads Explained to Geeks

Lecturer

François Sarradin is a Java and lambda developer, serving as a technical capitalization manager. He contributes to the Brown Bag Lunch initiative, sharing expertise through presentations.

Abstract

François Sarradin’s session introduces monads in functional programming, using Scala and Java 8 examples to demystify their utility. He addresses handling errors, asynchrony, and technical concerns without cluttering business logic, employing monadic structures like Try and Future. The talk analyzes code transformations for cleaner, composable designs, highlighting monads’ role in aspect-oriented programming and drawing parallels to AOP frameworks.

The Problem: Technical Debt Obscuring Business Logic

Sarradin illustrates a common plight: initial clean code accumulates technical safeguards—null checks, try-catch blocks, synchronization—eroding readability and productivity. He proposes separating concerns: keep business logic pure, inject technical aspects via mechanisms akin to aspect-oriented programming (AOP).

Using AOP tools like AspectJ or Spring AOP declares cross-cutting concerns (e.g., logging, error handling) separately, leveraging compilers for coherence. This maintains original code structure while addressing realities like exceptions or async calls.

An example application in Scala computes total balance across bank accounts, initially straightforward but vulnerable. Technical intrusions (e.g., if-null, try-catch) bloat it, prompting a search for elegant solutions.

Introducing Monads: Error Handling with Try

To manage errors without pervasive checks, Sarradin introduces the Try monad in Scala: a container wrapping success (Success(value)) or failure (Failure(exception)). This allows chaining operations via flatMap and map, propagating errors implicitly.

Transforming the balance app: wrap account retrieval in Try, use for-comprehensions (sugaring flatMap/map) for composition. If any step fails, the whole computation fails gracefully, without explicit exception handling.

Code evolves from imperative checks to declarative chains:

val total = for {
  account1 <- Try(getAccount(bank1))
  account2 <- Try(getAccount(bank2))
  balance1 <- Try(getBalance(account1))
  balance2 <- Try(getBalance(account2))
} yield balance1 + balance2

This yields Try[Double], inspectable via isSuccess, get, or getOrElse. Monads here abstract error propagation, enhancing modularity.

Java 8’s Optional partially mirrors this but lacks full monadic power; Sarradin implements a custom Try for illustration, using abstract classes with Success/Failure subclasses.

Extending to Asynchrony: Futures for Non-Blocking Computations

Asynchrony poses similar issues: callbacks or blocking awaits disrupt flow. Scala’s Future monad encapsulates eventual values, enabling composition without blocking.

In the app, wrap async calls in Future: use flatMap to chain, ensuring non-blocking execution. For-comprehensions again simplify:

val totalFuture = for {
  account1 <- Future(getAccountAsync(bank1))
  account2 <- Future(getAccountAsync(bank2))
  balance1 <- Future(getBalanceAsync(account1))
  balance2 <- Future(getBalanceAsync(account2))
} yield balance1 + balance2

totalFuture completes asynchronously; callbacks via onComplete handle results. This maintains sequential appearance while parallelizing under the hood.

Sarradin contrasts with Java 8’s CompletableFuture, which offers thenApply/thenCompose for similar chaining, though less idiomatic without for-comprehensions.

Monads as a Unifying Abstraction: Synthesis and Implications

Monads generalize: a type M[A] with map (transform value) and flatMap (chain computations). They inject contexts (error, future) into pure functions, separating concerns.

In the app, combining Try and Future (via Scalaz’s EitherT or custom) handles both errors and asynchrony. This AOP-like injection leverages type systems for safety, contrasting annotation-based AOP.

Java 8 approximates with lambdas and CompletableFuture/Optional, but lacks Scala’s expressiveness. Custom implementations reveal monads’ essence: abstract class with map/flatMap, subclasses for Success/Failure.

Sarradin concludes monads enhance composability, reducing boilerplate for robust, maintainable code in functional paradigms.

Relevant Links and Hashtags

Links:

PostHeaderIcon [DevoxxFR2013] NIO, Not So Simple?

Lecturer

Emmanuel Lecharny is a member of the Apache Software Foundation, contributing to projects like Apache Directory Server and Apache MINA. He also mentors incubating projects such as Deft and Syncope. As founder of his own company, he collaborates on OpenLDAP development through partnerships.

Abstract

Emmanuel Lecharny’s presentation delves into the intricacies of network input/output (NIO) in Java, contrasting it with blocking I/O (BIO) and asynchronous I/O (AIO). Through detailed explanations and code examples, he explores concurrency management, scalability, encoding/decoding, and performance in building efficient servers using Apache MINA. The talk emphasizes practical challenges and solutions, advocating framework use to simplify complex implementations while highlighting system-level considerations like buffers and selectors.

Fundamentals of I/O Models: BIO, NIO, and AIO Compared

Lecharny begins by outlining the three primary I/O paradigms in Java: blocking I/O (BIO), non-blocking I/O (NIO), and asynchronous I/O (AIO). BIO, the traditional model, assigns a thread per connection, blocking until data arrives. This simplicity suits low-connection scenarios but falters under high load, as threads consume resources—up to 1MB stack each—leading to context switching overhead.

NIO introduces selectors and channels, enabling a single thread to monitor multiple connections via events like OP_READ or OP_WRITE. This non-blocking approach scales better, handling thousands of connections without proportional threads. However, it requires manual state management, as partial reads/writes necessitate buffering.

AIO, added in Java 7, builds on NIO with callbacks or futures for completion notifications, reducing polling needs. Yet, it demands careful handler design to avoid blocking the callback thread, often necessitating additional threading for processing.

These models address concurrency differently: BIO is straightforward but resource-intensive; NIO offers efficiency through event-driven multiplexing; AIO provides true asynchrony but with added complexity in callback handling.

Building Scalable Servers with Apache MINA: Core Components and Configuration

Apache MINA simplifies NIO/AIO development by abstracting low-level details. Lecharny demonstrates a basic UDP server: instantiate IoAcceptor, bind to a port, and set a handler for messages. The framework manages buffers, threading, and protocol encoding/decoding.

Key components include IoService (for acceptors/connectors), IoHandler (for events like messageReceived), and filters (e.g., logging, protocol codecs). Configuration involves thread pools: one for I/O (typically one thread suffices due to selectors), another for application logic to prevent blocking.

Scalability hinges on proper setup: use direct buffers for large data to avoid JVM heap copies, but heap buffers for small payloads in Java 7 for speed. MINA’s executor filter offloads heavy computations, maintaining responsiveness.

Code example:

DatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(new MyHandler());
SocketAddress address = new InetSocketAddress(port);
acceptor.bind(address);

This binds a UDP acceptor, ready for incoming datagrams.

Handling Data: Encoding, Decoding, and Buffer Management

Encoding/decoding is pivotal; MINA’s ProtocolCodecFilter uses encoders/decoders for byte-to-object conversion. Lecharny explains cumulative decoding for fragmented messages: maintain a buffer, append incoming data, and decode when complete (e.g., via length prefixes).

Buffers in NIO are crucial: ByteBuffer for data storage, with position, limit, and capacity. Direct buffers (allocateDirect) bypass JVM heap for zero-copy I/O, ideal for large transfers, but allocation is costlier. Heap buffers (allocate) are faster for small sizes.

Performance tests show Java 7 heap buffers outperforming direct ones up to 64KB; beyond, direct excels. UDP limits (64KB max) favor heap buffers.

Partial writes require looping until completion, tracking written bytes. MINA abstracts this, but understanding underlies effective use.

public class LengthPrefixedDecoder extends CumulativeProtocolDecoder {
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) {
        if (in.remaining() < 4) return false;
        int length = in.getInt();
        if (in.remaining() < length) return false;
        // Decode data
        return true;
    }
}

This decoder checks for complete messages via prefixed length.

Concurrency and Performance Optimization in High-Load Scenarios

Concurrency management involves separating I/O from processing: MINA’s single I/O thread uses selectors for event polling, dispatching to worker pools. Avoid blocking in handlers; use executors for database queries or computations.

Scalability tests: on a quad-core machine, MINA handles 10,000+ connections efficiently. UDP benchmarks show Java 7 20-30% faster than Java 6, nearing native speeds. TCP may lag BIO slightly due to overhead, but NIO/AIO shine in connection volume.

Common pitfalls: over-allocating threads (match to cores), ignoring backpressure (queue overloads), and poor buffer sizing. Monitor via JMX: MINA exposes metrics for queued events, throughput.

Lecharny stresses: network rarely bottlenecks; focus on application I/O (databases, disks). 10Gbps networks outpace SSDs, so optimize backend.

Practical Examples: From Simple Servers to Real-World Applications

Lecharny presents realistic servers: a basic echo server with MINA requires minimal code—set acceptor, handler, bind. For protocols like LDAP, integrate codecs for ASN.1 encoding.

In Directory Server, NIO enables handling massive concurrent searches without thread explosion. MINA’s modularity allows stacking filters: SSL for security, compression for efficiency.

For UDP-based services (e.g., DNS), similar setup but with DatagramAcceptor. Handle datagram fragmentation manually if exceeding MTU.

AIO variant: Use AsyncIoAcceptor with CompletionHandlers for callbacks, reducing selector polling.

These examples illustrate MINA’s brevity: functional servers in under 50 lines, versus hundreds in raw NIO.

Implications and Recommendations for NIO Adoption

NIO/AIO demand understanding OS-level mechanics: epoll (Linux) vs. kqueue (BSD) for selectors, impacting portability. Java abstracts this, but edge cases (e.g., IPv6) require vigilance.

Performance gains are situational: BIO suffices for <1000 connections; NIO for scalability. Frameworks like MINA or Netty mitigate complexity, encapsulating best practices.

Lecharny concludes: embrace frameworks to avoid reinventing; comprehend fundamentals for troubleshooting. Java 7+ enhancements make NIO more viable, but test rigorously under load.

Relevant Links and Hashtags

Links:

PostHeaderIcon [DevoxxBE2012] Weld-OSGi in Action

Mathieu Ancelin and Matthieu Clochard, software engineers at SERLI specializing in Java EE and modular systems, showcased the synergy between CDI, OSGi, and Weld in their Weld-OSGi framework during DevoxxBE2012. Mathieu, a member of the CDI 1.1 expert group and contributor to projects like GlassFish, collaborated with Matthieu, who focuses on OSGi integrations, to demonstrate how Weld-OSGi simplifies dynamic application assembly without added complexity.

They started with CDI basics, where dependency injection manages component lifecycles via annotations like @Inject. OSGi’s modularity, with bundles as deployment units and a dynamic service registry, complements this by allowing runtime changes. Weld-OSGi bridges them, enabling CDI beans to interact seamlessly with OSGi services.

A demo illustrated bootstrapping Weld-OSGi in an OSGi environment, registering bundles, and using extensions for event handling. They emphasized transparent service interactions, where CDI observes OSGi events for dynamic updates.

Mathieu and Matthieu highlighted Weld-OSGi’s role in making OSGi accessible, countering perceptions of its difficulty by leveraging CDI’s programming model.

Fundamentals of CDI and OSGi Integration

Mathieu explained CDI’s bean management, scopes, and qualifiers for precise injections. Matthieu detailed OSGi’s bundle lifecycle and service registry, where services publish and consume dynamically.

Weld-OSGi embeds CDI containers in OSGi, using extensions to observe bundle events and register services as beans. This allows injecting OSGi services into CDI components effortlessly.

Dynamic Features and Practical Demonstrations

They demonstrated service dynamism: publishing a service updates dependent beans automatically. Unpublishing triggers alternatives or errors, ensuring robustness.

Demos included hybrid applications where Java EE components interact with OSGi bundles via the registry, deploying parts dynamically without restarts.

Future Prospects and Community Engagement

Mathieu discussed ongoing work for hybrid servers like GlassFish, embedding Weld-OSGi for cleaner integrations. They referenced RFC 146, inspired by Weld-OSGi, for native CDI-OSGi support.

Encouraging trials, they pointed to GitHub repositories with examples and documentation, fostering feedback to evolve the framework.

Mathieu and Matthieu’s presentation illustrated Weld-OSGi’s potential to create fully dynamic modular applications, blending CDI’s elegance with OSGi’s power.

Links:

PostHeaderIcon [DevoxxFR2013] The Space Mountain of Enterprise Java Development

Lecturer

Florent Ramière brings over a decade of software development and project management experience. After years in the US at a software editor and a stint at Capgemini upon returning to France, he co-founded Jaxio with Nicolas Romanetti in 2005. Jaxio offers code generation via Celerio; in 2009, they launched SpringFuse.com, an online version. Active in Paris Java scenes like ParisJUG and Coding Dojos.

Abstract

Florent Ramière’s dynamic demonstration navigates enterprise Java development’s complexities, showcasing tools like Maven, Spring, JPA, and more in a live Eclipse session. Emphasizing practical efficiencies for data-heavy applications, he covers CRUD operations, testing, profiling, and CI. The talk reveals techniques for rapid, robust development, highlighting simplicity’s challenges and offering actionable insights for real-world projects.

Setting the Stage: Tools and Environment for Efficient Development

Ramière begins with audience polling: most work on Java EE/Spring applications involving databases, often exceeding 100 tables. He focuses on large-scale management apps, sharing experiences from consulting across projects.

Demonstrating in Eclipse with Jetty embedded, he launches an internationalized app using an in-memory database for independence. Maven builds the project; SpringFuse aggregates best practices.

Key promise: simplicity is hard; knowing tools accelerates work. If nothing new learned, a Mojito offered – or a fun fact on calculating light speed with chocolate.

The app handles accounts: listing, searching, navigating. CRUD dominates; business logic intersperses.

Core Operations: Querying, Validation, and Data Manipulation

Search uses query-by-example: fields like ‘admin’ or ‘Tokyo’ filter results. JPA with Hibernate enables this; Bean Validation ensures integrity.

Editing involves JSF with PrimeFaces for UI: dialogs, calendars, auto-completes. Commons and Guava libraries aid utilities; Lombok reduces boilerplate.

Saving triggers validations: required fields, formats. Excel exports via JXLS; imports validate before persisting.

Full-text search with Hibernate Search (Lucene) indexes entities, supporting fuzzy matches and facets.

@Entity
@Indexed
public class User {
    @Id
    private Long id;
    @Field(index=Index.YES, analyze=Analyze.YES)
    private String name;
    // ...
}

This annotates for indexing, enabling advanced queries.

Testing and Quality Assurance: From Unit to Integration

JUnit with Fest-Assert and Mockito tests services: mocking DAOs, verifying behaviors.

Selenium with Firefox automates UI tests: navigating, filling forms, asserting outcomes.

JMeter scripts load tests: threading simulates users, measuring throughput.

Sonar integrates for code reviews: violations, discussions directly in Eclipse.

@Test
public void testService() {
    User user = mock(User.class);
    when(user.getName()).thenReturn("Test");
    assertEquals("Test", service.getUserName(1L));
}

Mockito example for isolated testing.

Performance and Deployment: Profiling and Continuous Integration

JProfiler attaches for heap/thread analysis: identifying leaks, optimizing queries.

Hudson (now Jenkins) builds via Maven: compiling, testing, deploying WARs.

iSpace visualizes dependencies, aiding architecture.

Profiles manage environments: dev/test/prod configurations.

Navigating Complexities: Best Practices and Pitfalls

Ramière advises command-line Maven for reliability; avoid outdated WTP.

For large schemas, tools like SpringFuse generate CRUD, reducing tedium.

NoSQL suits big data, but relational fits structured needs; patterns transfer.

Embrace profiles for configurations; Git for code reviews alongside Sonar/Gerrit.

Impact of profilers on tests: significant, but use for targeted optimizations via thread dumps.

In conclusion, enterprise Java demands tool mastery for efficiency; simplicity emerges from knowledge.

Links: