Enterprise Application Programming PDF

Document Details

Uploaded by Deleted User

Algonquin College

Tags

Java Programming Enterprise Java Beans JPA Web Development

Summary

This document covers lecture notes on enterprise application programming for a class. Topics include Java persistence, EJBs, and JSF.

Full Transcript

Enterprise Application Programming CST 8277 (ICT-AP) Week 5 Java Persistence II, Presentation III JPA EJB JSF 2 Lesson Summary Introduce two new Jakarta EE Components EJBs – Enterprise Java Beans JPA – Java Persistence API Use with JSF 3 ...

Enterprise Application Programming CST 8277 (ICT-AP) Week 5 Java Persistence II, Presentation III JPA EJB JSF 2 Lesson Summary Introduce two new Jakarta EE Components EJBs – Enterprise Java Beans JPA – Java Persistence API Use with JSF 3 Enterprise Java Beans (EJBs) Java EE 7, includes EJB 3.2 Offers a standardized way to implement solutions for server-side business logic EJBs are POJOs, but managed by an EJB container Using EJBs as JMS listeners Makes enterprise application more scalable without having to write additional code 4 Types of Enterprise Java Beans Type Description Stateless Session Bean Contains business logic but no client state Stateful Session Bean Contains business logic and maintains client state Singleton Session Bean Instantiated once per application Message Driven Bean Listen for messages on a JMS queue or topic 5 Simple EJB Demo (Hello World) Java EE App Server: Payara TestStatelessEJBServlet StatelessEJB TestStatefulEJBServlet StatefulEJB 6 Enterprise Java Beans (EJB) Stateless Session beans (@Stateless) execute business logic without maintaining client state any state stored in member variables last only for duration of method App server (typically) has pool of stateless beans Stateful Session beans (@Stateful) a stateful session bean is similar to an interactive session, can have only 1 client any state stored in member variables represents the state of a unique client/bean session (a.k.a. conversational state) When client terminates, its session bean also terminates, no longer associated https://javaee.github.io/tutorial/ejb-intro007.html 7 Enterprise Java Beans (cont'd) Message-Driven beans App server processes method invocation asynchronously MDB acts an event listener – another EE component JMS Queue service similar to Stateless EJB: no conversational state kept with client @MessageDriven not going to focus on them in this course https://javaee.github.io/tutorial/ejb-intro007.html 8 Session Beans (cont'd) Singleton Session Beans (@Singleton) A special version of a Stateless Session Bean Only one instance of Singleton Session Bean is created for application, but can be accessed by multiple clients Some state is kept – not with clients, but with resources under its control (Db, queues, etc.) Can execute 'special' behaviour on startup (@Startup) Arrange startup order with @DependsOn if lots of startup beans Only terminates when the application is shut down above state does not survive shut down https://javaee.github.io/tutorial/ejb-intro007.html 9 Java Persistence API – EJB? (Sorry for the confusion) Before it was called 'JPA' Handle Entities and business logic using 'Enterprise Java Beans' – EJBs Marketing folks chose name (nothing to do with Java SE JavaBeans) Requires J2EE container unlike modern JPA which can function both inside EE Server and outside using Java SE Originally proposed by IBM in 1997 1998: first formal Java specification for EJB 1.0 (that’s where I came in!) 1999: EJB 1.1 2001: EJB 2.0 2003: EJB 2.1 2006: EJB 3.0 -> switch to JPA 1.0 (JSR 220) 2009: JPA 2.0 2013: JPA 2.1 2017: JPA 2.2 (JSR 338) 10 EJB – Sorry  API User implemented Container auto-generates impl (plus any required helpers) Amnon H Eden http://en.wikipedia.org/wiki/Image:Enterprise_JavaBeans_in_LePUS3.gif Creative Commons Attribution 3.0 License 11 JPA – a.k.a EJB 3.0 Industry calls (crying?) for “lightweight component” version of EJB TopLink & Hibernate previously used 'light' component: Plain Old Java Objects EJB 3.0 Expert group set out to really fix EJB (in room next to me!) Mike Keith (Oracle TopLink Architect, spec lead) Gavin King (JBoss Hibernate Architect) actually got it right (yeah!) POJO == ‘Entity’, Standard APIs, JPQL (90% HQL) Mappings in either external XML files or Annotations (choice) Transactions, Locking … 12 Intersection of Specification and Implementation Need additional information beyond what is defined in spec to make application work with Payara (Glassfish) App Server: persistence.xml (the standard file for JPA) specifies the DataSource name java:app/jdbc/someDbName that connects to Contacts database glassfish-resources.xml (or payara-resources.xml) vendor-specific files for Glassfish/Payara Links above name java:app/jdbc/someDbName to actual connection pool Q: How does java:app/jdbc/someDbName help? A: It is a JNDI reference that JPA can lookup 13 JPA Annotations What makes a POJO an Entity – Annotations: wait, we've seen these before! import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity // if @Table annotation not used, table name derived from class name public class Employee implements Serializable { private int empId; // member fields are not annotate; Hibernate will use JavaBean property get/set methods private String empName; // annotate field, or properties – never both... // @Column annotation not really needed, all attributes will be persisted unless @Transient annotation is used public String getName() { return empName; } public void setName(String name) { this.empName = name; } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // Hibernate will use H2's auto-generated PK values public int getId() { return empId; } public void setId(int id) {... 14 Querying – JPQL is HQL (well... minor differences) Build JPQL from EntityManager @PersistenceContext(unitName = "address-bookPU") protected EntityManager em;... List lnameContacts = (List)em.createQuery("SELECT c FROM Contact c WHERE c.lastname LIKE :contactName").setParameter(“contactName", name).getResultList();... List lnameContacts = (List)em.createNamedQuery("findAllCustomersWithName").setParameter("custName", "Smith").getResultList(); JPQL provides rich capabilities: expressions, joins, sub-selects, order-by, grouping, aggregates (count, sum, etc.), bulk delete & update … 15 Web Layouts and Templates Templates common in Web apps – desire for common style, layout, navigation (user's expectations) Typical three-part layout: Header – common logos; site navigation; user login/logout Content body – sides, center (main focus of app) Footer – incidental (contact us, copyright) 16 JSF Templates JSF provide templating capabilities (Demo) jsf-templates project Drawbacks: Phases – much more complex some phases skipped: , some phases invoked multiple times: JS/DOM lifecycle –modern JavaScript/Web-page lifecycles document.addEventListener phase complexity interferes, listeners added multiple times or not at all Still.. good idea: 10 years later, Bootstrap! 17 Bootstrap Open-source project (Mark Otto, Jacob Thornton – while working at Twitter) HTML and CSS base artifacts: design templates for forms, buttons, tables, navigation, carousels JS Plugins: popups, transitions, modals, dropdowns Font Awesome: is... well... Awesome! Advantages: Ease-of-Use only simple knowledge of HTML/CSS required (I’m proof!) Responsive Web app's appearance changes in response to running on Mobile, Tablets, or Desktop Mobile-first Compatible: both 'regular' and mobile browsers (not easy!) 18 Bootstrap Classes (a.k.a styles) Bootstrap's CSS for (JSF's translated to ) simple – minimal padding, only horizontal dividers support for striped-rows table-hover, caption styles responsive: resize under 768px (definition of 'small' device) Buttons – numerous styles btn-default btn-primary btn-success btn-info btn-warning btn-danger btn-link 19 Regional Inventory Demo – version 2 Not just improved style, EE components connected Managed Beans Controller - InventoryController: 'name' of bean connects to XHTML DAO - InventoryDao: injected @Inject into (above) Managed Bean ViewScoped – InventoryPojo use in view Do we still need DTOs? (many opinions, nothing strictly required) EJBs Stateless or Singleton - InventoryService: injected using @EJB JPA EntityManager: injected using @PersistenceContext Demo 20 Enterprise Application Programming CST 8277 (ICT-AP) More JPA – Starting the system JPA works in both Jakarta EE and Java SE EE META-INF/persistence.xml in.war/.ear file transaction-type="JTA" org.eclipse.persistence.jpa.PersistenceProvider EclipseLink – RI; Payara/Glassfish org.hibernate.jpa.HibernatePersistenceProvider Hibernate SE META-INF/persistence.xml in classpath Persistence.createEntityManagerFactory("name-of-PU"); Programmatically (really difficult … each vendor different) 2 More JPA – In-depth look Simplest valid JPA Entity JPA needs to know that a class is 'an Entity' needs a PK (aka "Id") field needs a default constructor @Entity public class SimplestJPAPojo { @Id protected int id; protected String something; public SimplestJPAPojo() { //JPA likes the default constructor } } 3 More JPA (cont'd) @Basic for member fields/JavaBeans-style properties – basic Java types: primitives and their wrapper-types – e.g. int and Integer BigInteger/BigDecimal, various data/time classes... Optional – following are really same: protected String description; @Basic protected String description; naming convention means Db column is assumed to be "DESCRIPTION" 4 More JPA (cont'd) @Transient Opposite of @Basic – do not persist member field/JavaBeans-style property to Database (a.k.a. 'skip', 'ignore') @Id – Primary key for single Database column composite-key uses @EmbeddedId and helper class with as many member fields as key columns Possible generation strategies: GenerationType.AUTO – system chooses how to populate field/column GenerationType.IDENTITY – system leverages Db IDENTITY capabilities GenerationType.SEQUENCE – system leverages Db SEQUENCE capabilities GenerationType.TABLE – emulate SEQUENCE with table SEQ_NAME/SEQ_VAL 5 More JPA (cont'd) @Column If naming convention of Entity property does not match Database... Specify column name custom column-type definition: for example, need to use Oracle’s NVARCHAR unicode-aware column-type @Column(name="COL1", columnDefinition="NVARCHAR") insertable, updatable, unique, nullable, length – for numerics, precision and scale (floating-point) 6 More JPA (cont'd) @Temporal – for Entity properties of type java.util.Date or java.util.Calendar some Db’s have different idea of ‘date’ or ‘time’ column type (not required as often now) @Enumerated – for Java Enums: stored as String value of its Enum name @Entity public class Employee { public enum Gender { MALE, FEMALE, OTHER } @Enumerated(EnumType.STRING) // or EnumType.ORDINAL, stores 0-based protected Gender gender; } 7 More JPA (cont'd) @Version – a property (or field) that serves as an optimistic lock value. Only one @Version mappings is allowed per entity Supported types: int, Integer, short, Short, long, Long, java.sql.Timestamp @Entity public class SomeEntity { @Id protected int myId; @Version protected int version; } 8 JPA – Prevent lost updates (Typical 'startup' version) 'Last-Update-wins' Alice Db Bob Tx begin Tx begin Get Product 1 (also) Get Product 1 UPDATE Product 1, qty = 2 Bob's 30 min lunch break... 'Enter' Tx commit UPDATE Product 1, qty = 7 Tx commit Why are we over-writing the commit on Product 1? 9 JPA – Prevent lost updates Do not over-write committed work! Alice Db Bob Tx begin Tx begin Get Product 1 (also) Get Product 1 UPDATE Product 1, qty = 2, ver = 3 where ver =2 UPDATE Product 1, qty = 7, Tx commit ver = 3 where ver=2 0 rows updated (JPA) OptimisticLockException Bob must refresh his page... discovers cannot fulfill order for 7 10 MappedSuperClass All model classes inherit from ModelBase – common member fields id, description, version @javax.persistence.MappedSuperClass public abstract class ModelBase { protected int id; protected String description; protected int version; // properties-style annotations... subclasses must do same! @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } @Version public int getVersion() { return version; } public String getDescription() { return description; } } 11 Enterprise Application Programming CST 8277 (ICT-AP) Week 11 Gentle Introduction to Java EE Security 2 Gentle Introduction to Java EE Security As Java EE progressed, Security got harder and harder 3 Java EE Security Configuration in web.xml: Protected url /employee/* user And (vendor-specific) payara-web.xml (or liberty-web.xml) user USER 4 Java EE Security (cont'd) 5 Java EE Security (cont'd) Clunky, Inflexible, Server config expertise – how to code using this? Modern requirements: Account activation/lock-out/deactivate MFA - Multi-Factor Authentication Keyfob Mobile app Password Strength CAPTCHA = Completely Automated Public Turing test to tell Computers and Humans Apart Single Sign On... and more 6 JASPIC (JSR-196) Java Authentication Service Provider Interface for Containers Interface javax.security.auth.message.module.ServerAuthModule Register JASPIC module (implementation-specific; Payara admin console helps a bit) @WebListener public class MyWebListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { AuthConfigFactory factory = AuthConfigFactory.getFactory(); factory.registerConfigProvider( new MyAuthConfigProvider(), null,//name of layer, typically "HttpServlet"; null for all null, // appContextID, typically ear-id; null for all "My AuthConfigProvider" // description ); } } 7 JASPIC (cont'd) public class MyAuthConfigProvider implements AuthConfigProvider { private Map providerProperties; @Override public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { return new MyServerAuthConfig(layer, appContext, handler, providerProperties); } } public class MyServerAuthConfig implements ServerAuthConfig { @Override public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, Map properties) throws AuthException { return new MyServerAuthContext(handler); } } 8 JASPIC (cont'd) public class MyServerAuthContext implements ServerAuthContext { //delegate everything to MyServerAuthModule private ServerAuthModule serverAuthModule; public MyServerAuthContext(CallbackHandler handler) throws AuthException { serverAuthModule = new MyServerAuthModule(); serverAuthModule.initialize(null, null, handler, emptyMap()); } @Override public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { return serverAuthModule.validateRequest(messageInfo, clientSubject,serviceSubject); } } 9 JASPIC (cont'd) public class MyServerAuthModule implements ServerAuthModule { @Override public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { // actual Server Authentication Module logic goes here // Check authentication credentials ?? CallerPrincipal || Caller || Principal ?? Impl different for Servlets, JSF, EJBs, ManagedBeans, JAX-RS... return AuthStatus.SUCCESS; // oe AuthStatus.FAILURE } Five layers deep – simple, eh? 10 New Java EE Security (JSR-375) 'Soteria' – Greek goddess of Safety RI – Glassfish/Payara 5 Simpler Authentication Mechanism: Annotations, CDI (everything @Inject'd) javax.security.enterprise.identitystore.IdentityStore standardized API (caller, principal, credentials) across all components validate credentials, retrieve group/role membership, authentication, authorization pre-built: @DatabaseIdentityStoreDefinition @LdapIdentityStoreDefinition (e.g. Active Directory) @EmbeddedIdentityStoreDefinition Custom IdentityStore – for example, use JPA 11 JSR-375 Java EE Security (cont'd) Pre-built Authentication Mechanisms @BasicAuthenticationMechanismDefinition HTTP Header: key='Authorization', value = 'Basic ' is "username:password" concatenated together NEVER send over HTTP – "username:password" is in-the-clear @FormAuthenticationMechanismDefinition Redirects user to Form to collect username, password Form inputs must be called 'j_username', 'j_password' @CustomFormAuthenticationMechanismDefinition Redirects user to custom Forms – 'loginPage', 'errorPage' @Inject javax.security.enterprise.SecurityContext Demo's 12 JSR-375 Java EE Security (cont'd) More … 'rememberMe' cookies: @RememberMe(cookieMaxAgeSeconds = 3600) JSON Web Token (JWT) JWT contains header, payload and (encrypted) signature (shared-secret, public/private keys) Stateless – can be served from 3rd-party server or Server hosting the app 13 JWT (Java EE Security cont'd) 14 More … OAuth2: uses tokens but also must follow strict sequence of messages between server (a.k.a. the 'OAuth2 Dance') https://www.youtube.com/watch?v=CPbvxxslDTU (up to about 6 mins) Single-Sign On SAML – Security Assertion Markup Language (complex XML doc) Microsoft 'Active Directory'; Salesforce … User's Identity lives in one place – IdentityProvider (IDP) Client and AppServer – exchange encrypted-signed XML docs w IDP authenticated credentials can be trusted https://www.youtube.com/watch?v=i8wFExDSZv0 (up to about 7 mins) 15 Enterprise Application Programming CST 8277 (ICT-AP) Week 10 Gentle Introduction to REST 2 Gentle Introduction to REST All the various ways to ‘do’ distributed computing – EJB, CORBA, RMI, SOAP, Web Services Description Language (WSDL), etc – suffer a serious drawback: complexity REST (Representational State Transfer) – described by the doctoral dissertation of Roy Fielding (co-founder of The Apache Software Foundation) - without a spec or a Standards group Architectural hybrid-style for distributed systems, derived from multiple network- based architectures Guiding principles for software engineering to promote simplicity and scalability over all other concerns Example - Google introduced a REST service duplicating existing SOAP service (dictionary/thesaurus lookup),

Use Quizgecko on...
Browser
Browser