Posts Tagged ‘DevoxxFR2013’
[DevoxxFR2013] WTF – What’s The Fold?
Lecturer
Olivier Croisier operates as a freelance Java expert, trainer, and speaker through Moka Technologies. With over twelve years in the field, he assists clients in Java 8 migrations, advanced stack development, and revitalizing team enthusiasm for coding.
Abstract
Olivier Croisier elucidates the fold concept from functional programming, demonstrating its abstraction of iteration for enhanced code expressiveness. Using Java 8 streams and Haskell parallels, he dissects implementations, applications in mapping/filtering/reducing, and performance implications. The analysis positions fold as a versatile pattern surpassing traditional loops, integrable even in pre-Java 8 environments.
Origins and Essence: Fold as Iterative Abstraction
Croisier traces fold to functional languages like Haskell, where it generalizes accumulation over collections. Left fold (foldl) processes sequentially; right fold (foldr) enables laziness.
In essence, fold applies a binary operation cumulatively: start with accumulator, combine with each element.
Java analogy: external iterators (for-loops) versus internal (streams). Fold internalizes control, yielding concise, composable code.
Implementing Fold in Java: From Basics to Streams
Pre-Java 8, Croisier crafts a utility:
public static <T, R> R fold(Collection<T> coll, R init, BiFunction<R, T, R> f) {
R acc = init;
for (T e : coll) acc = f.apply(acc, e);
return acc;
}
Usage: sum integers—fold(list, 0, (a, b) -> a + b).
Java 8 streams natively provide reduce (fold alias):
int sum = list.stream().reduce(0, Integer::sum);
Parallel streams distribute: .parallelStream().reduce().
Croisier notes identity requirement for parallelism; non-associative operations risk inconsistencies.
Beyond Reduction: Mapping, Filtering, and Collection Building
Fold transcends summing; rebuild collections:
List<String> mapped = fold(list, new ArrayList<>(), (acc, e) -> { acc.add(transform(e)); return acc; });
Filter via conditional accumulation. This unifies operations—map/filter as specialized folds.
Haskell’s foldr constructs lists lazily, enabling infinite structures. Java’s eager evaluation limits but streams offer similar chaining.
Expressive Power and Performance Trade-offs
Croisier contrasts verbose loops with declarative folds, enhancing readability/maintainability. Encapsulate patterns in methods for reuse/optimization.
Performance: sequential folds match loops; parallel leverages multicore but incurs overhead (threading, combining).
JVM optimizations (invokedynamic for lambdas) potentially outperform anonymous classes. Croisier advocates testing under load.
Versus map-reduce: fold suits in-memory; Hadoop for distributed big data.
Integration Strategies and Broader Implications
Adopt incrementally: utility class for legacy code. Java 8+ embraces streams.
Croisier views fold as expressivity tool—not replacing conditionals but abstracting mechanics.
Implications: functional paradigms ease concurrency, prepare for multicore era. Fold’s versatility—from reductions to transformations—elevates code abstraction.
Links:
[DevoxxFR2013] Security for Enterprises in a Cloudy and Mobile World
Lecturer
Ludovic Poitou serves as Product Manager at ForgeRock, overseeing directory products, and holds the position of General Manager for ForgeRock France. With a background in open-source Java and LDAP, he previously worked at Sun Microsystems as a developer and architect for directory solutions, later engaging in community management.
Abstract
Ludovic Poitou examines evolving enterprise security demands amid mobile proliferation, social networks, and cloud computing. Centering on identity management, he analyzes ForgeRock’s Open Identity Stack—an open-source Java solution—detailing standards like OAuth, OpenID Connect, and SCIM. The discussion evaluates impacts on information systems infrastructure and application architecture, advocating adaptive strategies for secure access in hybrid environments.
Shifting Paradigms: Mobile, Cloud, and Social Influences on Security
Poitou identifies three transformative trends reshaping information security: ubiquitous mobile devices, pervasive social platforms, and cloud services adoption. These necessitate reevaluating traditional perimeters, as data flows beyond firewalls to diverse endpoints.
Mobile introduces BYOD challenges—personal devices accessing corporate resources—demanding granular controls. Cloud shifts storage and processing externally, requiring federated trust. Social networks amplify identity federation needs for seamless yet secure interactions.
At the core lies identity management: provisioning, authentication, authorization, and storage across lifecycles. ForgeRock, emerging post-Sun acquisition, builds on open-source projects like OpenDJ (LDAP server) to deliver comprehensive solutions.
Core Components of Open Identity Stack: Directory, Access, and Federation
ForgeRock’s stack comprises OpenDJ for LDAP-based storage, OpenAM for access management, and OpenIDM for identity administration. OpenDJ handles scalable directories; OpenAM manages SSO, federation; OpenIDM orchestrates provisioning.
Poitou highlights Java foundations enabling portability. Development centers in Grenoble support global operations.
This modular approach allows tailored deployments, integrating with existing systems while supporting modern protocols.
Emerging Standards: OAuth, OpenID Connect, and SCIM for Interoperability
Addressing federation, Poitou details OAuth 2.0 for delegated authorization—clients obtain tokens without credentials. Variants include authorization code for web, implicit for browsers.
OpenID Connect layers identity atop OAuth, providing ID tokens (JWT) with user claims. This enables authenticated APIs, profile sharing.
SCIM standardizes user/group provisioning via REST, simplifying cloud integrations. Poitou contrasts with LDAP’s genericity, noting SCIM’s user-centric focus.
Code illustration (conceptual OAuth flow):
// Client requests token
HttpResponse response = client.execute(new HttpPost("token_endpoint"));
// Server validates, issues JWT
JWTClaimsSet claims = new JWTClaimsSet.Builder()
.subject(userId)
.build();
SignedJWT signedJWT = new SignedJWT(header, claims);
These standards facilitate secure, standardized exchanges.
Architectural Implications: Token-Based Authorization and Device Management
Traditional session cookies falter in mobile/cloud; tokens prevail. Applications validate JWTs statelessly, reducing server load.
Poitou discusses administrative token generation—pre-authorizing apps/devices without logins. OpenAM supports this for seamless access.
Infrastructure evolves: decouple authentication from apps via gateways. Hybrid models blend on-premise directories with cloud federation.
Challenges include token revocation, scope management. Solutions involve introspection endpoints, short-lived tokens.
Practical Deployment and Future Considerations
ForgeRock’s stack deploys flexibly—on-premise, cloud, hybrid. OpenDJ scales horizontally; OpenAM clusters for high availability.
Poitou stresses user-centric policies: dynamic authorizations based on context (location, device).
Emerging: UMA for resource owner control. Standards mature via IETF, OpenID Foundation.
Enterprises must adapt architectures for agility, ensuring compliance amid fluidity.
Links:
[DevoxxFR2013] Java EE 7 in Detail
Lecturer
David Delabassee is a Principal Product Manager in Oracle’s GlassFish team. Previously at Sun for a decade, he focused on end-to-end Java, related technologies, and tools. Based in Belgium, he contributes to Devoxx Belgium’s steering committee.
Abstract
David Delabassee’s overview details Java EE 7’s innovations, emphasizing developer simplicity and HTML5 support. Covering WebSockets, JSON-P, JAX-RS 2, JMS 2, concurrency, caching, and batch processing, he demonstrates features via GlassFish. The analysis explores alignments with modern needs like cloud and modularity, implications for productivity, and forward compatibility.
Evolution and Key Themes: Simplifying Development and Embracing Modern Web
Delabassee notes Java EE 6’s (2009) popularity, with widespread server adoption. Java EE 7, nearing finalization, builds on this via JCP, comprising 13 updated, 4 new specs.
Themes: ease of development (defaults, pruning), web enhancements (HTML5 via WebSockets), alignment with trends (cloud, multi-tenancy). Pruning removes outdated techs like EJB CMP; new APIs address gaps.
GlassFish 4, the reference implementation, enables early testing. Delabassee demos features, stressing community feedback.
Core API Enhancements: WebSockets, JSON, and REST Improvements
WebSocket (JSR 356): Enables full-duplex, bidirectional communication over single TCP. Annotate endpoints (@ServerEndpoint), handle messages (@OnMessage).
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void echo(String message, Session session) {
session.getBasicRemote().sendText(message);
}
}
JSON-P (JSR 353): Parsing/processing API with streaming, object models. Complements JAX-RS for RESTful services.
JAX-RS 2 (JSR 339): Client API, filters/interceptors, async support. Client example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://example.com");
Response response = target.request().get();
These foster efficient, modern web apps.
Messaging and Concurrency: JMS 2 and Utilities for EE
JMS 2 simplifies: annotation-based injection (@JMSConnectionFactory), simplified API for sending/receiving.
@Inject
JMSContext context;
@Resource(lookup="myQueue")
Queue queue;
context.send(queue, "message");
Concurrency Utilities (JSR 236): Managed executors, scheduled tasks in EE context. Propagate context to threads, avoiding direct Thread creation.
Batch Applications (JSR 352): Framework for chunk/step processing, job management. XML-defined jobs with readers, processors, writers.
Additional Features and Future Outlook: Caching, CDI, and Java EE 8
Though JCache (JSR 107) deferred, it enables standardized distributed caching, usable on EE 7.
CDI 1.1 enhances: @Vetoed for exclusions, alternatives activation.
Java EE 8 plans: modularity, cloud (PaaS/SaaS), further HTML5. Community shapes via surveys.
Delabassee urges Adopt-a-JSR participation for influence.
Implications for Enterprise Development: Productivity and Adaptability
Java EE 7 boosts productivity via simplifications, aligns with web/cloud via new APIs. Demos show practical integration, like WebSocket chats or batch jobs.
Challenges: Learning curve for new features; benefits outweigh via robust, scalable apps.
Forward, EE 7 paves for EE 8’s evolutions, ensuring Java’s enterprise relevance.
Links:
[DevoxxFR2013] JCP & Adopt a JSR Workshop
Lecturer
Patrick Curran chairs the Java Community Process (JCP), overseeing membership, processes, and Executive Committee. With over 20 years in software, including 15 at Sun, he led Java Conformance Engineering and chaired related councils. Active in W3C and OASIS.
Arun Gupta directs Developer Advocacy at Red Hat, focusing on JBoss Middleware. A Java EE founding member at Sun, he drove global adoption; at Oracle, he launched Java EE 7.
Mike Seghers, an IT consultant since 2001, specializes in Java enterprise web apps using frameworks like Spring, JSF. Experienced in RIA and iOS, he engages developer communities.
Abstract
Patrick Curran, Arun Gupta, and Mike Seghers’s workshop guides joining the Java Community Process (JCP) and participating in Adopt-a-JSR. They explain membership, transparency, and tools for JUG involvement like hackathons. Focusing on Java EE 8, the session analyzes collaboration benefits, demonstrating practical contributions for standard evolution.
Understanding JCP: Membership and Participation Pathways
Curran outlines JCP membership: free for individuals via jcp.org, requiring agreements; paid for corporations/non-profits ($2,000-$5,000). Java User Groups join as associates, nominating representatives.
Adopt-a-JSR encourages JUGs to engage JSRs: review specs, test implementations, provide feedback. This democratizes development, ensuring community input.
Gupta details Java EE 8 focus: HTML5, cloud, modularity. Adopt-a-JSR aids via mailing lists, issue trackers, wikis.
Practical Engagement: Tools and Initiatives for Collaboration
Tools include mailing lists for discussions, JIRA for bugs, GitHub for code. JUGs organize hack days, building samples.
Seghers demos Belgian JUG’s app: uses JSF, EJB, JPA for urban travelers game. Source on GitHub, integrates WebSockets.
This hands-on approach educates, uncovers issues early.
Case Studies: Global Adopt-a-JSR Impact
Examples: London JUG’s multiple JSR contributions; SouJava’s CDI focus; Morocco JUG’s hackathons. Chennai JUG built apps; Egypt JUG presented at conferences.
These illustrate visibility, skill-building, influence on standards.
Broader Implications: Enhancing Transparency and Community
JCP 2.8 mandates open Expert Groups, encouraging participation. Adopt-a-JSR amplifies this, benefiting platforms via diverse input.
Curran urges minimal commitments: feedback, testing. Gupta highlights launch opportunities.
Workshop fosters collaborative ecosystem, strengthening Java’s future.
Links:
[DevoxxFR2013] Live Coding: A WOA Application in 50 Minutes
Lecturer
Guillaume Bort co-founded Zenexity, specializing in Web Oriented Architecture. Previously a J2EE expert, he developed web frameworks for large enterprises, creating Play Framework to prioritize simplicity. He leads Play’s development.
Sadek Drobi, Zenexity’s CTO, focuses on enterprise applications, bridging problem and solution domains. As a programming languages expert, he contributes to Play Framework’s core team.
Abstract
Guillaume Bort and Sadek Drobi’s live coding demonstrates building a Web Oriented Architecture (WOA) application using Play Framework and Scala. Consuming Twitter’s API, they handle JSON, integrate MongoDB, and stream real-time data via Server-Sent Events to an HTML5 interface. The session analyzes reactive programming, asynchronous handling, and scalability, showcasing Play’s efficiency for modern web apps.
Setting Up the Foundation: Play Framework and Twitter API Integration
Bort and Drobi initiate with Play Framework, creating a project via activator. They configure routes for homepage and stream endpoints, using Scala’s async for non-blocking I/O.
Consuming Twitter’s search API: construct URLs with keywords like “DevoxxFR”, include entities for images. Use WS (WebService) for HTTP requests, parsing JSON responses.
They extract tweet data: user, text, images. Handle pagination with since_id for subsequent queries, building a stream of results.
This setup leverages Play’s stateless design, ideal for scalability.
Building Reactive Streams: Enumerators and Asynchronous Processing
To create a continuous stream, they employ Enumerators and Iteratees. Poll Twitter periodically (e.g., every 5 seconds), yielding new tweets.
Code uses concurrent scheduling:
val tweets: Enumerator[Tweet] = Enumerator.generateM {
Future {
// Fetch and parse tweets
Some(newTweets)
}
}
Flatten to a single stream. Handle errors with recover, ensuring resilience.
This reactive approach processes data as it arrives, avoiding blocking and enabling real-time updates.
Persisting Data: Integrating MongoDB with ReactiveMongo
For storage, integrate ReactiveMongo: asynchronous, non-blocking driver. Define Tweet case class, insert via JSONCollection.
val collection = db.collection[JSONCollection]("tweets")
collection.insert(tweetJson)
Query for latest since_id. Use find with sort/take for efficient retrieval.
This maintains asynchrony, aligning with WOA’s distributed nature.
Streaming to Clients: Server-Sent Events and HTML5 Interface
Output as EventSource: chunked response with JSON events.
Ok.chunked(tweets &> EventSource()).as("text/event-stream")
Client-side: JavaScript EventSource listens, appending images with animations.
Handle dynamics: form submission triggers stream, updating UI.
This enables push updates, enhancing interactivity without WebSockets.
Optimizing for Scalability: Backpressure and Error Handling
Address overload: use onBackpressureBuffer to queue, drop, or fail. Custom strategies compress or ignore excess.
Play’s Akka integration aids actor-based concurrency.
Implications: Builds resilient, scalable apps handling high loads gracefully.
Collaborative Development: Live Insights and Community Resources
Session highlights rapid prototyping: zero slides, GitHub commits for following.
Drobi comments on concepts like futures unification in Scala 2.10, inter-library interoperability.
They encourage exploring Play docs, plugins for extensions.
This methodology fosters understanding of reactive paradigms, preparing for distributed systems.
Links:
[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:
[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:
[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:
[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:
[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.