As an exercise, I want all the servlet requests to be queued, and through the use of thread, the problem of cosumer/producer is actually implemented.The problem I have now is that :
Is the whole code correct? I mean, have I understood all the points correctly?
In function
redirectPage
how can I access request, response?@WebServlet(name = "UserController",urlPatterns = {"/register"}) public class UserController extends HttpServlet { private static final long serialVersionUID = 1L; private static final int MAX_QUEUE_CAPACITY = 300; private UserJsonUtils jsonUtils; private User data; final String userPath = "src/model/user/users.json"; public void init() { jsonUtils = new UserJsonUtils(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { data = jsonUtils.parseJson(request.getParameter("data")); UserQueue userQueue = new UserQueue(MAX_QUEUE_CAPACITY); UserProducer userProducer = new UserProducer(userQueue); Thread producerThread = new Thread(userProducer); UserConsumer userConsumer = new UserConsumer(userQueue); Thread consumerThread = new Thread(userConsumer); producerThread.start(); consumerThread.start(); List<Thread> threads = new ArrayList<>(); threads.add(producerThread); threads.add(consumerThread); // let threads run for two seconds sleep(2000); // stop threads userProducer.stop(); userConsumer.stop(); waitForAllThreadsToComplete(threads);}public User getData() { return data;}public void redirectPage(User user) throws IOException { jsonUtils.writeToFile(userPath, user); ///// PROBLEM /*RequestDispatcher rd = request.getRequestDispatcher("profile.jsp"); rd.forward(request, response);*/ }}
UserConsumer.java
public class UserConsumer extends UserController implements Runnable {private boolean running = false;private final UserQueue userQueue;private UserDao userDao;public UserConsumer(UserQueue userQueue) { this.userQueue = userQueue;}@Overridepublic void run() { running = true; consume();}public void stop() { running = false;}private void consume() { while (running) { if (userQueue.isEmpty()) { try { userQueue.waitIsNotEmpty(); } catch (InterruptedException e) { break; } } // avoid spurious wake-up if (!running) { break; } User user = userQueue.poll(); try { useMessage(user); } catch (IOException e) { throw new RuntimeException(e); } //Sleeping on random time to make it realistic ThreadUtil.sleep((long) (Math.random() * 100)); }}private void useMessage(User data) throws IOException { userDao = new UserDao(); PasswordValidator passwordValidator = new PasswordValidator(); boolean isValidPassword = passwordValidator.isValidPassword(data.getPassword()); if (!isValidPassword) { throw new IllegalStateException("password is not valid"); } EmailValidator emailValidator = new EmailValidator(); boolean isValidEmail = emailValidator.isValidEmail(data.getEmail()); if (!isValidEmail) { throw new IllegalStateException("email not valid"); } if (userDao.findByEmail(data.getEmail()) != null) { throw new IllegalStateException("email has been already taken"); } Address address = new Address(data.getAddress().getState(), data.getAddress().getCountry(), data.getAddress().getCity(), data.getAddress().getZipCode(), data.getAddress().getAddressLine1(), data.getAddress().getAddressLine2()); User user = new User(data.getFirstName(), data.getLastName(), data.getEmail(), address, data.getPassword(), UserRole.USER); if ( userDao.registerUser(user) != -1) { UserController userController = new UserController(); userController.redirectPage(user); } /*else { RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); rd.include(request, response); }*/}
}
public class User {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Column(name = "first_name")private String firstName;@Column(name = "last_name")private String lastName;@Column(name = "user_name")private String email;@Embeddedprivate Address address;@Column(name = "password")private String password;@Column(name="user_role")@Enumerated(EnumType.STRING)private UserRole userRole;@Column(name="locked")private Boolean locked = false;@Column(name="enabled")private Boolean enabled = false;public User(String firstName, String lastName, String email, Address address, String password, UserRole userRole) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.address = address; this.password = password; this.userRole = userRole;}//setter and getter
I used a series of consumer codes through a link that I don't have now.