Skip to contentSkip to navigationSkip to topbar
On this page

Masked Phone Numbers with Java and Servlets


This Java Servlets sample application is modeled after the amazing rental experience created by AirBnB(link takes you to an external page), but with more Klingons(link takes you to an external page).

Host users can offer rental properties which other guest users can reserve. The guest and the host can then anonymously communicate via a disposable Twilio phone number created just for a reservation. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

(warning)

Legal implications of managing communications between users

If you choose to manage communications between your users, including voice calls, text-based messages (e.g., SMS), and chat, you may need to comply with certain laws and regulations, including those regarding obtaining consent. Additional information regarding legal compliance considerations and best practices for using Twilio to manage and record communications between your users, such as when using Twilio Proxy, can be found here(link takes you to an external page).

Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.

Read how Lyft uses masked phone numbers to let customers securely contact drivers.(link takes you to an external page)


Create a Reservation

create-a-reservation page anchor

The first step in connecting a guest and host is creating a reservation. Here, we handle a form submission for a new reservation which contains the message. The guest's information is pulled out from the logged user.

Create a Reservation

create-a-reservation-1 page anchor

src/main/java/org/twilio/airtng/servlets/ReservationServlet.java

1
package org.twilio.airtng.servlets;
2
3
import org.twilio.airtng.lib.notifications.SmsNotifier;
4
import org.twilio.airtng.lib.servlets.WebAppServlet;
5
import org.twilio.airtng.lib.web.request.validators.RequestParametersValidator;
6
import org.twilio.airtng.models.Reservation;
7
import org.twilio.airtng.models.User;
8
import org.twilio.airtng.models.VacationProperty;
9
import org.twilio.airtng.repositories.ReservationRepository;
10
import org.twilio.airtng.repositories.UserRepository;
11
import org.twilio.airtng.repositories.VacationPropertiesRepository;
12
13
import javax.servlet.ServletException;
14
import javax.servlet.http.HttpServletRequest;
15
import javax.servlet.http.HttpServletResponse;
16
import java.io.IOException;
17
18
public class ReservationServlet extends WebAppServlet {
19
20
private final VacationPropertiesRepository vacationPropertiesRepository;
21
private final ReservationRepository reservationRepository;
22
private UserRepository userRepository;
23
private SmsNotifier smsNotifier;
24
25
public ReservationServlet() {
26
this(new VacationPropertiesRepository(), new ReservationRepository(), new UserRepository(), new SmsNotifier());
27
}
28
29
public ReservationServlet(VacationPropertiesRepository vacationPropertiesRepository, ReservationRepository reservationRepository, UserRepository userRepository, SmsNotifier smsNotifier) {
30
super();
31
this.vacationPropertiesRepository = vacationPropertiesRepository;
32
this.reservationRepository = reservationRepository;
33
this.userRepository = userRepository;
34
this.smsNotifier = smsNotifier;
35
}
36
37
@Override
38
public void doGet(HttpServletRequest request, HttpServletResponse response)
39
throws ServletException, IOException {
40
41
VacationProperty vacationProperty = vacationPropertiesRepository.find(Long.parseLong(request.getParameter("id")));
42
request.setAttribute("vacationProperty", vacationProperty);
43
request.getRequestDispatcher("/reservation.jsp").forward(request, response);
44
}
45
46
@Override
47
public void doPost(HttpServletRequest request, HttpServletResponse response)
48
throws ServletException, IOException {
49
50
super.doPost(request, response);
51
52
String message = null;
53
VacationProperty vacationProperty = null;
54
55
if (isValidRequest()) {
56
message = request.getParameter("message");
57
String propertyId = request.getParameter("propertyId");
58
vacationProperty = vacationPropertiesRepository.find(Long.parseLong(propertyId));
59
60
User currentUser = userRepository.find(sessionManager.get().getLoggedUserId(request));
61
Reservation reservation = reservationRepository.create(new Reservation(message, vacationProperty, currentUser));
62
smsNotifier.notifyHost(reservation);
63
response.sendRedirect("/properties");
64
}
65
preserveStatusRequest(request, message, vacationProperty);
66
request.getRequestDispatcher("/reservation.jsp").forward(request, response);
67
}
68
69
@Override
70
protected boolean isValidRequest(RequestParametersValidator validator) {
71
72
return validator.validatePresence("message");
73
}
74
75
private void preserveStatusRequest(
76
HttpServletRequest request,
77
String message, Object vacationProperty) {
78
request.setAttribute("message", message);
79
request.setAttribute("vacationProperty", vacationProperty);
80
}
81
}

Part of our reservation system is receiving reservation requests from potential renters. However, these reservations need to be confirmed. Let's see how we would handle this step.


Before the reservation is finalized, the host needs to confirm that the property was reserved. Learn how to automate this process in our first AirTNG tutorial, Workflow Automation(link takes you to an external page).

src/main/java/org/twilio/airtng/servlets/ReservationConfirmationServlet.java

1
package org.twilio.airtng.servlets;
2
3
import com.twilio.twiml.MessagingResponse;
4
import com.twilio.twiml.TwiMLException;
5
import org.twilio.airtng.lib.helpers.TwiMLHelper;
6
import org.twilio.airtng.lib.notifications.SmsNotifier;
7
import org.twilio.airtng.lib.servlets.WebAppServlet;
8
import org.twilio.airtng.models.Reservation;
9
import org.twilio.airtng.models.User;
10
import org.twilio.airtng.repositories.ReservationRepository;
11
import org.twilio.airtng.repositories.UserRepository;
12
13
import javax.servlet.ServletException;
14
import javax.servlet.http.HttpServletRequest;
15
import javax.servlet.http.HttpServletResponse;
16
import java.io.IOException;
17
18
public class ReservationConfirmationServlet extends WebAppServlet {
19
20
private UserRepository userRepository;
21
private ReservationRepository reservationRepository;
22
private SmsNotifier smsNotifier;
23
24
public ReservationConfirmationServlet() {
25
this(new UserRepository(), new ReservationRepository(), new SmsNotifier());
26
}
27
28
public ReservationConfirmationServlet(UserRepository userRepository, ReservationRepository reservationRepository, SmsNotifier smsNotifier) {
29
super();
30
this.userRepository = userRepository;
31
this.reservationRepository = reservationRepository;
32
this.smsNotifier = smsNotifier;
33
}
34
35
@Override
36
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
37
38
String phone = request.getParameter("From");
39
String smsContent = request.getParameter("Body");
40
41
String smsResponseText = "Sorry, it looks like you don't have any reservations to respond to.";
42
43
try {
44
User user = userRepository.findByPhoneNumber(phone);
45
Reservation reservation = reservationRepository.findFirstPendantReservationsByUser(user.getId());
46
if (reservation != null) {
47
if (smsContent.contains("yes") || smsContent.contains("accept"))
48
reservation.confirm();
49
else
50
reservation.reject();
51
reservationRepository.update(reservation);
52
53
smsResponseText = String.format("You have successfully %s the reservation", reservation.getStatus().toString());
54
smsNotifier.notifyGuest(reservation);
55
}
56
57
respondSms(response, smsResponseText);
58
59
} catch (Exception e) {
60
throw new RuntimeException(e);
61
}
62
}
63
64
private void respondSms(HttpServletResponse response, String message)
65
throws IOException, TwiMLException {
66
MessagingResponse twiMLResponse = TwiMLHelper.buildSmsRespond(message);
67
response.setContentType("text/xml");
68
response.getWriter().write(twiMLResponse.toXml());
69
}
70
}

Once the reservation is confirmed, we need to purchase a Twilio number that the guest and host can use to communicate.


Purchase a Twilio Number

purchase-a-twilio-number page anchor

Here we use a Twilio Java helper library(link takes you to an external page) to search for and buy a new phone number to associate with the reservation. When we buy the number, we designate a Twilio Application that will handle webhook(link takes you to an external page) requests when the new number receives an incoming call or text.

We then save the new phone number on our Reservation model, so when our app receives calls or texts to this number, we'll know which reservation the call or text belongs to.

src/main/java/org/twilio/airtng/lib/phonenumber/Purchaser.java

1
package org.twilio.airtng.lib.phonenumber;
2
3
import com.twilio.base.ResourceSet;
4
import com.twilio.http.TwilioRestClient;
5
import com.twilio.rest.api.v2010.account.IncomingPhoneNumberCreator;
6
import com.twilio.rest.api.v2010.account.availablephonenumbercountry.Local;
7
import com.twilio.type.PhoneNumber;
8
import org.twilio.airtng.lib.Config;
9
10
public class Purchaser {
11
12
private final TwilioRestClient client;
13
14
public Purchaser() {
15
client = new TwilioRestClient.Builder(Config.getAccountSid(), Config.getAuthToken()).build();
16
}
17
18
public Purchaser(TwilioRestClient client) {
19
this.client = client;
20
}
21
22
public String buyNumber(Integer areaCode) {
23
ResourceSet<Local> availableNumbersForGivenArea = Local.reader("US")
24
.setAreaCode(areaCode)
25
.setSmsEnabled(true)
26
.setVoiceEnabled(true)
27
.read();
28
29
if (availableNumbersForGivenArea.iterator().hasNext()) {
30
PhoneNumber availableNumber = createBuyNumber(
31
availableNumbersForGivenArea.iterator().next().getPhoneNumber()
32
);
33
34
return availableNumber.toString();
35
} else {
36
ResourceSet<Local> generalAvailableNumbers = Local.reader("US")
37
.setSmsEnabled(true)
38
.setVoiceEnabled(true)
39
.read();
40
if (generalAvailableNumbers.iterator().hasNext()) {
41
PhoneNumber availableNumber = createBuyNumber(
42
generalAvailableNumbers.iterator().next().getPhoneNumber()
43
);
44
return availableNumber.toString();
45
} else {
46
return null;
47
}
48
}
49
}
50
51
private PhoneNumber createBuyNumber(PhoneNumber phoneNumber) {
52
return new IncomingPhoneNumberCreator(phoneNumber)
53
.setSmsApplicationSid(Config.getApplicationSid())
54
.setVoiceApplicationSid(Config.getApplicationSid())
55
.create(client).getPhoneNumber();
56
}
57
}

Now that each reservation has a Twilio Phone Number, we can see how the application will look up reservations as guest or host calls come in.


When someone sends an SMS or calls one of the Twilio numbers you have configured, Twilio makes a request to the URL you set in the TwiML app. In this request, Twilio includes some useful information including:

  • The incomingPhoneNumber number that originally called or sent an SMS.
  • The anonymousPhoneNumber Twilio number that triggered this request.

Take a look at Twilio's SMS Documentation and Twilio's Voice Documentation for a full list of the parameters you can use.

In our servlet we use the to parameter sent by Twilio to find a reservation that has the number we bought stored in it, as this is the number both hosts and guests will call and send SMS to.

src/main/java/org/twilio/airtng/servlets/BaseExchangeServlet.java

1
package org.twilio.airtng.servlets;
2
3
import com.twilio.twiml.TwiML;
4
import com.twilio.twiml.TwiMLException;
5
import org.twilio.airtng.lib.servlets.WebAppServlet;
6
import org.twilio.airtng.models.Reservation;
7
import org.twilio.airtng.repositories.ReservationRepository;
8
9
import javax.servlet.http.HttpServletResponse;
10
import java.io.IOException;
11
import java.util.Objects;
12
13
public class BaseExchangeServlet extends WebAppServlet {
14
protected ReservationRepository reservationRepository;
15
16
public BaseExchangeServlet(ReservationRepository reservationRepository) {
17
this.reservationRepository = reservationRepository;
18
}
19
20
protected String gatherOutgoingPhoneNumber(String incomingPhoneNumber, String anonymousPhoneNumber) {
21
String outgoingPhoneNumber = null;
22
23
Reservation reservation = reservationRepository.findByAnonymousPhoneNumber(anonymousPhoneNumber);
24
25
if (Objects.equals(reservation.getUser().getPhoneNumber(), incomingPhoneNumber)) {
26
outgoingPhoneNumber = reservation.getVacationProperty().getUser().getPhoneNumber();
27
} else {
28
outgoingPhoneNumber = reservation.getUser().getPhoneNumber();
29
}
30
31
return outgoingPhoneNumber;
32
}
33
34
protected void respondTwiML(HttpServletResponse response, TwiML twiMLResponse)
35
throws IOException {
36
response.setContentType("text/xml");
37
try {
38
response.getWriter().write(twiMLResponse.toXml());
39
} catch (TwiMLException e) {
40
e.printStackTrace();
41
}
42
}
43
}

Next, let's see how to connect the guest and the host via SMS.


Our Twilio application should be configured to send HTTP requests to this controller method on any incoming text message. Our app responds with TwiML to tell Twilio what to do in response to the message.

If the initial message sent to the anonymous number was sent by the host, we forward it on to the guest. Conversely, if the original message was sent by the guest, we forward it to the host.

To find the outgoing number we'll use the gatherOutgoingPhoneNumberAsync helper method.

src/main/java/org/twilio/airtng/servlets/ExchangeSmsServlet.java

1
package org.twilio.airtng.servlets;
2
3
import com.twilio.twiml.Body;
4
import com.twilio.twiml.Message;
5
import com.twilio.twiml.MessagingResponse;
6
import org.twilio.airtng.repositories.ReservationRepository;
7
8
import javax.servlet.ServletException;
9
import javax.servlet.http.HttpServletRequest;
10
import javax.servlet.http.HttpServletResponse;
11
import java.io.IOException;
12
13
public class ExchangeSmsServlet extends BaseExchangeServlet {
14
15
@SuppressWarnings("unused")
16
public ExchangeSmsServlet() {
17
this(new ReservationRepository());
18
}
19
20
public ExchangeSmsServlet(ReservationRepository reservationRepository) {
21
super(reservationRepository);
22
}
23
24
@Override
25
public void doPost(HttpServletRequest request, HttpServletResponse response)
26
throws ServletException, IOException {
27
28
String from = request.getParameter("From");
29
String to = request.getParameter("To");
30
String body = request.getParameter("Body");
31
32
String outgoingNumber = gatherOutgoingPhoneNumber(from, to);
33
34
MessagingResponse messagingResponse = new MessagingResponse.Builder()
35
.message(new Message.Builder().body(new Body(body)).to(outgoingNumber).build())
36
.build();
37
38
respondTwiML(response, messagingResponse);
39
}
40
}

Let's see how to connect the guest and the host via phone call next.


Our Twilio application will send HTTP requests to this method on any incoming voice call. Our app responds with TwiML instructions that tell Twilio to Play an introductory MP3 audio file and then Dial either the guest or host, depending on who initiated the call.

src/main/java/org/twilio/airtng/servlets/ExchangeVoiceServlet.java

1
package org.twilio.airtng.servlets;
2
3
import com.twilio.twiml.Dial;
4
import com.twilio.twiml.Number;
5
import com.twilio.twiml.Play;
6
import com.twilio.twiml.VoiceResponse;
7
import org.twilio.airtng.repositories.ReservationRepository;
8
9
import javax.servlet.ServletException;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13
14
public class ExchangeVoiceServlet extends BaseExchangeServlet {
15
16
@SuppressWarnings("unused")
17
public ExchangeVoiceServlet() {
18
this(new ReservationRepository());
19
}
20
21
public ExchangeVoiceServlet(ReservationRepository reservationRepository) {
22
super(reservationRepository);
23
}
24
25
@Override
26
public void doPost(HttpServletRequest request, HttpServletResponse response)
27
throws ServletException, IOException {
28
29
String from = request.getParameter("From");
30
String to = request.getParameter("To");
31
32
String outgoingNumber = gatherOutgoingPhoneNumber(from, to);
33
34
VoiceResponse voiceResponse = new VoiceResponse.Builder()
35
.play(new Play.Builder("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3").build())
36
.dial(new Dial.Builder().number(new Number.Builder(outgoingNumber).build()).build())
37
.build();
38
39
respondTwiML(response, voiceResponse);
40
}
41
42
}

That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy.


If you're a Java developer working with Twilio, you might want to check out these other tutorials:

IVR: Phone Tree

Create a seamless customer service experience by building an IVR Phone Tree for your company.

Click To Call

Allow your company to convert web traffic into phone calls with the click of a button.

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio(link takes you to an external page) to let us know what you think.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.