# Workflow Automation with Java and Servlets

One of the more abstract concepts you'll handle when building your business is what the *workflow* will look like.

At its core, setting up a standardized workflow is about enabling your service providers (agents, hosts, customer service reps, administrators, and the rest of the gang) to better serve your customers.

To illustrate a very real-world example, today we'll build a Java and Servlets webapp for finding and booking vacation properties — tentatively called ***Airtng***.

Here's how it'll work:

1. A *host* creates a vacation property listing
2. A *guest* requests a reservation for a property
3. The *host* receives an SMS notifying them of the reservation request. The host can either **Accept** or **Reject** the reservation
4. The *guest* is notified whether a request was rejected or accepted

*[Learn how Airbnb used Twilio SMS to streamline the rental experience for 60M+ travelers around the world.](https://customers.twilio.com/en-us/airbnb)*

## Workflow Building Blocks

We'll be using the Twilio REST API to send our users messages at important junctures. Here's a bit more on our API:

* Sending Messages with Twilio API

## User and Session Management

For this workflow to work, we need to have a user model and allow logins.

```java title="User and Session Management" description="src/main/java/org/twilio/airtng/models/User.java"
// !mark(7:48)
package org.twilio.airtng.models;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @Column(name = "phone_number")
    private String phoneNumber;

    @OneToMany(mappedBy="user")
    private List<Reservation> reservations;

    @OneToMany(mappedBy="user")
    private List<VacationProperty> vacationProperties;

    public User() {
        this.reservations = new ArrayList<>();
        this.vacationProperties = new ArrayList<>();
    }

    public User(
            String name,
            String email,
            String password,
            String phoneNumber) {
        this();
        this.name = name;
        this.email = email;
        this.password = password;
        this.phoneNumber = phoneNumber;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void addReservation(Reservation reservation) {

        if (this.reservations.add(reservation) && reservation.getUser() != this) {
            reservation.setUser(this);
        }
    }

    public void removeReservation(Reservation reservation) {
        if (this.reservations.remove(reservation) && reservation.getUser() == this) {
            reservation.setUser(null);
        }
    }

    public void addVacationProperty(VacationProperty vacationProperty) {

        if (this.vacationProperties.add(vacationProperty) && vacationProperty.getUser() != this) {
            vacationProperty.setUser(this);
        }
    }

    public void removeVacationProperty(VacationProperty vacationProperty) {
        if (this.reservations.remove(vacationProperty) && vacationProperty.getUser() == this) {
            vacationProperty.setUser(null);
        }
    }

}
```

Next, let's look at the Vacation Property model.

## Vacation Property Model

In order to build a true vacation rental company we'll need a way to create a property rental listing.

The `VacationProperty` model belongs to the `User` who created it (we'll call this user the *host* moving forward) and contains only two properties: a `description` and an `imageUrl`.

The model has two associations implemented: there are many *reservations* in it and many *users* can make those reservations.

```java title="Vacation Property Model" description="src/main/java/org/twilio/airtng/models/VacationProperty.java"
// !mark(7:37)
package org.twilio.airtng.models;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "vacation_properties")
public class VacationProperty {

    @javax.persistence.Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "description")
    private String description;

    @Column(name = "image_url")
    private String imageUrl;

    @OneToMany(mappedBy = "vacationProperty")
    private List<Reservation> reservations;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    public VacationProperty() {
        this.reservations = new ArrayList<Reservation>();
    }

    public VacationProperty(String description, String imageUrl, User user) {
        this.description = description;
        this.imageUrl = imageUrl;
        this.user = user;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void addReservation(Reservation reservation) {

        if (this.reservations.add(reservation) && reservation.getVacationProperty() != this) {
            reservation.setVacationProperty(this);
        }
    }

    public void removeReservation(Reservation reservation) {
        if (this.reservations.remove(reservation) && reservation.getVacationProperty() == this) {
            reservation.setVacationProperty(null);
        }
    }
}
```

Next, let's look at the all-important Reservation model.

## The Reservation Model

The `Reservation` model is at the center of the workflow for this application. It is responsible for keeping track of:

* The `guest` who performed the reservation
* The `vacation property` the guest is requesting (and associated *host*)
* The `status` of the reservation: `pending`, `confirmed`, or `rejected`

```java title="The Reservation Model" description="src/main/java/org/twilio/airtng/models/Reservation.java"
// !mark(5:37)
package org.twilio.airtng.models;

import javax.persistence.*;

@Entity
@Table(name = "reservations")
public class Reservation {

    @javax.persistence.Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "message")
    private String message;

    @Column(name = "status")
    private Integer status;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vacation_property_id")
    private VacationProperty vacationProperty;

    public Reservation() {
    }

    public Reservation(String message, VacationProperty vacationProperty, User user) {
        this();
        this.message = message;
        this.vacationProperty = vacationProperty;
        this.user = user;
        this.setStatus(Status.Pending);
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Status getStatus() {
        return Status.getType(this.status);
    }

    public void setStatus(Status status) {
        if (status == null) {
            this.status = null;
        } else {
            this.status = status.getValue();
        }
    }

    public VacationProperty getVacationProperty() {
        return vacationProperty;
    }

    public void setVacationProperty(VacationProperty vacationProperty) {
        this.vacationProperty = vacationProperty;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void reject() {
        this.setStatus(Status.Rejected);
    }

    public void confirm() {
        this.setStatus(Status.Confirmed);
    }

    public enum Status {

        Pending(0), Confirmed(1), Rejected(2);

        private int value;

        Status(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            switch (value) {
                case 0:
                    return "pending";
                case 1:
                    return "confirmed";
                case 2:
                    return "rejected";
            }
            return "Value out of range";
        }


        public static Status getType(Integer id) {

            if (id == null) {
                return null;
            }

            for (Status status : Status.values()) {
                if (id.equals(status.getValue())) {
                    return status;
                }
            }
            throw new IllegalArgumentException("No matching type for value " + id);
        }
    }
}
```

Next up, we'll show how our new application will create a new reservation.

## Create a Reservation

The reservation creation form holds only one field: the message that will be sent to the *host* when reserving one of her properties.

The rest of the information necessary to create a reservation is taken from the logged in user and the relationship between a property and its owner. Our base generic [`Repository`](https://github.com/TwilioDevEd/airtng-servlets/blob/eac1e32c4d2eb2071ef00f4e6b7b78b33cdcc541/src/main/java/org/twilio/airtng/repositories/Repository.java#L53-L66) is in charge of handling entity insertion.

A reservation is created with a default status of `pending`. This lets our application react to a host rejecting or accepting a reservation request.

```java title="Create a new reservation" description="src/main/java/org/twilio/airtng/servlets/ReservationServlet.java"
// !mark(45:67)
package org.twilio.airtng.servlets;

import org.twilio.airtng.lib.notifications.SmsNotifier;
import org.twilio.airtng.lib.servlets.WebAppServlet;
import org.twilio.airtng.lib.web.request.validators.RequestParametersValidator;
import org.twilio.airtng.models.Reservation;
import org.twilio.airtng.models.User;
import org.twilio.airtng.models.VacationProperty;
import org.twilio.airtng.repositories.ReservationRepository;
import org.twilio.airtng.repositories.UserRepository;
import org.twilio.airtng.repositories.VacationPropertiesRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ReservationServlet extends WebAppServlet {

    private final VacationPropertiesRepository vacationPropertiesRepository;
    private final ReservationRepository reservationRepository;
    private UserRepository userRepository;
    private SmsNotifier smsNotifier;

    public ReservationServlet() {
        this(new VacationPropertiesRepository(), new ReservationRepository(), new UserRepository(), new SmsNotifier());
    }

    public ReservationServlet(VacationPropertiesRepository vacationPropertiesRepository, ReservationRepository reservationRepository, UserRepository userRepository, SmsNotifier smsNotifier) {
        super();
        this.vacationPropertiesRepository = vacationPropertiesRepository;
        this.reservationRepository = reservationRepository;
        this.userRepository = userRepository;
        this.smsNotifier = smsNotifier;
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        VacationProperty vacationProperty = vacationPropertiesRepository.find(Long.parseLong(request.getParameter("id")));
        request.setAttribute("vacationProperty", vacationProperty);
        request.getRequestDispatcher("/reservation.jsp").forward(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        super.doPost(request, response);

        String message = null;
        VacationProperty vacationProperty = null;

        if (isValidRequest()) {
            message = request.getParameter("message");
            String propertyId = request.getParameter("propertyId");
            vacationProperty = vacationPropertiesRepository.find(Long.parseLong(propertyId));

            User currentUser = userRepository.find(sessionManager.get().getLoggedUserId(request));
            Reservation reservation = reservationRepository.create(new Reservation(message, vacationProperty, currentUser));
            smsNotifier.notifyHost(reservation);
            response.sendRedirect("/properties");
        }
        preserveStatusRequest(request, message, vacationProperty);
        request.getRequestDispatcher("/reservation.jsp").forward(request, response);
    }

    @Override
    protected boolean isValidRequest(RequestParametersValidator validator) {

        return validator.validatePresence("message");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String message, Object vacationProperty) {
        request.setAttribute("message", message);
        request.setAttribute("vacationProperty", vacationProperty);
    }
}
```

Now let's look at how the system will notify a `host` when a new reservation request is submitted.

## Notify the Host

When a reservation is created for a property we want to notify the owner that someone has made a reservation.

We use an abstraction called `SmsNotifier` which under the hood uses another abstraction called `Sender`. Here is where we use [Twilio's Rest API](/docs/iam/api) to send an SMS message to the *host* using your [Twilio phone number](https://twilio.com/console).

```java title="Notify the host" description="src/main/java/org/twilio/airtng/lib/sms/Sender.java"
// !mark(20:26)
package org.twilio.airtng.lib.sms;

import com.twilio.http.TwilioRestClient;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;
import org.twilio.airtng.lib.Config;

public class Sender {

    private final TwilioRestClient client;

    public Sender() {
        client = new TwilioRestClient.Builder(Config.getAccountSid(), Config.getAuthToken()).build();
    }

    public Sender(TwilioRestClient client) {
        this.client = client;
    }

    public void send(String to, String message) {
        new MessageCreator(
                new PhoneNumber(to),
                new PhoneNumber(Config.getPhoneNumber()),
                message
        ).create(client);
    }

}
```

The next step shows how to handle a host accepting or rejecting a request - let's continue.

## Handle Incoming Messages

Let's take a closer look at the `ReservationConfirmation` servlet. This servlet handles our incoming Twilio request and does three things:

1. Check for a pending reservation from the incoming user.
2. Update the status of the reservation.
3. Respond to the host and send notification to the guest.

## Incoming Twilio Requests

In the [Twilio console](https://twilio.com/console), you should change the 'A Message Comes In' webhook to call your application's endpoint in the route `/reservation-confirmation:`

![Messaging configuration with webhook URL set to https://yourserver.com/sms.](https://docs-resources.prod.twilio.com/f25966b33e960a4214a186c1dbdd0d35aff94f3b3c704f7db85ba8a082ec20d2.png)

One way to expose your machine to the world during development is to use [ngrok](https://ngrok.com/). Your URL for the SMS web hook on your phone number should look something like this:

```bash
http://<subdomain>.ngrok.io/reservation-confirmation
```

An incoming request from Twilio comes with some helpful parameters, including the `From` phone number and the message `Body`.

We'll use the `From` parameter to lookup the host and check if they have any pending reservations. If they do, we'll use the message body to check for an 'accept' or 'reject'.

Finally, we update the reservation status and use the `SmsNotifier` abstraction to send an SMS to the *guest* with the news.

```java title="Handle incoming messages" description="Webhook for handling Host's decision"
// !mark(35:62)
package org.twilio.airtng.servlets;

import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;
import org.twilio.airtng.lib.helpers.TwiMLHelper;
import org.twilio.airtng.lib.notifications.SmsNotifier;
import org.twilio.airtng.lib.servlets.WebAppServlet;
import org.twilio.airtng.models.Reservation;
import org.twilio.airtng.models.User;
import org.twilio.airtng.repositories.ReservationRepository;
import org.twilio.airtng.repositories.UserRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ReservationConfirmationServlet extends WebAppServlet {

    private UserRepository userRepository;
    private ReservationRepository reservationRepository;
    private SmsNotifier smsNotifier;

    public ReservationConfirmationServlet() {
        this(new UserRepository(), new ReservationRepository(), new SmsNotifier());
    }

    public ReservationConfirmationServlet(UserRepository userRepository, ReservationRepository reservationRepository, SmsNotifier smsNotifier) {
        super();
        this.userRepository = userRepository;
        this.reservationRepository = reservationRepository;
        this.smsNotifier = smsNotifier;
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String phone = request.getParameter("From");
        String smsContent = request.getParameter("Body");

        String smsResponseText = "Sorry, it looks like you don't have any reservations to respond to.";

        try {
            User user = userRepository.findByPhoneNumber(phone);
            Reservation reservation = reservationRepository.findFirstPendantReservationsByUser(user.getId());
            if (reservation != null) {
                if (smsContent.contains("yes") || smsContent.contains("accept"))
                    reservation.confirm();
                else
                    reservation.reject();
                reservationRepository.update(reservation);

                smsResponseText = String.format("You have successfully %s the reservation", reservation.getStatus().toString());
                smsNotifier.notifyGuest(reservation);
            }

        respondSms(response, smsResponseText);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void respondSms(HttpServletResponse response, String message)
            throws IOException, TwiMLException {
        MessagingResponse twiMLResponse = TwiMLHelper.buildSmsRespond(message);
        response.setContentType("text/xml");
        response.getWriter().write(twiMLResponse.toXml());
    }
}
```

Next up, let's see how we will respond to Twilio.

## TwiML Response

Finally, we'll use [Twilio's TwiML](/docs/glossary/what-is-twilio-markup-language-twiml) as a response to Twilio's server instructing it to send SMS notification message to the *host.*

We'll be using the [`Message`](/docs/messaging/twiml/message) verb to instruct Twilio's server that it should send the message.

```java title="Build a TwiML response" description="src/main/java/org/twilio/airtng/servlets/ReservationConfirmationServlet.java"
// !mark(64:69)
package org.twilio.airtng.servlets;

import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;
import org.twilio.airtng.lib.helpers.TwiMLHelper;
import org.twilio.airtng.lib.notifications.SmsNotifier;
import org.twilio.airtng.lib.servlets.WebAppServlet;
import org.twilio.airtng.models.Reservation;
import org.twilio.airtng.models.User;
import org.twilio.airtng.repositories.ReservationRepository;
import org.twilio.airtng.repositories.UserRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ReservationConfirmationServlet extends WebAppServlet {

    private UserRepository userRepository;
    private ReservationRepository reservationRepository;
    private SmsNotifier smsNotifier;

    public ReservationConfirmationServlet() {
        this(new UserRepository(), new ReservationRepository(), new SmsNotifier());
    }

    public ReservationConfirmationServlet(UserRepository userRepository, ReservationRepository reservationRepository, SmsNotifier smsNotifier) {
        super();
        this.userRepository = userRepository;
        this.reservationRepository = reservationRepository;
        this.smsNotifier = smsNotifier;
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String phone = request.getParameter("From");
        String smsContent = request.getParameter("Body");

        String smsResponseText = "Sorry, it looks like you don't have any reservations to respond to.";

        try {
            User user = userRepository.findByPhoneNumber(phone);
            Reservation reservation = reservationRepository.findFirstPendantReservationsByUser(user.getId());
            if (reservation != null) {
                if (smsContent.contains("yes") || smsContent.contains("accept"))
                    reservation.confirm();
                else
                    reservation.reject();
                reservationRepository.update(reservation);

                smsResponseText = String.format("You have successfully %s the reservation", reservation.getStatus().toString());
                smsNotifier.notifyGuest(reservation);
            }

        respondSms(response, smsResponseText);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void respondSms(HttpServletResponse response, String message)
            throws IOException, TwiMLException {
        MessagingResponse twiMLResponse = TwiMLHelper.buildSmsRespond(message);
        response.setContentType("text/xml");
        response.getWriter().write(twiMLResponse.toXml());
    }
}
```

Congrats! You've just learned how to automate your workflow with Twilio SMS.

Next, let's look at some other interesting features you might want to add to your application.

## Where to Next?

Like Twilio? Like Java? You're in the right place. Here are a couple other excellent tutorials:

**[SMS and MMS notifications](/blog/server-notifications-java-servlets)**

Build a server notification system that will alert all administrators via SMS when a server outage occurs.

**[Click To Call](/docs/voice/sdks/javascript/get-started)**

Convert web traffic into phone calls with the click of a button.
