package com.nevernote.login;
import java.io.File;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasypt.util.password.BasicPasswordEncryptor;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.nevernote.domain.Preferences;
import com.nevernote.domain.Users;
import com.nevernote.enums.ColorScheme;
import com.nevernote.enums.SortingMethod;
import com.nevernote.service.PreferencesService;
import com.nevernote.service.UsersService;
/**
* Servlet implementation class LoginServlet
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 8379761632383399763L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context.xml");
ctx.refresh();
UsersService usersService = ctx.getBean("usersService", UsersService.class);
PreferencesService preferenceService = ctx.getBean("preferencesService", PreferencesService.class);
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(request.getParameter("pw"));
if(usersService.findById(request.getParameter("un")) != null) {
request.setAttribute("registrationMessage", "Username is already taken please regiser with another user name.");
String url = "/Register.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
return;
} else {
Users newUser = new Users();
newUser.setId(request.getParameter("un"));
newUser.setPassword(encryptedPassword);
newUser.setPriviledge("standard");
newUser.setEnabled(true);
System.out.println(newUser.toString());
Users savedUser = usersService.save(request.getParameter("un"),newUser);
Preferences prefs = new Preferences();
prefs.setUserID(savedUser.getId());
prefs.setColors(ColorScheme.valueOf("BLACK_ON_WHITE").toString());
prefs.setSort(SortingMethod.valueOf("ALPHA_ASCENDING").toString());
preferenceService.save(prefs);
String relativeWebPath = "WEB-INF/notesRepo";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File directory = new File(absoluteDiskPath + "/" + newUser.getId());
boolean success = directory.mkdirs();
if (success) {
request.setAttribute("success", "Successfully created new user.");
String url = "/Login.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
return;
}
}
response.sendRedirect("Login.jsp");
}
}