275 - Enterprise app - Final

Lec7 : Transaction

★ A series of actions (often database operations) that are treated as a single unit of work
★ Essential technique in enterprise applications to ensure data integrity and consistency

ACID

  • Atomicity: An atomic operation that consists of a series of actions. The atomicity of a transaction ensures that the actions either complete entirely or take no effect at all
  • Consistency: Upon completion, your data and resources will be in a consistent state that conforms to business rules
  • Isolation: Because there may be many transactions processing with the same data set at the same time, each transaction should be isolated from others to prevent data corruption
  • Durability : Upon completion, its result should be durable to survive any system failure. Usually, the result of a transaction is written to persistent storage

JDBC: boilerplate code

Managing Transactions with JDBC Commit and Rollback

"boilerplate code" is any seemingly repetitive code that shows up again and again in order to get some result that seems like it ought to be much simpler.

⇩⇩⇩

TransactionManager interface : Still have some boilerplate code

⇩⇩⇩
Declarative Transactions with Transaction Advices

  • Annotate public methods only
  • Transaction manager needs to be specified
    • Use the bean name transactionManager, or
    • Explicitly specify a transaction manager <tx: annotation-driven transaction-manager="transactionManager"/>

Transaction Propagation

REQUIRED : Default propagation

  • Use existing if there is any
  • Otherwise create a new transaction

REQUIRES_NEW

  • Must start a **new transaction
  • If there’s an existing one, suspend it
  • When it’s done, resume suspended

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Helvetica}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 15.0px Helvetica}

● SUPPORTS : Optional; run with any existing transaction
● NOT_SUPPORTED : Suspend existing transactions
● MANDATORY : Throw an exception if no transactions in progress
● NEVER : Throw an exception if there is any transaction
● NESTED : Allow nesting of subtransactions

Problems Caused by Concurrent Transactions

Dirty read

T1 reads a field that has been updated by T2 but not yet committed. Later, if T2 rolls back, the field read by T1 will be temporary and invalid

Non-repeatable read

T1 reads a field and then T2 updates the field. Later, if T1 reads the same field again, the value will be different

Phantom read

T1 queries a table and gets some rows back, and then T2 inserts new rows into the table. When T1 queries the same table again, there will be additional rows

Lost updates

T1 and T2 both select a row for update, and based on the state of that row, make an update to it. Thus, one overwrites the other when the second transaction to commit should have waited until the first one committed before performing its selection

Spring isolation levels

Attributes

Timeout and Read-only Attributes

Timeout: How long this transaction runs before timing out and being rolled back automatically

Read-only status: A read-only transaction can be used when your code reads but does not modify data.

Rollback Attribute

By default, only unchecked exceptions will cause a rollback

  • RuntimeException
  • Error
  • Customize the rollback transaction attribute.

Lec8 : Security

Access Control

Authentication

  • Process of verifying a principal’s identity against what it claims to be
  • A principal has to provide evidence of identity to be authenticated

Authorization : Process of granting authorities to an authenticated user for accessing particular resources

Role Based Access Control

  • Role based authorization
    • Authorize permissions at the role level
  • Role engineering
    • Create the right roles
  • Role assignment
    • Assign users to roles

Form-based login service: A default page that contains a login form for users to log into this application
Logout service: A handler mapped with a URL for users to log out
HTTP Basic authentication: Authenticates by the basic credentials presented in HTTP request headers
Anonymous login: Assigns a principal and grants authorities to an anonymous user as if it is like a normal user
Remember-me support: Remembers a user’s identity across multiple browser sessions, usually by storing a cookie in the user’s browser
Servlet API integration: Allows you to access security info via standard Servlet APIs HttpServletRequest.isUserInRole() and HttpServletRequest.getUserPrincipal()

DelegatingFilterProxy Configuration

Better to separate the security configurations in an isolated file

HTTP Basic Authentication

<http-basic> : When required, a browser will typically display a login dialog or a specific login page for users to log in

form-based login take precedence with HTTP Basic Authentication

Form-based authentication

Render a web page that contains a login form for users to input their login details and process the login form submission

Differ from HTTP-Basic

● Does not use the formal HTTP authentication techniques (basic or digest via WWW-Authenticate)

● Uses the standard HTML form fields to pass the username and password values

● The server validates the credentials and then creates a “session” that is tied to a unique key

● The server supports log off by invalidating the session key

Anonymous Login

Configured via the <anonymous> element, where you can customize the username and authorities of an anonymous user, whose default values are anonymousUser and ROLE_ANONYMOUS

Authenticating Users with Inline Definitions

You can specify a username, a password, a disabled status, and a set of granted authorities

Authenticating Users Against a Database

Authenticating Users by providing your own tables and queries

LDAP (Lightweight Directory Access Protocol) :

Encrypting Passwords

Method Security

The @Secured annotation is used to specify a list of roles on a method. Hence, a user only can access that method if she has at least one of the specified roles.

@Secured({ "ROLE_VIEWER", "ROLE_EDITOR" })
public boolean isValidUsername(String username) {
    return userRoleRepository.isValidUsername(username);
}

Lec9: Java Message Service

Messaging is a form of loosely coupled distributed communication, **where the term 'communication' means exchange of messages between software components
❏ Integrate heterogeneous platforms
❏ Reduce system bottlenecks and increase scalability
❏ Respond more quickly to changes

Point-To-Point

❏ Messages are routed to an individual consumer
❏ Involved parties: senders, queues, and receivers

Publish-Subscribe

❏ Messages are published to a particular topic
❏ Subscribers subscribe to a particular message topic
❏ Involve subscribers, topics, and receivers

Java Message Service (JMS)

is a specification that allows Java applications to create, send, receive, and read distributed enterprise messages ➜ loosely coupled, reliable, and asynchronous.

  • do not want components to depend on information from other's interface
  • run whether all components are up and running simultaneously
  • Allow component operate without receiving immediate response

Basic JMS Concepts and Objects

  • JMS provider: a messaging system that implements the JMS interfaces and provides administrative and control features.
  • JMS clients: Java programs/components that produce and consume messages
  • Messages: objects that communicate information between JMS clients
  • Administered objects: preconfigured JMS objects, destinations and connection factories, created by an administrator for the use of clients

JMS Architecture

Administrative tools allow you to bind destinations and connection factories into a JNDI namespace

A JMS client can then use resource injection to access the administered objects and establish a logical connection to the JMS provider

Point-to-Point Messaging

❏ Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages
❏ Queues retain all messages sent to them until the messages are consumed or expire
❏ Each message has only one consumer
❏ A sender and a receiver of a message have no timing dependencies

Publish/Subscribe Messaging

❏ Clients address messages to a topic
❏ The system distributes the messages arriving from a topic’s multiple publishers to its multiple subscribers
❏ Topics retain messages only as long as it takes to distribute them to current subscribers
❏ Publishers and subscribers have timing dependencies

Durable Subscriptions

receive messages sent while the subscribers are not active

TopicSubscriber sub1 = 
session.createDurableSubscriber(topic, "myPubId1");

Message Consumption

❏ Synchronously: A subscriber explicitly fetches the message by calling the receive method, which can block until a message arrives or timing out

❏ Asynchronously: A client can register a message listener with a consumer, whose onMessage method gets called when a message arrives

The JMS API Programming Model

JMS basic building blocks

❏ Administered objects
❏ Connection factories
❏ Destinations

❏ Connections
❏ Sessions
❏ Message producers
❏ Message consumers
❏ Messages

Administered objects

JMS API provides two kinds of Administered Objects to the JMS Clients.

  • Connection Factory
  • Destination

A connection factory is the object a client uses to create a connection to a provider

❏ Encapsulates a set of connection configuration parameters that has been defined by an administrator
❏ Each is an instance of the ConnectionFactory, QueueConnectionFactory, or TopicConnectionFactory interface

A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes

❏ Queues in the PTP messaging domain
❏ Topics in the pub/sub messaging domain

Connections

A connection encapsulates a virtual connection with a JMS provider

❏ Could represent an open TCP/IP socket between a client and a provider service daemon
❏ A connection to create one or more sessions

Connection connection = connectionFacorty.createConnection();

Sessions

A session is a single-threaded context for producing and consuming messages.
Sessions are used to create the following:
❏ Message producers
❏ Message consumers
❏ Messages
❏ Queue browsers
❏ Temporary queues and topics

Message Producers

used for sending messages to a destination or unidentified producers. It implements the MessageProducer interface

MessageProducer producer = session.createProducer(dest);

Message Consumers

used for receiving messages sent to a destination

MessageConsumer consumer = session.createConsumer(dest);

Allows a JMS client to register interest in a destination with a JMS provider

connection.start();
Message m = consumer.receive();

Message Listeners

A message listener is an object that acts as an asynchronous event handler for messages

❏ This object implements the MessageListener interface, with its onMessage method defines the actions to be taken when a message arrives
❏ Needs to be registered with a specific MessageConsumer by using the setMessageListener method

Message

This JMS Message is divided into 3 parts:

  • Message Header
  • Message Properties
  • Message Body

Message Header

This section is mandatory. It contains predefined name-value pairs used by JMS Clients and JMS Providers to identify and route messages.

Message Body

This section is optional. It contains actual message sent from JMS Sender to JMS Receiver. It supports the following message formats:

  • TextMessage
  • ObjectMessage
  • BytesMessage
  • StreamMessage
  • MapMessage

Create and consume a Text message

Basic Reliability Mechanisms

  • Controlling message acknowledgment: You can specify various levels of control over message acknowledgment.
  • Specifying message persistence: You can specify that messages are persistent, meaning that they must not be lost in the event of a provider failure.
  • Setting message priority levels: You can set various priority levels for messages, which can affect the order in which the messages are delivered.
  • Allowing messages to expire: You can specify an expiration time for messages so that they will not be delivered if they are obsolete.

Lec10: Advanced Java Features

❏ Java 7 - String switch, try with resources, enhanced catches, improved type inferences

static String readFirstLineFromFile(String path) throws IOException {
    // try with resources
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
    //  enhanced catches
    catch( NullPointerException npe | IndexOutOfBoundsException iobe )
    {
           throw ex;
    }
}
// Java Type Inference
List<Integer> list2 = new ArrayList<>();

❏ Java 8 - Streams, Iterable forEach, lambda expressions,

forEach

Streams

A stream is a sequence of elements supporting sequential and parallel aggregate operations ➜ stream pipeline

❏ Source
❏ Intermediate operations (filer, sorted, map, ...)
❏ Terminate operation (sum, match, collect, iterator, reduce, …)

Operation: Must be non-interfering (do not modify the stream source); In most cases must be stateless

Intermediate operations not executed until terminal operation

Can execute in sequence or parallel :
❏ Collection.stream() - sequential
❏ Collection.parallelStream() - parallel
❏ BaseStream.sequential()
❏ BaseStream.parallel()

lambda expressions

❏ Java 9 - Modules, HTTP 2.0, process API

❏ Java 10 - Local Variable Type Inference

var

Where not to use var?

  • public long process(var list) { }
  • var x = null;
  • var x; x=5;
  • var x = () -> {}

results matching ""

    No results matching ""