This document discusses patterns and best practices for dependency injection using the Contexts and Dependency Injection (CDI) specification. It provides an overview of CDI concepts like scopes, qualifiers, producers, events, decorators, and alternatives. It also discusses how CDI is implemented in WebSphere Application Server, including bean failover support.
Slides of the university I gave at Devoxx Belgium with Antonio Goncalves on CDI, Java EE and JBoss Forge.
Abstract:
-------
During this 3 hours university, you will learn some CDI basis, and will quickly dive into more advance CDI features (such as extension). Using JBoss Forge we will quickly generate a Java EE 7 web application, and then, following business requirements, we will add CDI functionalities.
This university talk will be a mixture of code and slides, focusing on CDI and Java EE 7.
--------
Video of the university is available on YouTube: http://youtu.be/LYKMaj4XKvg
Code and Slides on GitHub: https://github.com/antoinesd/cdi-forge-uni/tree/DevoxxBe2015
This session compares the Spring and Java EE stacks in terms of Web frameworks. It re-examines the motivations behind the Spring framework and explores the emergence of the Java EE programming model to meet the challenges posed. The presentation provides insight into when Spring and/or Java EE is appropriate for a building Web applications and if they can coexist.
Slides of the university I gave at Devoxx Belgium with Antonio Goncalves on CDI, Java EE and JBoss Forge.
Abstract:
-------
During this 3 hours university, you will learn some CDI basis, and will quickly dive into more advance CDI features (such as extension). Using JBoss Forge we will quickly generate a Java EE 7 web application, and then, following business requirements, we will add CDI functionalities.
This university talk will be a mixture of code and slides, focusing on CDI and Java EE 7.
--------
Video of the university is available on YouTube: http://youtu.be/LYKMaj4XKvg
Code and Slides on GitHub: https://github.com/antoinesd/cdi-forge-uni/tree/DevoxxBe2015
This session compares the Spring and Java EE stacks in terms of Web frameworks. It re-examines the motivations behind the Spring framework and explores the emergence of the Java EE programming model to meet the challenges posed. The presentation provides insight into when Spring and/or Java EE is appropriate for a building Web applications and if they can coexist.
This presentation shows what are JSON Web Tokens, explaining about the structure, signature, encryption and how we can integrate this with Authentication/Authorization together with Spring Security.
The link for the project in Github is:
https://github.com/BHRother/spring-boot-security-jwt
The example implements JWT + Spring Security in a Spring-Boot project.
How I learned to stop worrying and love UX metricsTammy Everts
This talk at the 2018 performance.now() conference (Amsterdam) walks through a brief history of UX and web performance research, highlighting landmark studies that helped connect the dots between performance and user experience. I also demystify the current state of performance metrics and help you understand what you need to focus on for your site and your users.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
"Json Web Token with digital signature. Modern authentication or authorization. Cookies are bad. Avoid Man-in-the-middle-attack. No need to protect against CSRF. Stateless.
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Edureka!
(**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****)
This Edureka tutorial on “Java Threads” will talk about one of the core concepts of Java i.e Java Threads. It will give you a complete insight into how to create, work and synchronize with multiple threads. Through this tutorial you will learn the following topics:
What is a Java Thread?
Thread Lifecycle
Creating a Thread
Main Thread
Multi-Threading
Thread Pool
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
What is JWT?
When should you use JSON Web Tokens?
WHAT IS THE JSON WEB TOKEN STRUCTURE?
JWT Process
PROS AND CONS
JWT.IO
Using JSON Web Tokens as API Keys
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
IBM WebSphere Application Foundation Sessions at IBM InterConnect 2015ibmwebspheresoftware
An overview of all of the key sessions at IBM InterConnect 2015 for the WebSphere Application Foundation portfolio, including:
- WebSphere Application Server including Liberty profile
- Extreme Scale
- PureSystems (WAS related)
- Bluemix (runtimes related)
- WebSphere Application Server Developer Tools
To build your InterConnect agenda online or import sessions into your calendar, visit: ibm.co/interconnectagendabuilder
To register for IBM InterConnect, visit: http://ibm.co/interconnect
This presentation shows what are JSON Web Tokens, explaining about the structure, signature, encryption and how we can integrate this with Authentication/Authorization together with Spring Security.
The link for the project in Github is:
https://github.com/BHRother/spring-boot-security-jwt
The example implements JWT + Spring Security in a Spring-Boot project.
How I learned to stop worrying and love UX metricsTammy Everts
This talk at the 2018 performance.now() conference (Amsterdam) walks through a brief history of UX and web performance research, highlighting landmark studies that helped connect the dots between performance and user experience. I also demystify the current state of performance metrics and help you understand what you need to focus on for your site and your users.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
"Json Web Token with digital signature. Modern authentication or authorization. Cookies are bad. Avoid Man-in-the-middle-attack. No need to protect against CSRF. Stateless.
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Edureka!
(**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****)
This Edureka tutorial on “Java Threads” will talk about one of the core concepts of Java i.e Java Threads. It will give you a complete insight into how to create, work and synchronize with multiple threads. Through this tutorial you will learn the following topics:
What is a Java Thread?
Thread Lifecycle
Creating a Thread
Main Thread
Multi-Threading
Thread Pool
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
What is JWT?
When should you use JSON Web Tokens?
WHAT IS THE JSON WEB TOKEN STRUCTURE?
JWT Process
PROS AND CONS
JWT.IO
Using JSON Web Tokens as API Keys
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
IBM WebSphere Application Foundation Sessions at IBM InterConnect 2015ibmwebspheresoftware
An overview of all of the key sessions at IBM InterConnect 2015 for the WebSphere Application Foundation portfolio, including:
- WebSphere Application Server including Liberty profile
- Extreme Scale
- PureSystems (WAS related)
- Bluemix (runtimes related)
- WebSphere Application Server Developer Tools
To build your InterConnect agenda online or import sessions into your calendar, visit: ibm.co/interconnectagendabuilder
To register for IBM InterConnect, visit: http://ibm.co/interconnect
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.PilgrimPayara
The talk presented by Peter Pilgrim at the London JavaEE & GlassFish User Group event on the 18th of February 2015.
find out more at: http://payara.co/february_london_glassfish_user_group_with_peter
Traditional virtualization technologies have been used by cloud infrastructure providers for many years in providing isolated environments for hosting applications. These technologies make use of full-blown operating system images for creating virtual machines (VMs). According to this architecture, each VM needs its own guest operating system to run application processes. More recently, with the introduction of the Docker project, the Linux Container (LXC) virtualization technology became popular and attracted the attention. Unlike VMs, containers do not need a dedicated guest operating system for providing OS-level isolation, rather they can provide the same level of isolation on top of a single operating system instance.
An enterprise application may need to run a server cluster to handle high request volumes. Running an entire server cluster on Docker containers, on a single Docker host could introduce the risk of single point of failure. Google started a project called Kubernetes to solve this problem. Kubernetes provides a cluster of Docker hosts for managing Docker containers in a clustered environment. It provides an API on top of Docker API for managing docker containers on multiple Docker hosts with many more features.
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...jaxLondonConference
Presented at JAX London 2013
The Java EE 7 platform focuses on Productivity and HTML5. JAX-RS 2 adds a new Client API to invoke the RESTful endpoints. JMS 2 is undergoing a complete overhaul to align with improvements in the Java language. The long awaited Batch Processing API and Concurrency API are also getting added to build applications using capabilities of the platform itself. Together these APIs will allow you to be more productive by simplifying enterprise development. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication.
Update:
Video available from Oredev: vimeo.com/53147485
Metaprogramming is the dirty little secret behind the success of many Java frameworks such as Spring and Struts2, and constitutes the backbone of many of the most fundamental APIs across the JEE technology stack. This session aims introduce the topic and highlight, with code examples, the different mechanisms and techniques to take advantage of this underused feature of the Java Programming Language.
This session will adopt a learn-by-example approach that combines the philosophy and theory behind metaprogramming with concrete code examples. The audience will be walked real-life scenarios to highlight the benefits of this technique such as minimizing the number of lines of code, reduced development time, and greater flexibility, etc… Design patterns, and best practices will be picked up along the way.
No previous knowledge or exposure to the topic is required, but an intermediate understanding of Java SE is expected.
Unleash the power of Context and Dependency Injection (CDI) in a JEE container. The slides go over the 2.0 specification and how each part of the specification can be applied. Code for this can be found on GitHub: https://github.com/bpaskin/JavaExamples/tree/master/CDI2.0Examples/src/com/ibm/example/cdi
Spring in the Cloud - using Spring with Cloud FoundryJoshua Long
This talk's about using the power of the Spring framework with Cloud Foundry, the open source PaaS (platform as-a-service) from VMware. This is a bit more deep an introduction than my other Spring and Cloud Foundry talk, and so I've kept both, while encouraging people to check this one out, first.
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
As the adoption of Contexts and Dependency Injection (CDI) for Java EE API grows, it is important to understand how to use CDI effectively to maximize the benefits of using a loosely coupled, type-safe, annotation-driven dependency injection solution. This session outlines the best practices for using CDI, such as annotations versus XML, @Named as a qualifier, qualifier type safety versus verbosity, effective use of producers/disposers, using scopes properly, best practices for using conversations, defining effective stereotypes, interceptors versus decorators, static versus dynamic injection/lookup, CDI versus Java EE resource injection, using CDI with EJB 3.1, CDI/JSF 2 integration patterns, and CDI/JPA 2 usage patterns.
Enterprise Java Beans (EJB) is a platform for building portable, reusable, and scalable business applications using the Java programming language.
EJB allows application developers to focus on building business logic without having to spend time on building infrastructure code for services such as transactions, security, automated persistence, and so on.
This presentation introduces EJB 3.0 concepts with code examples.
API First or Events First: Is it a Binary Choice? Rohit Kelapure
When do you use API-first or events-first architecture? Is this a binary choice? This is a false dichotomy! A mental model is needed to frame the architecture, packaging, and programming choices for modern applications.
Varying degrees of combination of events and APIs can be used to design a system. Event notifications-based systems require an API callback to the source. CQRS and event-sourcing patterns, on the other hand, are on the complex end of the event-driven spectrum. APIs also have a maturity model, evolving with the adoption of reactive paradigms.
In this session, we’ll look at heuristics such as cost, latency, security, and external integrations that will influence implementation. Architects will learn actionable fitness functions to strike a balance between APIs and events to build sustainable architectures.
Why does application Modernization in the form of decomposing monoliths result in so many microservices ? Why has microservices become the default deployment model for applications. In this talk we will add some sanity to the process of constructing microservices and provide guidelines and design heuristics on structuring microservices. We will look at life after running microservices architectures in production and learn from the mistakes committed over the past five years. We will analyze real life systems on the criteria for consolidating microservices into monoliths or moduliths based on technical and business heuristics as illustrated In [4]. The techniques - a combination of mapping microservices to core technical attributes [2] reduced by affinity mapping and business domain context distillation [3] - have emerged from working with a number of customers where the value of microservices has not been realized despite leveraging Domain Driven Design.
References:
1 https://hackmd.io/10j-7DfqSIu1C8GQjHa1Bw?view
2 https://content.pivotal.io/blog/should-that-be-a-microservice-keep-these-six-factors-in-mind
3 https://bit.ly/2VFwDr1
4 https://twitter.com/RKela/status/1227188151887843329/photo/1
How do we add some sanity to the process of constructing microservices and provide guidelines and design heuristics on restructuring microservices. In this talk we will look at life after running microservices architectures in production and learn from the mistakes committed over the past five years. We will analyze real life systems on the criteria for consolidating microservices into monoliths or moduliths based on technical and business heuristics as illustrated In [4]. The techniques - a combination of mapping microservices to core technical attributes [2] reduced by affinity mapping and business domain context distillation [3] - have emerged from working with a number of customers where the value of microservices has not been realized despite leveraging Domain Driven Design.
1. Essay on this topic : https://hackmd.io/10j-7DfqSIu1C8GQjHa1Bw?view
2. https://content.pivotal.io/blog/should-that-be-a-microservice-keep-these-six-factors-in-mind
3. https://medium.com/nick-tune-tech-strategy-blog/core-domain-patterns-941f89446af5
4. https://twitter.com/RKela/status/1227188151887843329/photo/1
Travelers 360 degree health assessment of microservices on the pivotal platformRohit Kelapure
Is your system healthy? Are SLOs being met? What are the top performance constraints? What are the high-priority implementation concerns? Is the architecture a right fit? Are the teams leveraging the capabilities of the platform? What are the pain points with platform services? It can be challenging to find root cause among problem symptoms in distributed systems. Just as in real life, it's important for microservices to undergo regular health checks.
In this talk, we'll provide a systems-based approach to execute an app health check along 10 different dimensions: monitoring and metrics, failure mode analysis, technical debt, emergency response, performance optimization, change management, microservices rationalization, platform as a product, balanced team, and path to production. We'll explain how to address issues uncovered during a health check and provide recommendations on how to build a sustainable Day 2 app-ops reliability engineering practice.
Migrate Heroku & OpenShift Applications to IBM BlueMixRohit Kelapure
This slide deck describes some of the architectural principles behind the Heroku, OpenShift, Cloud Foundry and BlueMix enterprise PaaS. The commonalities and differences in designing and porting apps across these platforms to Cloud Foundy/BlueMix are explored.
Liberty Buildpack: Designed for Extension - Integrating your services in Blue...Rohit Kelapure
The Liberty Buildpack aims to remove the hassle of running Java applications on Cloud Foundry whether it is the simplified setup, auto-configuration of Liberty and Java EE references to cloud resources, reduced droplet size through selective provisioning of the runtime, or the zero-touch configuration and usage of services. There are times, however, when an application needs a feature that the buildpack does not yet provide. This talk will start by showing how to use and configure the Java buildpack and finish by showing how to extend the buildpack to ensure that IBM BlueMix Cloud Foundry is the best place to run your application. To build services and integrate them with BlueMix, you must implement the Service Broker API of Cloud Foundry for your services. This talk will explain how to write plugins to the Liberty Buildpack that will auto wire services your organization developed and integrated into CF making it easier for your apps to use the services in Cloud Foundry.
A Deep Dive into the Liberty Buildpack on IBM BlueMix Rohit Kelapure
This talk goes into the details and mechanics of how the Liberty buildpack deploys an application into the IBM BlueMix Cloud Foundry. It also explores how the Cloud Foundry runtime drives the Liberty buildpack code and what the Liberty buildpack code in Cloud Foundry does to run an application in the cloud environment. This talk touches on the restrictions that Cloud Foundry and the Liberty runtime imposes on applications running in Cloud Foundry. Developers attending this talk get deep insight into the why, what, how, and when of the Liberty buildpack ruby code, enabling them to write applications faster and optimized for the Liberty runtime in IBM BlueMix.
The ICAP Integrated Development Environment (IDE) provides a number of standard development tools to ease the design of modern applications.
Mobile (Worklight)
Includes IBM's industry leading mobile development platform
Java (WebSphere Liberty Profile)
Rapidly build next-generation, engaging applications for the WebSphere Application Server Liberty Profile.
JavaScript (Node.js)
Easily build applications with the most popular JavaScript runtime for event-driven server side development .
Cloud Explorer
Quickly discover shared services to enhance applications. Develop custom services to share with others.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
The Art of the Pitch: WordPress Relationships and Sales
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
1. Patterns and Best Practices for
Contexts for Dependency Injection
Rohit Kelapure
WebSphere Application Server Caching Architect
Apache OpenWebBeans Committer
IBM
http://wasdynacache.blogspot.com/
Session ID = TDP-1167
1
2. Contributions from Mark Struberg, Gerhard Petracek,
Arne Limburg, Reza Rahman & Ryan Cuprak
http://www.slideshare.net/os890/
https://cwiki.apache.org/confluence/display/EXTCDI/External
http://people.apache.org/~struberg
http://www.openknowledge.de/?id=62#139
http://www.slideshare.net/os890/make-jsf-more-typesafe-with-
cdi-and-myfaces-codi
http://www.slideshare.net/os890/myfaces-codi-conversations
http://people.apache.org/~struberg/jax2012/cdi-
basics_jax2012.pdf
http://people.apache.org/~struberg/jax2011/JSR-
299_JAX_2011.pdf
http://www.rahmannet.net/downloads/cdi_best_practices.pdf
2 Session ID: TDP 1167
3. Agenda
Tour of CDI (Contextual Dependency Injection)
Common Pitfalls
New Programming Patterns
Best Practices
CDI Extension Programming
CDI Extensions
3 Session ID: TDP 1167
4. 4
Contextual Dependency Injection JSR299
Future of JEE
Loose Coupling
– Server & Client, Components, Concerns & Events
Design pattern Specific type of IoC
– Don’t call us, we will call you
– No hard coded dependencies
Inspirations SEAM, Spring, Guice
Dramatic reduction in LOC
Goes far beyond what was possible with Java EE5
Not only an API but also a SPI
Spec compliant way to modify the EE platform via CDI
extensions
4 Session ID: TDP 1167
5. 5
CDI Services
Contextual State and lifecycle mgmt.
Typesafe dependency injection
Interceptors and decorators
– extend behavior with typesafe interceptor bindings
SPI enables portable extensions
– integrates cleanly with Java EE
Adds the Web conversation context
– + to standard contexts (request, session, application)
Unified component model
– Integration with the Unified EL
• Enables use of EJB 3.0 components as JSF managed beans
Events decouple producers and consumers
5 Session ID: TDP 1167
6. 6
Relationship to other Java EE Specs
Contextual lifecycle mgmt. for EJBs
– Session bean instances obtained via DI are contextual
• Bound to a lifecycle context
• Available to others that execute in that context
• Container creates instance when needed
• Container Destroys instance when context ends
Contextual lifecycle mgmt. for Managed Beans
Associate Interceptors with beans using typesafe interceptor
bindings
Enhances JSF with a sophisticated context & DI model
– Allows any bean to be assigned an unique EL name
6 Session ID: TDP 1167
7. 7
What is a CDI Managed Bean
Concrete POJO (exception for @Decorator)
– Must have a no-argument constructor or constructor annotated @Inject
– Cannot be a static inner class
– Opt in with a beans.xml
Objects returned by producers
Additional types defined by CDI SPI
Defined to be a managed bean by its EE specification
– EJB session beans (local or remote)
– Message Driven Beans
– JEE Resources (DataSources, JMS Destinations)
– Persistent Unit, Persistent Contexts
– Web Service References
– Servlets, Filters, JSF Managed Beans, Tag Libraries …
Built-in Beans
– JTA User Transaction
– Security Principal representing caller identity
– Bean Validator & Validation Factory
7 Session ID: TDP 1167
8. 8
CDI Packaging
Bean classes packaged in a Bean Deployment Archive
To activate CDI create a beans.xml file (can be empty)
– META-INF
– WEB-INF/classes
Container searches for beans in all bean archives in
application classpath
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd
8 Session ID: TDP 1167
* Picture source Norman Richards
9. 9
Types of CDI Injection
Field Injection
Parameter Injection
– Observer, producer & disposer methods
– Initializer methods
@ConversationScoped
public class Order {
@Inject @Selected Product product; //Field injection
@Inject //Initializer method
void setProduct(@Selected Product product) {
this.product = product;
}
}
9 Session ID: TDP 1167
10. 10
Bean Definition
Bean Type
Qualifier
Scope
EL Name
Interceptors
Implementation
10 Session ID: TDP 1167
11. 11
Bean Types
public class BookShop
extends Business implements Shop<Book>{
...
}
Client visible Bean types
– BookShop, Business, Shop<Book>, Object
@Stateful
public class BookShopBean extends Business
implements BookShop, Auditable {
...
}
Bean types
– BookShop, Auditable , Object
Can be restricted using the @Typed annotation
– @Typed(Shop.class) public class BookShop
11 Session ID: TDP 1167
12. 12
Qualifiers
Distinguish between beans of the same Type
@ASynchronous
class AsynchronousPaymentProcessor
implements PaymentProcessor {
...
}
@Synchronous
class SynchronousPaymentProcessor
implements PaymentProcessor {
...
}
//Qualifier type
@Qualifier
@Target({TYPE, METHOD, PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface Synchronous{}
Specifying qualifiers on an injected bean aka Client
@Inject @Synchronous PaymentProcessor
12 Session ID: TDP 1167
13. 13
Qualifiers Cont…
Bean can define multiple qualifier types
– Injection Point only needs enough qualifiers to uniquely identify a bean
Every bean
– Built-in qualifier @Any
– Default qualifier @Default when one is not explicitly declared
Producer methods and fields can also use qualifiers
@Produces @Asynchronous
public PaymentProcessor createAsynchronousProcessor() {
return new AsynchronousPaymentProcessor();
}
Qualifiers with members
@Target({FIELD, PARAMETER}) @Retention(RUNTIME)
@Qualifier
public @interface Currency {
public String code();
}
// client
@Inject @Currency(code=“USD”) PaymentProcessor processor;
13 Session ID: TDP 1167
14. 14
Scope: Lifecycle & Visibility of Instances
Scoped Objects exist a lifecycle context
– Each bean aka contextual instance is a singleton in that context
– Contextual instance of the bean shared by all objects that execute
in the same context
// Session scoped bean shared by all requests
// that execute in the context of that session
public @SessionScoped class ShoppingCart implements Serializable {
...
}
@Produces @RequestScoped @Named("orders")
List<Order> getOrderSearchResults() { ... }
@ConversationScoped public class Order { ... }
@Produces @SessionScoped User getCurrentUser() { ... }
14 Session ID: TDP 1167
15. 15
Scope: Lifecycle & Visibility of Instances
Normal Scopes
– @RequestScoped DTO/Models, JSF Backing beans
– @ConversationScoped Multi-step workflow, Shopping Cart
– @SessionScoped User login credentials
– @ApplicationScoped Data shared by entire app, Cache
Pseudo scope
– @Dependent (default scope) makes sense for majority
• Bound to the lifecycle of the object they were injected
Qualifier
– @New (new instance will be created)
• Not bound to the declared scope
• Has had DI performed
Custom scopes provided by Extensions
– OpenWebBeans provides @ViewScoped through the Jsf2ScopesExtension
15 Session ID: TDP 1167
16. 16
EL Name: Lookup beans in Unified EL
Binding components to JSF Views
Specified using the @Named annotation
public @SessionScoped @Named("cart“) class ShoppingCart implements
Serializable {
...
}
Now we can easily use the bean in any JSF or JSP page
<h:dataTable value="#{cart.lineItems}" var="item">
...
</h:dataTable>
Container derives default name in absence of @Named
– Unqualified short class name of the bean class
@Named is a built-in Qualifier
16 Session ID: TDP 1167
17. 17
Interceptors
Separate cross-cutting concerns from business logic
Associate Interceptors to beans using Interceptor Bindings
@Inherited
@InterceptorBinding //Interceptor Binding Type definition
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Transactional {}
//Declaring Interceptor Bindings of an Interceptor
@Transactional @javax.interceptor.Interceptor
public class TransactionInterceptor {
@AroundInvoke
public Object manageTransaction(InvocationContext ctx)
throws Exception { ... }
}
//Binding Interceptor to Bean
@Transactional public class ShoppingCart { ... }
public class ShoppingCart {
@Transactional
public void placeOrder() { ... }
}
17 Session ID: TDP 1167
18. 18
Interceptors
Enabled manually in the beans.xml
Order defined in beans.xml
@Dependent object of the object it intercepts
<beans>
<interceptors>
<class>org.mycompany.TransactionInterceptor</class>
<class>org.mycompany.LoggingInterceptor</class>
</interceptors>
</beans>
18 Session ID: TDP 1167
19. 19
Implementation Design Patterns
Bean Implementation provided by
– Developer … Java class
– Container … Java EE env. Resource beans
Contextual Singleton
All Normal scoped beans are proxied
– Contextual Reference implies a proxy for a contextual instance
Dynamic Proxies
– Passivation of contextual instances
– Scope Management
• Narrower scope injected into a wider scope
Chaining of Dynamic Proxies
– Interceptor and Decorator chaining
19 Session ID: TDP 1167
20. 20
Alternatives
Deploy time selection of bean implementation
Alternate implementation of bean
– Explicitly enabled in the beans.xml
– Overrides the original bean
@Alternative // annotate bean class, producer method or field
@Specializes
public class MockOrder extends Order {
... // alternative implementation
}
<beans>
<alternatives>
<class>org.example.MockOrder</class>
</alternatives>
</beans>
@Specializes
– Alternate inherits the metadata (name, qualifiers ) etc of the parent
20 Session ID: TDP 1167
21. 21
Stereotypes
Stereotype bundles @Target(TYPE)
@Retention(RUNTIME)
– Scope
public @interface Action {}
– Interceptor Bindings
– @Named
– @Alternative Built-in Stereotypes
– @Model
Bean annotated with a
stereotype inherits all – @Decorator
annotations of the stereotype – @Interceptor
@RequestScoped @Alternative applied to a
@Secure stereotype
@Transactional – ALL beans with that stereotype
are enabled/disabled as a group
@Named
@Stereotype
21 Session ID: TDP 1167
22. 22
Producers
Application control of bean instance creation & destruction
Producer Fields
public class Shop {
@Produces @ApplicationScoped @Catalog @Named("catalog")
List<Product> products = ....;
}
Producer Methods
public class Shop {
@Produces @ApplicationScoped @Catalog @Named("catalog")
List<Product> getProducts(CatalogID cID) { ... }
}
Disposer Methods
– Customized cleanup of object returned by a producer method
public class Shop {
public void close(@Disposes @Catalog List<Product> products) {
products.clear();
}
}
22 Session ID: TDP 1167
23. 23
Injecting Java EE Resources
When injecting EJBs
– Use @Inject to get Contextual Injection
– Use @EJB ONLY for remote session beans
Define producers making EE types available for injection… non
contextual injection
@Produces @WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;
@Produces @PersistenceContext(unitName="CustomerDatabase")
@CustomerDatabase EntityManager customerDatabasePersistenceContext;
Consume the Injected types in other CDI Beans
@Inject @CustomerDatabase EntityManager myEntityManager
@Inject PaymentService myPaymentService
23 Session ID: TDP 1167
24. 24
Decorators
Implements one or more bean types
– Can be abstract
– Implements the interface it is decorating
Extend bean types with function specific to that type
Called after interceptors
Explicitly enabled in the beans.xml
public interface Htmlable { String toHtml(); } //interface
public class HtmlDate extends Date implements Htmlable {
public String toHtml() { //date class that knows its HTML representation
return toString();
}
}
@Decorator public class StrongDecorator implements Htmlable {
@Inject @Delegate @Any private Htmlable html;
public String toHtml() { //decorator that puts the HTML inside <strong>
tags
return "<strong>" + html.toHtml() + "</strong>";
}
}
24 Session ID: TDP 1167
25. 25
Events: Observer Pattern
public class MyEvent { String data; Date eventTime; .... } // Event is a POJO
// Event<MyEvent> is injected automatically by the container
@Stateless @Named (“producer”)
public class EventProducer {
@Inject @My Event<MyEvent> event; //@My is a Qualifier
public void doSomething() {
event.fire(new MyEvent());
}
}
// Declare method that takes a parameter with @Observes annotation
@Stateless // Transactional, Conditional observer
public class EventConsumer {
public void afterMyEvent(
@Observes(during=AFTER_SUCCESS receive=IF_EXISTS) @My MyEvent event) {
// .. Do something with MyEvent
}
}
<h:form> // Fire the event from a JSF 2.0 Page
<h:commandButton value="Fire!" action="#{producer.doSomething}"/>
</h:form>
25 Session ID: TDP 1167
26. 26
CDI Implementation in WAS
WAS CDI implementation is based on Apache OpenWebBeans
– OpenWebBeans release 1.0.0 + fixes
Changes & additions on top of OpenWebBeans to support
integration with the server run time
– Integration with other Java EE containers like JSF, Servlet & EJB
container that support injectable components.
– Proprietary ScannerService implementation
– Direct use of EJB metadata for determining EJB types.
– Automatic registration of Servlet Listeners, Filters, Interceptors for
CDI applications
– WebSphere Application Server-specific implementations of many
OpenWebBeans Service Programming Interfaces (SPI)
• ResourceInjectionService, TransactionService, failover service…
26 Session ID: TDP 1167
27. 27
CDI Bean Failover in WAS
WAS supports failover (activation & passivation) of CDI beans &
enterprise beans, along with their interceptors and decorators
EJB failover support with CDI ONLY works for Stateful Session
Beans and requires the same configuration as Stateful Session
Bean failover
Configure EJB failover with web HTTP session failover
Except for abstract decorators, failover services are based on
current WAS failover providers
Both Web session failover and EJB SFSB failover need to
configured
27 Session ID: TDP 1167
28. Pitfalls
CDI Exception How to Fix
AmbiguousResolutionException Add qualifiers or alternatives to @Inject to
More than one bean eligible for injection. narrow bean resolution. Disable alternatives.
Annotate class with @Typed
UnproxyableResolutionException Ensure that bean types are legal. Check if class
bean type cannot be proxied by the container is declared final, has final methods or private
CTOR with no parameters
UnsatisfiedResolutionException Remove qualifiers from injection point or add
No bean eligible for injection qualifiers to existing types. Enable alternatives
BusyConversationException Before starting a conversation check if one
Rejected request b/c concurrent request is already exists using Conversation.isTransient()
associated with the same conversation context.
NonexistentConversationException Check if conversation is being propagated with
Conversation context could not be restored the cid GET request parameter
ContextNotActiveException Ensure that methods on the injected bean are
Bean invocation in inactive context called in a context that is active as defined by
the scope of the bean.
ObserverException Fix observer method code that throws the
Exception is thrown while handling event exception.
28 Session ID: TDP 1167
29. Program pattern - @Typed
Defines the Java Type which should be used for that bean
Possible to 'disable' a bean with @Typed() to prevent
AmbiguousResolutionExceptions
@Typed() // basically disables this Bean
public class MenuItem implements Serializable {
@ApplicationScoped
public class TrackReadOnlyService {
public Track readTrack(int id) {..}
}
@Typed(TrackReadWriteService.class)
@ApplicationScoped
public class TrackReadWriteService extends TrackReadOnlyService {
public void writeTrack(Track t) {..}
}
Handy for subclasses which should NOT conflict with their
parent class types
29 Session ID: TDP 1167
30. Program pattern - Cache Cleaning via Events
If user changes the language or logs in, then we need to change
the menu
@SessionScoped
public class Menu {
private @Inject MenutItem parentMenu;
protected reloadMenu(@Observes UserSettingsChangedEvent
uscE) {
parentMenu = menuSvc.loadMenu();
}
}
30 Session ID: TDP 1167
31. Program Pattern – Type safe configuration
Configuration without properties or XML files
Just create an Interface or default config class
– public interface MyConfig{
– String getJdbcUrl();
– }
Later just implement @Specializes, @Alternative,
@ProjectStageActivated, @ExpressionActivated for your
configuration implementation
31 Session ID: TDP 1167
33. Best Practice- Scopes
Scopes – Components with
appropriate scopes maximize
memory usage.
Scopes remove boilerplate
state maintenance code –
especially at presentation tier.
Make judicious use of
conversations
Leverage appropriate
conversation scope from
MyFaces CODI
33 Session ID: TDP 1167
34. Best Practice - Qualifiers with enums
@Qualifier
@Qualifier
@Retention(RUNTIME)
@Retention(RUNTIME)
@Target({ FIELD, TYPE })
@Target({ FIELD, TYPE })
public @interface MailSenderType {
public @interface Admin {}
MailSenderTypes value();
}
@Qualifier
public enum MailSenderTypes {
@Retention(RUNTIME)
ADMIN, SUPPORT
@Target({ FIELD, TYPE })
}
public @interface Support {}
@Inject
@MailSenderType(MailSenderTypes.SU
@Inject @Support PPORT) private MailSender
private MailSender mailSender; mailSender;
34 Session ID: TDP 1167
35. Best Practice – Interceptors, Decorators, Naming
Interceptors are designed for system-level crosscutting
concerns very decoupled from business logic.
Decorators intended for concerns that should be
compartmentalized but are still very close to business logic.
Naming Only necessary to name components that are
referenced outside of Java such as in JSF/Facelets via EL.
Naming Default names are good enough.
Naming Be careful of naming conflicts – name-based resolution
not type-safe!
Naming Choose names that add to readability/API fluency
Stereotypes Encapsulate specialized behavior & component
groups of recurring metadata
35 Session ID: TDP 1167
36. Best Practice - Injection
Declarative, static injection sufficient for most cases
@Produces & @Disposes used when objects must be
programmatically created/destroyed
Look-up using Instance used when dependencies need to be
resolved at runtime
For dynamic resolution BeanManager.getBeans SPI can be
used
Java EE 5 introduced limited, specialized, name-based resource
injection via annotations - @Resource, @EJB,
@PersistenceContext
CDI provides powerful, general purpose, type-safe injection
Favor CDI for greater flexibility
36 Session ID: TDP 1167
37. Best Practice - Integration CDI & EJB
Use EJB for enterprise services – like transactions, security
Use CDI managed beans otherwise – EJB does have overhead
Avoid plain managed beans
EJBs most appropriate for service/business logic tier
CDI makes it possible to use EJBs as JSF managed beans –
only good practice for RAD/prototyping
Using EJB services without EJB
Interfaces are optional
37 Session ID: TDP 1167
38. Best Practice- How to deal with Interfaces
Interfaces are evil
In Java EE 6 interfaces are absolutely optional
– Inject classes directly
Eliminate interfaces
– Considerably reduce the number of files
– Code becomes easier to understand & maintain
Not needed for decoupling purposes
– EJB 3.1 / CDI bean be directly exposed over SOAP or REST
Should be used ONLY for
– Strategy Pattern
– Layering
– APIs (not very common)
38 Session ID: TDP 1167
39. Best Practice - Integration CDI & JSF
CDI more powerful replacement to JSF managed beans
Seam Faces and CODI MyFaces excellent enhancements
CDI naming, scopes, producers, qualifiers work in powerful
ways with JSF
CDI designed with JSF in mind, but not limited to JSF
Wicket, Struts 2, Spring MVC have CDI extensions for
integration.
Replace all JSF managed beans and scopes with corresponding
CDI scopes
39 Session ID: TDP 1167
40. Best Practice - Integration CDI & JPA
CDI/JPA bean life-cycle mismatch
Life-cycle mismatch bridged by CDI producers
Make judicious use of stateful session bean extended persistence context
Use the entitymanager-per-request design pattern by producing your EntityManager
@RequestScoped
public class EntityManagerProducer {
private @PersistenceContext(unitName="Course") EntityManager entityManager;
@Produces @RequestScoped @QCourse
public EntityManager createEntityManager() {
return entityManager;
}
public void dispose(@Disposes @QCourse EntityManager entityManager) {
entityManager.close();
}
}
public class MyUserService {
private @Inject @QCourse EntityManager em;
public User getUser(long id) {
return em.find(id, User.class);
}
40 Session ID: TDP 1167
41. Best Practice - Integration CDI & JMS
Message Producer &
JMS Abstraction
41 Session ID: TDP 1167
42. Best Practice - CDI as replacement for JMS
CDI provides simple lightweight local transactional publish-
subscribe communication
Main goal of JMS 2.0 will be simplicity & tight integration with
CDI
JMS pub-sub implementation is more powerful, flexible;
however requires more code
CDI events are delivered synchronously
Events can be asynchronously consumed with an EJB 3.1 bean.
@Stateless
public class MessageListener {
@Asynchronous
public void onImportantMessage(
@Observes @Importance(Importance.Degree.HIGH)
String message){
System.out.println("+Important " + message);
}
42 Session ID: TDP 1167
}
43. 43
CDI Extensions
Portable
– Activated by dropping jars on the application classpath
– Loaded by the java.util.ServiceLoader
– Tools/utilities, extending Java EE, integration with Java EE APIs & integrating with non-
standard APIs, environments
Service provider of the service javax.enterprise.inject.spi.Extension declared in META-
INF/services
Code to javax.enterprise.inject.spi .* interfaces
Integrate with container through container lifecycle events by
– Providing its own beans, interceptors and decorators
– Injecting dependencies into its own objects
– Providing a context implementation for a custom scope
– Augmenting or overriding the annotation-based metadata with other source
43 Session ID: TDP 1167
44. CDI Extension code sample
My Faces CODI ProjectStageActivated
Before Process Process After
Process After Bean
Bean Annotated Injection Deployment
Beans Discovery
Discovery Type Targets Validation
• Add scope • Veto bean • Replace • Prepare • Add bean • Assessment
• Add annotated candidate Injection target additional • Add context
type • Replace beans • Add observer
• Add annotated type method
interceptor
binding
• Add
stereotype
44 Session ID: TDP 1167
47. Future of CDI Extensions – Apache DeltaSpike
Users have to look at several CDI extensions like JBoss, Seam
3 and Apache MyFaces CODI as well as smaller projects & blog
entries
No out of- the-box optimization across different extension-
projects
To combine them sometimes requires a detailed knowledge
about the projects.
Goal: Add and/or merge most features in/into DeltaSpike
First releases - the community started to merge features of
Apache My-Faces CODI-Core and JBoss Solder which is a
central part of Seam3
47 Session ID: TDP 1167
48. 48
CDI 1.1 & Future
Globally enabled Interceptors and Alternatives
XML configuration
@Disposes for producer fields
Clarifies some AnnotatedType behavior
@Veto + optional beans
Relax Serialization rules
@EarApplicationScoped vs @WebApplicationScoped
https://issues.jboss.org/browse/CDI
Closer integration between other EE specs like EJB and CDI beans
Transactions, Security, Concurrency etc delivered as Interceptors that can be
applied to any CDI bean
Popular CDI portable extensions rolled into DeltaSpike and future specifications
48 Session ID: TDP 1167
Editor's Notes
CDI brings Dependency Injection to a new level. Within the first two years of its existence, CDI quickly rose from anunknown little JSR to now being unanimously considered the star of Java EE 6.
Bean Type The bean type is the set of Java types that the bean provides. CDI injection always uses type as the primary identifier for determining the bean that will provide an instance. Unless otherwise restricted, a bean’s type includes all the superclasses and interfaces in the Java type hierarchy.
Sometimes, a bean type alone does not provide enough information for the container to know whichbean to inject. For instance, suppose we have two implementations of the PaymentProcessorinterface: CreditCardPaymentProcessor and DebitPaymentProcessor. Injecting a field of typePaymentProcessor introduces an ambiguous condition. In these cases, the client must specify some additionalquality of the implementation it is interested in. We model this kind of "quality" using a qualifier.A qualifier is a user-defined annotation that is itself annotated @Qualifer. A qualifier annotation is an extension ofthe type system. It lets us disambiguate a type without having to fall back to string-based names. Here's an exampleof a qualifier annotation:Qualifiers allow extra type information to be supplied whilekeeping the reference type generic● A Qualifier provides guidance to CDI about which bean classshould be used. ● An injection point can use multiple qualifiers. All qualifiersmust be present on the bean.@Qualifier@Target({TYPE, METHOD, PARAMETER, FIELD})@Retention(RUNTIME)public @interface CreditCard {}There may be multiple beans that implement a desired Java type. It is possible to distinguish between multiple types using qualifier annotations. Qualifiers are developer-defined and provide a type-safe way to distinguish between multiple beans implementations. qualifier type represents some client-visible semantic associated with a type that is satisfied by some implementations ofthe type (and not by others). For example, we could introduce qualifier types representing synchronicity and asynchronicity.In Java code, qualifier types are represented by annotations.
Java EE components such as servlets, EJBs and JavaBeans do not have a well-defined scope. These components are either:• singletons, such as EJB singleton beans, whose state is shared between all clients,• stateless objects, such as servlets and stateless session beans, which do not contain client-visible state, or• objects that must be explicitly created and destroyed by their client, such as JavaBeans and stateful session beans,whose state is shared by explicit reference passing between clients.Scoped objects, by contrast, exist in a well-defined lifecycle context:• they may be automatically created when needed and then automatically destroyed when the context in which they werecreated ends, and• their state is automatically shared by clients that execute in the same context.All beans have a scope. The scope of a bean determines the lifecycle of its instances, and which instances of the bean arevisible to instances of other beans, as defined in Chapter 6, Scopes and contexts. A scope type is represented by an annotationtype.For example, an object that represents the current user is represented by a session scoped object:All beans have a well-defined scope that determines the lifecycle and visibility of instances. The set of scopes is fully extensible, with built-in scopes including request scope, conversation scope, session scope and application scope. Beans can also be dependent and inherit the scope of their injection point An instance of a session-scoped bean is bound to a user session and is shared by all requests that execute in thecontext of that session
Java EE components such as servlets, EJBs and JavaBeans do not have a well-defined scope. These components are either:• singletons, such as EJB singleton beans, whose state is shared between all clients,• stateless objects, such as servlets and stateless session beans, which do not contain client-visible state, or• objects that must be explicitly created and destroyed by their client, such as JavaBeans and stateful session beans,whose state is shared by explicit reference passing between clients.Scoped objects, by contrast, exist in a well-defined lifecycle context:• they may be automatically created when needed and then automatically destroyed when the context in which they werecreated ends, and• their state is automatically shared by clients that execute in the same context.All beans have a scope. The scope of a bean determines the lifecycle of its instances, and which instances of the bean arevisible to instances of other beans, as defined in Chapter 6, Scopes and contexts. A scope type is represented by an annotationtype.For example, an object that represents the current user is represented by a session scoped object:All beans have a well-defined scope that determines the lifecycle and visibility of instances. The set of scopes is fully extensible, with built-in scopes including request scope, conversation scope, session scope and application scope. Beans can also be dependent and inherit the scope of their injection point An instance of a session-scoped bean is bound to a user session and is shared by all requests that execute in thecontext of that sessionScope DescriptionDependent A dependent reference is created each time it is injected and the reference isremoved when the injection target is removed. This is the default scope for CDIand makes sense for the majority of cases.ApplicationScoped An object reference is created only once for the duration of the application and theobject is discarded when the application is shut down. This scope makes sense forservice objects, helper APIs or objects that store data shared by the entireapplication.RequestScoped An object reference is created for the duration of the HTTP request and isdiscarded when the request ends. This makes sense for things like data transferobjects/models and JSF backing beans that are only needed for the duration of anHTTP request.SessionScoped An object reference is created for the duration of an HTTP session and isdiscarded when the session ends. This scope makes sense for objects that areneeded throughout the session such as maybe user login credentials.ConversationScoped A conversation is a new concept introduced by CDI. It will be familiar to Seamusers, but new to most others. A conversation is essentially a truncated sessionwith start and end points determined by the application, as opposed to the sessionwhich is controlled by the browser, server and session timeout. There are twotypes of conversations in CDI -- transient which basically corresponds to a JSFrequest cycle and long-running which is controlled by you via the Conversion.beginand Conversion.end calls. A transient conversation can be turned into along-running one as needed. Conversations are very useful for objects that areused across multiple pages as part of a multi-step workflow. An order or shoppingcart is a good example. Conversations deserve detailed discussion so we will takea much closer look at them in a later article in the series.
Although it’s completely optional, beans may define an EL name that can be used for non-type safe access. One common usage of EL name is for binding components to JavaServer Faces (JSF) views. used in places where CDI’s type-based lookup is not possible.
Alternatively, an alternative may be declared by annotating a bean, producer method or producer field with a stereotypethat declares an @Alternative annotation.If an interceptor or decorator is an alternative, non-portable behavior results.Qualifiers allow class selection but require modification tosource code and recompiling if they need to be changed● Alternatives allow CDI to alternate bean classes based onXML configuration data (beans.xml)● Alternative classes (annotated with @Alternative) aredisabled by default● An enabled (via beans.xml) alternative class takesprecedence over a non-alternative class● Two enabled alternative classes matching the samequalifiers on an injection point would result in an exception
Almost always use @Inject● Lets you use interceptors, delegates, scope based beans,qualifiers, etc● Can inject EJBs● @EJB is okay for remote session beans in some cases● Lets you specify a JNDI name● @Resource is seldom needed● Injecting a DataSource● Producers can be used to enable @Inject based injectionfor @EJB and @Resource dependencies if needed
Any calls to the delegate object that correspond to a decorated type will be called on the decorator, which may in turn invoke the method directly on the delegate object.
http://www.dzone.com/links/r/decoupling_event_producers_and_consumers_in_jee6.htmlhttp://www.adam-bien.com/roller/abien/entry/java_ee_6_observer_withEvent Producer -> Event Consumer(s) [foreground thread]Event Producer -> Event Sender -> JMS Queue [foreground thread]JMS Queue -> Event Dispatcher -> Event Consumer [background threadIf there are multiple observers for an event, the order that they are called in is not definedCDI will automagically wire EventProducer and EventConsumer so that when EventProducer fires the event, EventConsumer.afterMyEvent gets called
Strategy Pattern: there are already several implementations of an algorithm or conceptLayering: there is a clear need to hide e.g. an ugly implementation of a legacy frameworkAPI (not very common): you have to expose a API, which gets implemented by SPI (e.g. JDBC)
Many of the modules developed in Seam 3 demonstrate thissuch as ‘Mail’, ‘JMS’, ‘JCR’, ‘Reports’ and ‘Spring’-Integration.All of these modules came from the community as a holewas discovered while using the technologies and seeking amore unified and simpler approach for developers.