Ladies_Man

login phone formatter

May 25th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.64 KB | None | 0 0
  1. package ru.pochta.abon.ui.view;
  2.  
  3. import com.google.i18n.phonenumbers.AsYouTypeFormatter;
  4. import com.google.i18n.phonenumbers.NumberParseException;
  5. import com.google.i18n.phonenumbers.PhoneNumberUtil;
  6. import com.google.i18n.phonenumbers.Phonenumber;
  7. import com.vaadin.data.validator.RegexpValidator;
  8. import com.vaadin.event.MouseEvents;
  9. import com.vaadin.event.ShortcutAction;
  10. import com.vaadin.navigator.View;
  11. import com.vaadin.navigator.ViewChangeListener;
  12. import com.vaadin.server.Page;
  13. import com.vaadin.spring.annotation.SpringView;
  14. import com.vaadin.ui.*;
  15. import org.apache.commons.lang3.StringUtils;
  16. import org.apache.commons.lang3.exception.ExceptionUtils;
  17. import org.apache.log4j.Logger;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.context.MessageSource;
  20. import org.springframework.core.env.Environment;
  21. import ru.pochta.abon.container.Container;
  22. import ru.pochta.abon.ldap.AuthorizationException;
  23. import ru.pochta.abon.ldap.LdapUser;
  24. import ru.pochta.abon.ldap.LdapUserAuthorizationService;
  25. import ru.pochta.abon.ldap.LdapUserRepo;
  26. import ru.pochta.abon.library.dto.abonClient.dto.EmployeeRole;
  27. import ru.pochta.abon.library.dto.abonClient.dto.EmployeeWrapper;
  28. import ru.pochta.abon.library.dto.abonClient.enumeration.EmployeeRoleEnum;
  29. import ru.pochta.abon.library.service.abonClient.ServiceManager;
  30. import ru.pochta.abon.service.AuthenticationService;
  31. import ru.pochta.abon.ui.notification.AbonNotification;
  32. import ru.pochta.abon.util.VariousUtils;
  33.  
  34. import javax.annotation.PostConstruct;
  35. import java.time.ZoneId;
  36. import java.util.Locale;
  37. import java.util.Objects;
  38. import java.util.regex.Matcher;
  39. import java.util.regex.Pattern;
  40.  
  41. @SpringView(name = LoginView.VIEW_NAME)
  42. public class LoginView extends VerticalLayout implements View {
  43.  
  44.     public static final String VIEW_NAME = "login";
  45.     private static final Logger LOG = Logger.getLogger(LoginView.class);
  46.  
  47.     @Autowired
  48.     private Environment environment;
  49.  
  50.     @Autowired
  51.     private AuthenticationService authenticationService;
  52.  
  53.     @Autowired
  54.     private LdapUserRepo ldapUserRepo;
  55.  
  56.     @Autowired
  57.     private LdapUserAuthorizationService ldapUserAuthorizationService;
  58.  
  59.     @Autowired
  60.     private ServiceManager serviceManager;
  61.  
  62.     @Autowired
  63.     private Container container;
  64.  
  65.     @Autowired
  66.     private MessageSource messageSource;
  67.  
  68.     private Label singInLabel;
  69.     private TextField loginTextField;
  70.     private PasswordField passwordTextField;
  71.     private Button forgotLink;
  72.     private Button singInButton;
  73.  
  74.     private String enableOwnAuthentication;
  75.  
  76.     @PostConstruct
  77.     void init() {
  78.         //in case ldap is not working or you want to login as operator set 'login.enableOwnAuthentication' = 'true'
  79.         enableOwnAuthentication = environment.getProperty("login.enableOwnAuthentication");
  80.     }
  81.  
  82.     @Override
  83.     public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
  84.         setSizeFull();
  85.         setSpacing(true);
  86.         initComponents();
  87.         setTexts();
  88.     }
  89.  
  90.     private void initComponents() {
  91.         VerticalLayout loginLayout = new VerticalLayout();
  92.         loginLayout.setSpacing(true);
  93.         loginLayout.setWidthUndefined();
  94.         addComponent(loginLayout);
  95.         setComponentAlignment(loginLayout, Alignment.MIDDLE_CENTER);
  96.  
  97.         singInLabel = new Label();
  98.         singInLabel.setStyleName("h2");
  99.         loginTextField = new TextField();
  100.         passwordTextField = new PasswordField();
  101.  
  102.         HorizontalLayout actionBlock = new HorizontalLayout();
  103.         actionBlock.setSpacing(true);
  104.         actionBlock.setWidth(100, Unit.PERCENTAGE);
  105.         forgotLink = new Button();
  106.         forgotLink.setStyleName("link");
  107.         this.forgotLink.addClickListener(clickEvent -> {
  108.             Notification.show(messageSource.getMessage("login.forgotNotification", null, getLocale()));
  109.         });
  110.         singInButton = new Button();
  111.         singInButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
  112.         singInButton.setStyleName("primary");
  113.         actionBlock.addComponents(forgotLink, singInButton);
  114.         actionBlock.setComponentAlignment(forgotLink, Alignment.MIDDLE_LEFT);
  115.         actionBlock.setComponentAlignment(singInButton, Alignment.MIDDLE_RIGHT);
  116.  
  117.         this.singInButton.addClickListener(clickEvent -> {
  118.             if (StringUtils.isNotBlank(loginTextField.getValue()) &&
  119.                     (StringUtils.isNotBlank(passwordTextField.getValue()) || enableOwnAuthentication.equalsIgnoreCase("true"))) {
  120.                 if (authenticateLdap(loginTextField.getValue(), passwordTextField.getValue())) {
  121.                     EmployeeWrapper employeeWrapper = authorizeOwn(loginTextField.getValue());
  122.                     if (Objects.nonNull(employeeWrapper)) {
  123.                         ZoneId officesZoneId = VariousUtils.getZoneIdForPostOffice(employeeWrapper.getPostOffice(), serviceManager);
  124.                         if (officesZoneId != null) {
  125.                             container.setOfficesZoneId(officesZoneId);
  126.                             LOG.debug("Saved office's time zone is " + officesZoneId.toString());
  127.                         }
  128.                         container.setEmployeeWrapper(employeeWrapper);
  129.                         setUpAuthorizationFlags(employeeWrapper);
  130.                     } else {
  131.                         LOG.error("Failed to authorize user via ldap: " + loginTextField.getValue());
  132.                         showFailedAuthorizationNotification();
  133.                     }
  134.                 } else if (enableOwnAuthentication.equalsIgnoreCase("true") && authenticateOwn(loginTextField.getValue(), passwordTextField.getValue())) {
  135.                     EmployeeWrapper employeeWrapper = authorizeOwn(loginTextField.getValue());
  136.                     if (Objects.nonNull(employeeWrapper)) {
  137.                         ZoneId officesZoneId = VariousUtils.getZoneIdForPostOffice(employeeWrapper.getPostOffice(), serviceManager);
  138.                         if (officesZoneId != null) {
  139.                             container.setOfficesZoneId(officesZoneId);
  140.                             LOG.debug("Saved office's time zone is " + officesZoneId.toString());
  141.                         }
  142.                         container.setEmployeeWrapper(employeeWrapper);
  143.                         setUpAuthorizationFlags(employeeWrapper);
  144.                     } else {
  145.                         LOG.error("Failed to authorize user via own system: " + loginTextField.getValue());
  146.                         showFailedAuthorizationNotification();
  147.                     }
  148.                 } else {
  149.                     showFailedAuthenticationNotification();
  150.                 }
  151.             } else {
  152.                 showFailedAuthenticationNotification();
  153.             }
  154.         });
  155.  
  156.         loginLayout.addComponents(singInLabel, loginTextField, passwordTextField, actionBlock);
  157.     }
  158.  
  159.     private void setTexts() {
  160.         Locale locale = getLocale();
  161.         singInLabel.setValue(messageSource.getMessage("login.singInLabel", null, locale));
  162.         loginTextField.setCaption(messageSource.getMessage("login.login", null, locale));
  163.         loginTextField.setValue("Ext-N.Ovcharenko");
  164.         passwordTextField.setCaption(messageSource.getMessage("login.password", null, locale));
  165.         forgotLink.setCaption(messageSource.getMessage("login.forgot", null, locale));
  166.         singInButton.setCaption(messageSource.getMessage("login.singIn", null, locale));
  167.  
  168.  
  169.         TextField phoneNumberField = new TextField("phone number");
  170.         String patternPhoneExtended = "^\\+7 \\d{3} \\d{3}-\\d{2}-\\d{2}$";
  171.         Pattern patternPhoneSimple = Pattern.compile("^(8|\\+?7)\\d{10}$");
  172.         phoneNumberField.addValidator(new RegexpValidator(patternPhoneExtended, messageSource.getMessage("fieldPhoneFormat", null, locale)));
  173.         phoneNumberField.addTextChangeListener(textChangeEvent -> {
  174.             String eventString = textChangeEvent.getText();
  175.             String val = phoneNumberField.getValue();
  176.             System.out.println("txt val/event: " + val + " / " + eventString);
  177.  
  178.             phoneNumberField.setValue(eventString.replaceAll("[\\+ ()-]", ""));
  179.  
  180.             int delta = countCursorOffset(eventString, phoneNumberField.getCursorPosition());
  181.  
  182.             System.out.print("cursor: " + phoneNumberField.getCursorPosition() + " -> ");
  183.             phoneNumberField.setCursorPosition(phoneNumberField.getCursorPosition() + delta);
  184.             System.out.println(phoneNumberField.getCursorPosition());
  185.         });
  186.         phoneNumberField.addValueChangeListener(valueChangeEvent -> {
  187.             String val = phoneNumberField.getValue();
  188.             Matcher m = patternPhoneSimple.matcher(val);
  189.             if (m.matches()) {
  190.                 PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
  191.                 try {
  192.                     Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(val, "RU");
  193.                     String formattedPhone = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
  194.                     phoneNumberField.setValue(formattedPhone);
  195.                 } catch (NumberParseException e) {
  196.                     LOG.error(ExceptionUtils.getStackTrace(e));
  197.                 }
  198.             }
  199.         });
  200.         addComponent(phoneNumberField);
  201.     }
  202.  
  203.     private int countCursorOffset(String number, int currPos) {
  204.         String formattedPrefix, originalPrefix, formatted, original;
  205.         int len;
  206.         if (number.contains(" ")) {
  207.             //then it's already formatted. if we got here then we need to count cursor offset to the left
  208.  
  209.             formattedPrefix = number.substring(0, currPos);
  210.             //System.out.println("prefix: " + formattedPrefix);
  211.  
  212.             originalPrefix = formattedPrefix.replaceAll("[\\+ ()-]", "");
  213.             //System.out.println("short : " + formattedShort);
  214.  
  215.             len = formattedPrefix.length() - originalPrefix.length();
  216.             System.out.println("delta   : " + len);
  217.  
  218.         } else {
  219.             //else convert original to formatted. and add (formatted - origin) prefix to cursor offset
  220.             len = 1;
  221.         }
  222.  
  223.         return len;
  224.     }
  225.  
  226.     private String formatPhoneNumber(String number) {
  227.  
  228.         String prefix = "(\\+?[78])";
  229.         String code = "(\\d{3})";
  230.         String number1 = "(\\d{3})";
  231.         String number2 = "(\\d{2})";
  232.         String extra = "\\d";
  233.  
  234.  
  235.         Pattern p = Pattern.compile(
  236.                 "(^" + prefix + ")?(" + code + ")?(" + number1 + ")?(" + number2 + ")?(" + number2 + ")?(" + extra + ")*");
  237.  
  238.         System.out.println("in : " + number);
  239.         number = number.replaceAll("[\\+ ()-]", "");
  240.         System.out.println("out: " + number);
  241.         Matcher m = p.matcher(number);
  242.  
  243.         StringBuilder sb = new StringBuilder();
  244.         try {
  245.             if (m.find()) {
  246.                 if (null != m.group(2)) sb.append("+7 ");
  247.                 if (null != m.group(4)) sb.append("(" + m.group(4) + ") ");
  248.                 if (null != m.group(6)) sb.append(m.group(6) + "-");
  249.                 if (null != m.group(8)) sb.append(m.group(8) + "-");
  250.                 if (null != m.group(10)) sb.append(m.group(10));
  251.                 if (null != m.group(11)) sb.append(m.group(11));
  252.  
  253.                 return sb.toString();
  254.             }
  255.         } catch (Exception e) {}
  256.  
  257.         return "+" + number;
  258.     }
  259.  
  260.     private boolean authenticateLdap(String login, String password) {
  261.         boolean authenticated;
  262.         try {
  263.             authenticated = ldapUserRepo.authenticate(login, password);
  264.         } catch (Exception e) {
  265.             authenticated = false;
  266.             LOG.error("LDAP authentication failed!");
  267.             LOG.error(ExceptionUtils.getStackTrace(e));
  268.         }
  269.         return authenticated;
  270.     }
  271.  
  272.     private EmployeeWrapper authorizeLdap(String login) throws AuthorizationException {
  273.         LdapUser ldapUser = ldapUserRepo.findByLogin(login);
  274.         return ldapUserAuthorizationService.authorize(ldapUser);
  275.     }
  276.  
  277.     private boolean authenticateOwn(String login, String password) {
  278.         return authenticationService.authenticate(login, password);
  279.     }
  280.  
  281.     private EmployeeWrapper authorizeOwn(String login) {
  282.         return authenticationService.authorize(login);
  283.     }
  284.  
  285.     private void setUpAuthorizationFlags(EmployeeWrapper employeeWrapper) {
  286.         EmployeeRole role = employeeWrapper.getEmployeeRole();
  287.         if (Objects.nonNull(role)) {
  288.             if (role.isAdmin()) {
  289.                 container.setAdmin(true);
  290.                 container.setCoul(false);
  291.                 if (role.isAdminPostamtAndUFPS()) {
  292.                     container.setAdminPostamtAndUFPS(true);
  293.                 } else {
  294.                     container.setAdminPostamtAndUFPS(false);
  295.                 }
  296.                 getUI().getNavigator().navigateTo(AdminHomeView.VIEW_NAME);
  297.             } else if (role.getEntityId().equals(EmployeeRoleEnum.OPERATOR_COUL.getId())) {
  298.                 container.setCoul(true);
  299.                 container.setAdmin(false);
  300.                 container.setAdminPostamtAndUFPS(false);
  301.                 getUI().getNavigator().navigateTo(PostOfficeCardView.VIEW_NAME);
  302.             } else if (role.getEntityId().equals(EmployeeRoleEnum.OPERATOR.getId())) {
  303.                 // operators must use plugin for EAS, authorization of Operators occurs in AbonUI.class
  304.                 if (enableOwnAuthentication.equalsIgnoreCase("true")) {
  305.                     container.setAdmin(false);
  306.                     container.setCoul(false);
  307.                     container.setAdminPostamtAndUFPS(false);
  308.                     container.setLoggedViaEASOPS(true);
  309.                     getUI().getNavigator().navigateTo(PostOfficeCardView.VIEW_NAME);
  310.                 } else {
  311.                     showFailedAuthorizationNotification();
  312.                 }
  313.             }
  314.         } else {
  315.             showFailedAuthorizationNotification();
  316.         }
  317.     }
  318.  
  319.     private void showFailedAuthenticationNotification() {
  320.         Notification notification = AbonNotification.getAbonErrorNotification(
  321.                 messageSource.getMessage("login.failed.caption", null, getLocale()),
  322.                 messageSource.getMessage("login.authentication.failedNotification", null, getLocale()));
  323.         notification.show(Page.getCurrent());
  324.     }
  325.  
  326.     private void showFailedAuthorizationNotification() {
  327.         Notification notification = AbonNotification.getAbonErrorNotification(
  328.                 messageSource.getMessage("login.failed.caption", null, getLocale()),
  329.                 messageSource.getMessage("login.authorization.failedNotification", null, getLocale()));
  330.         notification.show(Page.getCurrent());
  331.     }
  332. }
Advertisement
Add Comment
Please, Sign In to add comment