SlideShare a Scribd company logo
MyFaces CODI Feature Tour
Make JSF more type-safe with MyFaces CODI
Join CONFESS_2012!
Agenda


•   Type-safety
•   CODI in a Nutshell
•   CODI Setup
•   CODI Core
•   CODI JSF-Module
•   CODI Message-Module
•   CODI JPA-Module
•   CODI Bean-Validation
•   CODI Scripting-Module
•   Integration and Unit Tests with CODI
Type-safety - Why should we care about it?


•   Allows to use std. IDE features like auto-completion
•   Specialized IDE support is always behind
•   No Typos
•   Several features allow compile-time or at least startup checks
•   Easier for new developers to find usages
•   Easier refactorings
•   Easier maintenance
•   …
MyFaces CODI - Overview


• MyFaces Extensions CDI aka MyFaces CODI is a
  portable CDI extension which can be used with
  Apache OpenWebBeans, JBoss Weld,… and
  in combination with other portable CDI extensions
• CODI-Core is required in any case
• Modules
   –   JSF Module (for 1.2 and 2.0 and 2.1)
   –   JPA Module
   –   BV Module
   –   I18n-Message Module
   –   Scripting Module
   –   Test Support Modules
MyFaces CODI in a Nutshell



•   JSF 1.2 and 2.x          • Type-safe View-Configs
•   Type-safety              • Type-safe Navigation
•   Extensibility            • JPA Integration
•   Advanced Scopes          • Dependency Injection
•   Various Events             Support for BV
•   View-Controller          • Advanced I18n
•   JSF 2 Scope Mappings     • Scripting Integration
                             • And more!
CODI - SETUP
Getting CODI up and running


• Add CODI to the project
    – With Maven
        • Add the modules (or the all-in-one package) to the POM
    – Without Maven
        • Download the current dist package
        • Add the modules (or the all-in-one package) to the Classpath of
          the project
•   Start using it!
Getting CODI up and running - Hints


• With JEE 5 and Mojarra use the controlled bootstrapping
  add-on
• Attention (hint for all bean archives):
  Ensure that the libs aren’t duplicated – otherwise the CDI
  implementation will blame ambiguous interceptors, beans,…
CODI CORE
Startup*


• Startup-Observer for the StartupEvent
  Triggered after the environment is initialized
    – Initialization tasks which need an up and running environment
    – Easy logging that the module was started

      protected void logModuleStart(
         @Observes StartupEvent startupEvent) {
         ...
      }
•   StartupEventBroadcaster
    Allows to integrate custom broadcasting mechanisms before
    the first mechanism of CODI gets called
ProjectStage and ProjectStageActivated


• Configure beans for a special project-stage in a type-safe way
• Examples
    – Sample data
    – Debug Phase-Listener
    @ProjectStageActivated(
       ProjectStage.Development.class)
    public class SampleDataStartupObserver {

        protected void createSampleData(
          @Observes StartupEvent startupEvent,
          UserRepository userRepository) {
            //...
            userRepository.save(user);
        }
    }
Custom Project-Stages - 1


public class ProjectStages
  implements ProjectStageHolder {

    @Typed() //no bean!
    public static final class CustomProjectStage
      extends ProjectStage {}

    public static final CustomProjectStage
      CustomProjectStage =
        new CustomProjectStage();
}

+ Service-Loader config
Custom Project-Stages - 2


• Configure the project-stage like std. CODI project stages
    – JSF std. project stage
    – org.apache.myfaces.extensions.cdi.ProjectStage
    – ConfiguredValueResolver
• Injecting the current project-stage
   @Inject private ProjectStage projectStage;

• Compare the injected value
   ProjectStage.Development.equals(this.projectStage)

• Overrule the current project-stage manually
   ProjectStageProducer.setProjectStage(
     ProjectStages.CustomProjectStage)
[CODI-Hint] Deactivatable


• CDI allows deactivation via a veto-mechanism
• Won‘t work for artifacts which aren‘t managed by CDI
• CODI allows do deactivate such implementations which
  implement Deactivatable
• Deactivating classes via an implementation of
  ClassDeactivator (+ Service-Loader config)
CODI JSF-MODULE
@JsfPhaseListener


  @ProjectStageActivated(
      ProjectStage.Development.class,
      CustomProjectStage.Debugging.class)
  @Advanced
  @JsfPhaseListener
  public class DebugPhaseListener implements PhaseListener {
    @Inject
    private Logger logger;
      public void beforePhase(PhaseEvent phaseEvent) {
        this.logger.info("before " + phaseEvent.getPhaseId());
      }

      public void afterPhase(PhaseEvent phaseEvent) {
        this.logger.info("after " + phaseEvent.getPhaseId());
      }
      public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
      }
  }
@InvocationOrder


• Allows to specify the order of multiple artifacts
• Example

  @JsfPhaseListener
  @InvocationOrder(1) //optional
  public class DebugPhaseListener
    implements PhaseListener {
    //...
  }
JSF LOMs – JSF Lifecycle Observer Methods


• Annotations
    – @BeforePhase
    – @AfterPhase
•   Example

    public void preInvokeApplication(
      @Observes @BeforePhase(ANY_PHASE)
      PhaseEvent event) {
      //...
    }
CODI View-Configs and @Page


• Allow to
   – host meta-data for pages
   – structure pages
   – navigate in a type-safe way
• Inline usage at page-beans is possible with restrictions
• Example for index.xhtml

  @Page
  public class Index implements ViewConfig {}
Organizing your pages


• Meta-data gets inherited
  (multiple inheritance with interfaces)
• Nested classes for defining the view-id via convention
  (explicit configuration is also possible)
• Example for /pages/index.xhtml

  @Page(navigation = REDIRECT)
  public interface Pages extends ViewConfig {
    public @Page class Index implements Pages {
    }
  }
Inherit Page-Configs by Example




@Page(navigation = REDIRECT)
public interface Pages extends ViewConfig {

    public @Page class Login
      extends DefaultErrorView implements Pages {}
}
Type-safe Navigation


• View-Conig
  public Class<? extends Pages> register() {
    //...
    return Pages.Login.class;
  }
• ViewNavigationHandler (for manual navigation)
  @Inject
  private ViewNavigationHandler vnh;

  vnh.navigateTo(Pages.Login.class);
• Navigation Event (PreViewConfigNavigateEvent)
  Allows to observe type-safe navigations and change the
  navigation target
@Secured by Example


@Secured(LoginAccessDecisionVoter.class)
public interface Secure extends Pages {

    @PageBean(FeedbackPage.class)
    public @Page class FeedbackList implements Secure {}
}

@ApplicationScoped
public class LoginAccessDecisionVoter extends
AbstractAccessDecisionVoter {
  @Override
  protected void checkPermission(
    InvocationContext ic, Set<SecurityViolation> violations) {
      if(...) {
        violations.add(newSecurityViolation("access denied"));
      }
    }
}
View-Controller


• Via
   – View-Config (@PageBean)
   – Inline (@View)
   – Package based
        • @Page for Page-Beans
        • @InlineViewConfigRoot as marker
• Annotations
   –    @InitView
   –    @PrePageAction
   –    @PreRenderView
   –    @PostRenderView
View-Controller – Examples


@Secured(LoginAccessDecisionVoter.class)
public interface Secure extends Pages {

     @PageBean(FeedbackPage.class)
     public @Page class FeedbackList
       implements Secure {}
}

or

@View(Pages.Secure.FeedbackList.class)
public class FeedbackPage
  implements Serializable { ... }
Error-Pages


• Configure a default error page
• Security violations  default error page
  (or the explicitly configured page)
• Manual Navigation to the default error view
  (independent of the configured error page)

  @Inject
  private ViewNavigationHandler vnh;

  vnh.navigateTo(DefaultErrorView.class);
Type-save Config by Example



@Specializes
public class CustomJsfModuleConfig
  extends JsfModuleConfig {

    @Override
    public boolean isAlwaysKeepMessages () {
      return false;
    }
}




                     With Weld you have to use @Alternative + xml config
Custom View-Meta-data


• Allows to create custom meta-data
• Get the meta-data with:
  ViewConfigResolver
    #getViewConfigDescriptor(...)#getMetaData();
• Example

  @Target({TYPE})
  @Retention(RUNTIME)
  @Documented
  @ViewMetaData
  public @interface AppInfo { ... }

  @AppInfo
  public @Page class About implements Pages {}
CODI MESSAGE-MODULE
I18n – The Message-Module


• Highly customizable
• Easy fluent API
• Different argument formats
   – Numbered
   – Named
   – EL-Expressions (optional)
• Serializable (key + config instead of the final message)
   other users get the persisted message in their specific language
• Message-Payload (e.g. MessageSeverity)
• Different message sources
• Optimized for JSF (in combination with the JSF Module)
I18n – The Message-Module - Example


@Inject
private MessageContext messageContext;

//...
this.messageContext.message()
 .text("{msgUserRegistered}")
 .namedArgument("userName", this.user.getUserName())
 . create();


             msgUserRegistered=User {userName} registered successfully!
I18n – The Message-Module – JSF Example


@Inject
private @Jsf MessageContext messageContext;

//...

this.messageContext.message()
  .text("{msgLoginFailed}")
  .payload(ERROR)
  . add();
CODI JPA-MODULE
@Transactional


• Alternative to EJBs esp. outside an Application-Server
• Allows to customize the behaviour
• Supports multiple persistence-units with qualifiers
@Transactional - Example


@ApplicationScoped
@Transactional
public abstract class AbstractGenericJpaRepository {

    @PersistenceContext(unitName = "default")
    protected EntityManager entityManager;

    public T loadById(Long id) {
      //...
    }
}
@Transactional with multiple Persistence Units


@Produces                                    + @Disposes
@Users                                       or @PreDestroy
@PersistenceContext(unitName="UserDB")
private EntityManager usersEntityManager;

//...
@Inject
@Users
protected EntityManager entityManager;

@Transactional(Users.class)
public void update(User user) {
  this.entityManager.merge(user);
}
LET’S WRITE CODE
CODI BEAN-VALIDATION
Bean-Validation by Example - 1


@Inject @Advanced
private Validator validator;
//...
validator.validate(user);
//...

@UniqueLoginName
public class User extends AbstractEntity
{
  //...
}
Bean-Validation by Example - 2


@Target({TYPE}) @Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {
  UniqueLoginNameValidator.class})
public @interface UniqueLoginName {
}

@Dependent
public class UniqueLoginNameValidator
  extends ClassLevelValidator
    <UniqueLoginName, User> {
    @Inject
    private UserRepository userRepository;
}
CODI SCRIPTING-MODULE
Scripting-Module by Example


public class ServerSideScriptingBean {
  @Inject
  @ScriptLanguage(JavaScript.class)
  private ScriptExecutor se;

    private Double calc() {
       return se.eval("10 + 4", Double.class);
    }
}
UNIT TESTS WITH CODI
CODI and JUnit by Example


@RunWith(JUnit4.class)
public class SimpleTestCase extends AbstractJsfAwareTest {
  @Inject private RegistrationPage registrationPage;
  @Inject private UserRepository repository;

    @Test public void testRegistration() {
      User user = this.registrationPage.getUser();
      user.setUserName("gp");
      user.setFirstName("Gerhard");
      //...
      assertEquals(Pages.Login.class,
        this.registrationPage.register());
      assertEquals("Gerhard",
        this.repository.loadUser("gp").getFirstName());
    }
}
INTEGRATION TESTS WITH CODI
CODI and Cargo by Example


@RunWith(JUnit4.class)
public class SimpleTestCase
  extends AbstractContainerAwareCargoTest {

    @Test
    public void testSimpleForm() {
      SimplePageInteraction pageInteraction =
        new SimplePageInteraction(getTestConfiguration())
                  .start(Pages.Index.class)
                  .useDefaultForm();

        String inputId = "userName";
        pageInteraction.setValue(inputId, "gpetracek")
                       .clickOk()
                       .checkState(Pages.Result.class);
    }
}
WHAT’S NEXT?
… more about MyFaces CODI and Apache DeltaSpike at:
Links


•   http://myfaces.apache.org/extensions/cdi/
•   https://cwiki.apache.org/confluence/display/EXTCDI/Index
•   https://svn.apache.org/repos/asf/myfaces/extensions/cdi/
•   http://twitter.com/MyFacesTeam
•   http://myfaces.apache.org/extensions/cdi/mail-lists.html
•   Recommended
    – http://openwebbeans.apache.org
    – http://code.google.com/a/apache-extras.org/p/
      myfaces-codi-addons/
    – http://os890.spaaze.com/myfaces-codi

More Related Content

What's hot

Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7
Azilen Technologies Pvt. Ltd.
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerZeroTurnaround
 
Java EE 8
Java EE 8Java EE 8
Java EE 8
Ryan Cuprak
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
Ryan Cuprak
 
Liferay maven sdk
Liferay maven sdkLiferay maven sdk
Liferay maven sdk
Mika Koivisto
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
Ray Ploski
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutes
Serge Huber
 
Developing modern java web applications with java ee 7 and angular js
Developing modern java web applications with java ee 7 and angular jsDeveloping modern java web applications with java ee 7 and angular js
Developing modern java web applications with java ee 7 and angular jsShekhar Gulati
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Shekhar Gulati
 
Intelligent Projects with Maven - DevFest Istanbul
Intelligent Projects with Maven - DevFest IstanbulIntelligent Projects with Maven - DevFest Istanbul
Intelligent Projects with Maven - DevFest Istanbul
Mert Çalışkan
 
Introduction tomaven
Introduction tomavenIntroduction tomaven
Introduction tomaven
Manav Prasad
 
From JavaEE to AngularJS
From JavaEE to AngularJSFrom JavaEE to AngularJS
From JavaEE to AngularJS
Nebrass Lamouchi
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
Ryan Cuprak
 
Java build tool_comparison
Java build tool_comparisonJava build tool_comparison
Java build tool_comparison
Manav Prasad
 
Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)
Peter R. Egli
 
OSGi Presentation
OSGi PresentationOSGi Presentation
OSGi Presentation
Michal Malohlava
 
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application DevelopmentOSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
Sanjeeb Sahoo
 
Intro To OSGi
Intro To OSGiIntro To OSGi
Intro To OSGi
Stephan Janssen
 
Note - Apache Maven Intro
Note - Apache Maven IntroNote - Apache Maven Intro
Note - Apache Maven Introboyw165
 
Maven for Dummies
Maven for DummiesMaven for Dummies
Maven for Dummies
Tomer Gabel
 

What's hot (20)

Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 
Java EE 8
Java EE 8Java EE 8
Java EE 8
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
 
Liferay maven sdk
Liferay maven sdkLiferay maven sdk
Liferay maven sdk
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutes
 
Developing modern java web applications with java ee 7 and angular js
Developing modern java web applications with java ee 7 and angular jsDeveloping modern java web applications with java ee 7 and angular js
Developing modern java web applications with java ee 7 and angular js
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud
 
Intelligent Projects with Maven - DevFest Istanbul
Intelligent Projects with Maven - DevFest IstanbulIntelligent Projects with Maven - DevFest Istanbul
Intelligent Projects with Maven - DevFest Istanbul
 
Introduction tomaven
Introduction tomavenIntroduction tomaven
Introduction tomaven
 
From JavaEE to AngularJS
From JavaEE to AngularJSFrom JavaEE to AngularJS
From JavaEE to AngularJS
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Java build tool_comparison
Java build tool_comparisonJava build tool_comparison
Java build tool_comparison
 
Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)
 
OSGi Presentation
OSGi PresentationOSGi Presentation
OSGi Presentation
 
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application DevelopmentOSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
 
Intro To OSGi
Intro To OSGiIntro To OSGi
Intro To OSGi
 
Note - Apache Maven Intro
Note - Apache Maven IntroNote - Apache Maven Intro
Note - Apache Maven Intro
 
Maven for Dummies
Maven for DummiesMaven for Dummies
Maven for Dummies
 

Similar to Make JSF more type-safe with CDI and MyFaces CODI

Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
Virtual JBoss User Group
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Mark Proctor
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
Ondrej Mihályi
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class Libraries
Vagif Abilov
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
Azilen Technologies Pvt. Ltd.
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Rohit Kelapure
 
Eclipse plug in development
Eclipse plug in developmentEclipse plug in development
Eclipse plug in development
Martin Toshev
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 javatwo2011
 
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-JupiterToolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
Boni García
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming model
Alex Thissen
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
mfrancis
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi Applications
Effie Arditi
 
Spring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who CodeSpring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who Code
Purnima Kamath
 
CFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful CodeCFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful Code
indiver
 
How to help your editor love your vue component library
How to help your editor love your vue component libraryHow to help your editor love your vue component library
How to help your editor love your vue component library
Piotr Tomiak
 
Codeinator
CodeinatorCodeinator
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Drupalcon Paris
 
SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4Jon Galloway
 

Similar to Make JSF more type-safe with CDI and MyFaces CODI (20)

Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class Libraries
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
 
JSF2
JSF2JSF2
JSF2
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010
 
Eclipse plug in development
Eclipse plug in developmentEclipse plug in development
Eclipse plug in development
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
 
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-JupiterToolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
Toolbox for Selenium Tests in Java: WebDriverManager and Selenium-Jupiter
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming model
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi Applications
 
Spring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who CodeSpring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who Code
 
CFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful CodeCFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful Code
 
How to help your editor love your vue component library
How to help your editor love your vue component libraryHow to help your editor love your vue component library
How to help your editor love your vue component library
 
Codeinator
CodeinatorCodeinator
Codeinator
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
 
SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4
 

More from os890

Flexibilitaet mit CDI und Apache DeltaSpike
Flexibilitaet mit CDI und Apache DeltaSpikeFlexibilitaet mit CDI und Apache DeltaSpike
Flexibilitaet mit CDI und Apache DeltaSpikeos890
 
MyFaces Extensions Validator r4 news
MyFaces Extensions Validator r4 newsMyFaces Extensions Validator r4 news
MyFaces Extensions Validator r4 news
os890
 
MyFaces CODI v0.9.0 News
MyFaces CODI v0.9.0 NewsMyFaces CODI v0.9.0 News
MyFaces CODI v0.9.0 News
os890
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 News
os890
 
Metadatenbasierte Validierung
Metadatenbasierte ValidierungMetadatenbasierte Validierung
Metadatenbasierte Validierung
os890
 
MyFaces Extensions Validator 1.x.2 News
MyFaces Extensions Validator 1.x.2 NewsMyFaces Extensions Validator 1.x.2 News
MyFaces Extensions Validator 1.x.2 News
os890
 
MyFaces Extensions Validator Part 1 of 3
MyFaces Extensions Validator Part 1 of 3MyFaces Extensions Validator Part 1 of 3
MyFaces Extensions Validator Part 1 of 3
os890
 

More from os890 (7)

Flexibilitaet mit CDI und Apache DeltaSpike
Flexibilitaet mit CDI und Apache DeltaSpikeFlexibilitaet mit CDI und Apache DeltaSpike
Flexibilitaet mit CDI und Apache DeltaSpike
 
MyFaces Extensions Validator r4 news
MyFaces Extensions Validator r4 newsMyFaces Extensions Validator r4 news
MyFaces Extensions Validator r4 news
 
MyFaces CODI v0.9.0 News
MyFaces CODI v0.9.0 NewsMyFaces CODI v0.9.0 News
MyFaces CODI v0.9.0 News
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 News
 
Metadatenbasierte Validierung
Metadatenbasierte ValidierungMetadatenbasierte Validierung
Metadatenbasierte Validierung
 
MyFaces Extensions Validator 1.x.2 News
MyFaces Extensions Validator 1.x.2 NewsMyFaces Extensions Validator 1.x.2 News
MyFaces Extensions Validator 1.x.2 News
 
MyFaces Extensions Validator Part 1 of 3
MyFaces Extensions Validator Part 1 of 3MyFaces Extensions Validator Part 1 of 3
MyFaces Extensions Validator Part 1 of 3
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 

Make JSF more type-safe with CDI and MyFaces CODI

  • 1. MyFaces CODI Feature Tour Make JSF more type-safe with MyFaces CODI
  • 3. Agenda • Type-safety • CODI in a Nutshell • CODI Setup • CODI Core • CODI JSF-Module • CODI Message-Module • CODI JPA-Module • CODI Bean-Validation • CODI Scripting-Module • Integration and Unit Tests with CODI
  • 4. Type-safety - Why should we care about it? • Allows to use std. IDE features like auto-completion • Specialized IDE support is always behind • No Typos • Several features allow compile-time or at least startup checks • Easier for new developers to find usages • Easier refactorings • Easier maintenance • …
  • 5. MyFaces CODI - Overview • MyFaces Extensions CDI aka MyFaces CODI is a portable CDI extension which can be used with Apache OpenWebBeans, JBoss Weld,… and in combination with other portable CDI extensions • CODI-Core is required in any case • Modules – JSF Module (for 1.2 and 2.0 and 2.1) – JPA Module – BV Module – I18n-Message Module – Scripting Module – Test Support Modules
  • 6. MyFaces CODI in a Nutshell • JSF 1.2 and 2.x • Type-safe View-Configs • Type-safety • Type-safe Navigation • Extensibility • JPA Integration • Advanced Scopes • Dependency Injection • Various Events Support for BV • View-Controller • Advanced I18n • JSF 2 Scope Mappings • Scripting Integration • And more!
  • 8. Getting CODI up and running • Add CODI to the project – With Maven • Add the modules (or the all-in-one package) to the POM – Without Maven • Download the current dist package • Add the modules (or the all-in-one package) to the Classpath of the project • Start using it!
  • 9. Getting CODI up and running - Hints • With JEE 5 and Mojarra use the controlled bootstrapping add-on • Attention (hint for all bean archives): Ensure that the libs aren’t duplicated – otherwise the CDI implementation will blame ambiguous interceptors, beans,…
  • 11. Startup* • Startup-Observer for the StartupEvent Triggered after the environment is initialized – Initialization tasks which need an up and running environment – Easy logging that the module was started protected void logModuleStart( @Observes StartupEvent startupEvent) { ... } • StartupEventBroadcaster Allows to integrate custom broadcasting mechanisms before the first mechanism of CODI gets called
  • 12. ProjectStage and ProjectStageActivated • Configure beans for a special project-stage in a type-safe way • Examples – Sample data – Debug Phase-Listener @ProjectStageActivated( ProjectStage.Development.class) public class SampleDataStartupObserver { protected void createSampleData( @Observes StartupEvent startupEvent, UserRepository userRepository) { //... userRepository.save(user); } }
  • 13. Custom Project-Stages - 1 public class ProjectStages implements ProjectStageHolder { @Typed() //no bean! public static final class CustomProjectStage extends ProjectStage {} public static final CustomProjectStage CustomProjectStage = new CustomProjectStage(); } + Service-Loader config
  • 14. Custom Project-Stages - 2 • Configure the project-stage like std. CODI project stages – JSF std. project stage – org.apache.myfaces.extensions.cdi.ProjectStage – ConfiguredValueResolver • Injecting the current project-stage @Inject private ProjectStage projectStage; • Compare the injected value ProjectStage.Development.equals(this.projectStage) • Overrule the current project-stage manually ProjectStageProducer.setProjectStage( ProjectStages.CustomProjectStage)
  • 15. [CODI-Hint] Deactivatable • CDI allows deactivation via a veto-mechanism • Won‘t work for artifacts which aren‘t managed by CDI • CODI allows do deactivate such implementations which implement Deactivatable • Deactivating classes via an implementation of ClassDeactivator (+ Service-Loader config)
  • 17. @JsfPhaseListener @ProjectStageActivated( ProjectStage.Development.class, CustomProjectStage.Debugging.class) @Advanced @JsfPhaseListener public class DebugPhaseListener implements PhaseListener { @Inject private Logger logger; public void beforePhase(PhaseEvent phaseEvent) { this.logger.info("before " + phaseEvent.getPhaseId()); } public void afterPhase(PhaseEvent phaseEvent) { this.logger.info("after " + phaseEvent.getPhaseId()); } public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; } }
  • 18. @InvocationOrder • Allows to specify the order of multiple artifacts • Example @JsfPhaseListener @InvocationOrder(1) //optional public class DebugPhaseListener implements PhaseListener { //... }
  • 19. JSF LOMs – JSF Lifecycle Observer Methods • Annotations – @BeforePhase – @AfterPhase • Example public void preInvokeApplication( @Observes @BeforePhase(ANY_PHASE) PhaseEvent event) { //... }
  • 20. CODI View-Configs and @Page • Allow to – host meta-data for pages – structure pages – navigate in a type-safe way • Inline usage at page-beans is possible with restrictions • Example for index.xhtml @Page public class Index implements ViewConfig {}
  • 21. Organizing your pages • Meta-data gets inherited (multiple inheritance with interfaces) • Nested classes for defining the view-id via convention (explicit configuration is also possible) • Example for /pages/index.xhtml @Page(navigation = REDIRECT) public interface Pages extends ViewConfig { public @Page class Index implements Pages { } }
  • 22. Inherit Page-Configs by Example @Page(navigation = REDIRECT) public interface Pages extends ViewConfig { public @Page class Login extends DefaultErrorView implements Pages {} }
  • 23. Type-safe Navigation • View-Conig public Class<? extends Pages> register() { //... return Pages.Login.class; } • ViewNavigationHandler (for manual navigation) @Inject private ViewNavigationHandler vnh; vnh.navigateTo(Pages.Login.class); • Navigation Event (PreViewConfigNavigateEvent) Allows to observe type-safe navigations and change the navigation target
  • 24. @Secured by Example @Secured(LoginAccessDecisionVoter.class) public interface Secure extends Pages { @PageBean(FeedbackPage.class) public @Page class FeedbackList implements Secure {} } @ApplicationScoped public class LoginAccessDecisionVoter extends AbstractAccessDecisionVoter { @Override protected void checkPermission( InvocationContext ic, Set<SecurityViolation> violations) { if(...) { violations.add(newSecurityViolation("access denied")); } } }
  • 25. View-Controller • Via – View-Config (@PageBean) – Inline (@View) – Package based • @Page for Page-Beans • @InlineViewConfigRoot as marker • Annotations – @InitView – @PrePageAction – @PreRenderView – @PostRenderView
  • 26. View-Controller – Examples @Secured(LoginAccessDecisionVoter.class) public interface Secure extends Pages { @PageBean(FeedbackPage.class) public @Page class FeedbackList implements Secure {} } or @View(Pages.Secure.FeedbackList.class) public class FeedbackPage implements Serializable { ... }
  • 27. Error-Pages • Configure a default error page • Security violations  default error page (or the explicitly configured page) • Manual Navigation to the default error view (independent of the configured error page) @Inject private ViewNavigationHandler vnh; vnh.navigateTo(DefaultErrorView.class);
  • 28. Type-save Config by Example @Specializes public class CustomJsfModuleConfig extends JsfModuleConfig { @Override public boolean isAlwaysKeepMessages () { return false; } } With Weld you have to use @Alternative + xml config
  • 29. Custom View-Meta-data • Allows to create custom meta-data • Get the meta-data with: ViewConfigResolver #getViewConfigDescriptor(...)#getMetaData(); • Example @Target({TYPE}) @Retention(RUNTIME) @Documented @ViewMetaData public @interface AppInfo { ... } @AppInfo public @Page class About implements Pages {}
  • 31. I18n – The Message-Module • Highly customizable • Easy fluent API • Different argument formats – Numbered – Named – EL-Expressions (optional) • Serializable (key + config instead of the final message)  other users get the persisted message in their specific language • Message-Payload (e.g. MessageSeverity) • Different message sources • Optimized for JSF (in combination with the JSF Module)
  • 32. I18n – The Message-Module - Example @Inject private MessageContext messageContext; //... this.messageContext.message() .text("{msgUserRegistered}") .namedArgument("userName", this.user.getUserName()) . create(); msgUserRegistered=User {userName} registered successfully!
  • 33. I18n – The Message-Module – JSF Example @Inject private @Jsf MessageContext messageContext; //... this.messageContext.message() .text("{msgLoginFailed}") .payload(ERROR) . add();
  • 35. @Transactional • Alternative to EJBs esp. outside an Application-Server • Allows to customize the behaviour • Supports multiple persistence-units with qualifiers
  • 36. @Transactional - Example @ApplicationScoped @Transactional public abstract class AbstractGenericJpaRepository { @PersistenceContext(unitName = "default") protected EntityManager entityManager; public T loadById(Long id) { //... } }
  • 37. @Transactional with multiple Persistence Units @Produces + @Disposes @Users or @PreDestroy @PersistenceContext(unitName="UserDB") private EntityManager usersEntityManager; //... @Inject @Users protected EntityManager entityManager; @Transactional(Users.class) public void update(User user) { this.entityManager.merge(user); }
  • 40. Bean-Validation by Example - 1 @Inject @Advanced private Validator validator; //... validator.validate(user); //... @UniqueLoginName public class User extends AbstractEntity { //... }
  • 41. Bean-Validation by Example - 2 @Target({TYPE}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = { UniqueLoginNameValidator.class}) public @interface UniqueLoginName { } @Dependent public class UniqueLoginNameValidator extends ClassLevelValidator <UniqueLoginName, User> { @Inject private UserRepository userRepository; }
  • 43. Scripting-Module by Example public class ServerSideScriptingBean { @Inject @ScriptLanguage(JavaScript.class) private ScriptExecutor se; private Double calc() { return se.eval("10 + 4", Double.class); } }
  • 45. CODI and JUnit by Example @RunWith(JUnit4.class) public class SimpleTestCase extends AbstractJsfAwareTest { @Inject private RegistrationPage registrationPage; @Inject private UserRepository repository; @Test public void testRegistration() { User user = this.registrationPage.getUser(); user.setUserName("gp"); user.setFirstName("Gerhard"); //... assertEquals(Pages.Login.class, this.registrationPage.register()); assertEquals("Gerhard", this.repository.loadUser("gp").getFirstName()); } }
  • 47. CODI and Cargo by Example @RunWith(JUnit4.class) public class SimpleTestCase extends AbstractContainerAwareCargoTest { @Test public void testSimpleForm() { SimplePageInteraction pageInteraction = new SimplePageInteraction(getTestConfiguration()) .start(Pages.Index.class) .useDefaultForm(); String inputId = "userName"; pageInteraction.setValue(inputId, "gpetracek") .clickOk() .checkState(Pages.Result.class); } }
  • 49. … more about MyFaces CODI and Apache DeltaSpike at:
  • 50. Links • http://myfaces.apache.org/extensions/cdi/ • https://cwiki.apache.org/confluence/display/EXTCDI/Index • https://svn.apache.org/repos/asf/myfaces/extensions/cdi/ • http://twitter.com/MyFacesTeam • http://myfaces.apache.org/extensions/cdi/mail-lists.html • Recommended – http://openwebbeans.apache.org – http://code.google.com/a/apache-extras.org/p/ myfaces-codi-addons/ – http://os890.spaaze.com/myfaces-codi