• Save
Make JSF more type-safe with CDI and MyFaces CODI
Upcoming SlideShare
Loading in...5
×
 

Make JSF more type-safe with CDI and MyFaces CODI

on

  • 7,759 views

These slides show how to use type-safe mechanisms provided by MyFaces CODI for developing JSF applications which are more type-safe and easier to maintain. ...

These slides show how to use type-safe mechanisms provided by MyFaces CODI for developing JSF applications which are more type-safe and easier to maintain.

http://2012.con-fess.com/sessions/-/details/136/MyFaces-CODI-and-JBoss-Seam3-become-Apache-DeltaSpike is the next part with more details about MyFaces CODI and Apache DeltaSpike at

Statistics

Views

Total Views
7,759
Slideshare-icon Views on SlideShare
5,003
Embed Views
2,756

Actions

Likes
3
Downloads
19
Comments
0

40 Embeds 2,756

http://os890.blogspot.com 930
http://os890.blogspot.co.at 665
http://os890.blogspot.de 539
http://os890.blogspot.com.br 86
http://os890.blogspot.fr 56
http://os890.blogspot.ru 54
http://os890.blogspot.se 45
http://os890.blogspot.nl 41
http://os890.blogspot.ca 39
http://os890.blogspot.it 33
http://os890.blogspot.ch 30
http://os890.blogspot.in 28
http://os890.blogspot.no 24
http://os890.blogspot.cz 19
http://os890.blogspot.jp 18
http://os890.blogspot.hk 17
http://os890.blogspot.co.uk 15
http://os890.blogspot.mx 14
http://os890.blogspot.com.es 12
http://os890.blogspot.be 11
http://os890.blogspot.com.tr 11
http://os890.blogspot.sk 11
http://os890.blogspot.com.au 11
http://os890.blogspot.kr 7
http://os890.blogspot.dk 5
http://os890.blogspot.co.nz 5
http://os890.blogspot.com.ar 4
http://os890.blogspot.fi 4
http://os890.blogspot.ie 3
http://os890.blogspot.gr 3
http://os890.blogspot.pt 3
http://webcache.googleusercontent.com 2
http://os890.blogspot.hu 2
http://os890.blogspot.ae 2
http://os890.blogspot.tw 2
http://os890.blogspot.co.il 1
http://www.tubebox.us 1
http://os890.blogspot.ro 1
http://translate.googleusercontent.com 1
http://www.os890.blogspot.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Make JSF more type-safe with CDI and MyFaces CODI Make JSF more type-safe with CDI and MyFaces CODI Presentation Transcript

    • MyFaces CODI Feature TourMake 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 - 1public 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 {}}@ApplicationScopedpublic class LoginAccessDecisionVoter extendsAbstractAccessDecisionVoter { @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@Specializespublic 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@Injectprivate MessageContext messageContext;//...this.messageContext.message() .text("{msgUserRegistered}") .namedArgument("userName", this.user.getUserName()) . create(); msgUserRegistered=User {userName} registered successfully!
    • I18n – The Message-Module – JSF Example@Injectprivate @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@Transactionalpublic 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@Usersprotected 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 @Advancedprivate Validator validator;//...validator.validate(user);//...@UniqueLoginNamepublic class User extends AbstractEntity{ //...}
    • Bean-Validation by Example - 2@Target({TYPE}) @Retention(RUNTIME)@Documented@Constraint(validatedBy = { UniqueLoginNameValidator.class})public @interface UniqueLoginName {}@Dependentpublic class UniqueLoginNameValidator extends ClassLevelValidator <UniqueLoginName, User> { @Inject private UserRepository userRepository;}
    • CODI SCRIPTING-MODULE
    • Scripting-Module by Examplepublic 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