Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.06 KB | None | 0 0
  1. package custom.bgbilling.modules.inet.dyn.device.sim;
  2.  
  3. import custom.bgbilling.modules.inet.dyn.device.sim.interfaces.SimLockService;
  4. import custom.bgbilling.modules.inet.dyn.device.sim.megafon.MegafonApiService;
  5. import custom.bgbilling.modules.inet.dyn.device.sim.mts.MtsApiService;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpStatus;
  8. import org.apache.http.client.methods.CloseableHttpResponse;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.util.EntityUtils;
  13. import org.apache.log4j.Logger;
  14. import org.json.JSONObject;
  15. import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivatorEvent;
  16. import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDevice;
  17. import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDeviceType;
  18. import ru.bitel.bgbilling.modules.inet.api.common.bean.InetServ;
  19. import ru.bitel.bgbilling.modules.inet.dyn.device.mikrotik.MikrotikServiceActivator;
  20. import ru.bitel.bgbilling.modules.inet.dyn.device.terminal.SSHServiceActivator;
  21. import ru.bitel.bgbilling.server.util.Setup;
  22. import ru.bitel.common.ParameterMap;
  23. import ru.bitel.bgbilling.kernel.contract.api.common.bean.Contract;
  24.  
  25. import java.io.BufferedReader;
  26. import java.io.InputStreamReader;
  27. import java.util.stream.Collectors;
  28.  
  29. /**
  30.  * Блокировка/разблокировка сим при изменении статуса аккаунта
  31.  *
  32.  * @author
  33.  */
  34. public class DynSimServiceActivator extends SSHServiceActivator {
  35.     private static final String TAG = "DynSimServiceActivator";
  36.     private static final Logger logger = Logger.getLogger(DynSimServiceActivator.class);
  37.  
  38.     private static JSONObject requestNumberOperator(String number) throws Exception {
  39.         String body = "";
  40.         try (CloseableHttpClient client = HttpClients.createDefault()) {
  41.             HttpGet httpGet = new HttpGet("http://www.megafon.ru/api/mfn/info?msisdn=" + number);
  42.             CloseableHttpResponse response;
  43.  
  44.             response = client.execute(httpGet);
  45.             if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
  46.                 throw new Exception("Failed : HTTP error code : "
  47.                         + response.getStatusLine().getStatusCode());
  48.             }
  49.  
  50.             HttpEntity entity = response.getEntity();
  51.             try (BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
  52.                 body = buffer.lines().collect(Collectors.joining("\n"));
  53.             }
  54.             EntityUtils.consume(entity);
  55.  
  56.             return new JSONObject(body);
  57.         } catch (Exception e) {
  58.             logger.error(TAG + " -> requestNumberOperator Exception: " + e.getMessage() + "\n]\tResponse: " + body);
  59.             throw e;
  60.         }
  61.     }
  62.  
  63.     @Override
  64.     public Object init(Setup setup, int moduleId, InetDevice device, InetDeviceType deviceType, ParameterMap config)
  65.             throws Exception {
  66.         logger.info(TAG + " -> init");
  67.  
  68.         return super.init( setup, moduleId, device, deviceType, config );
  69.     }
  70.  
  71.     /**
  72.      * Создание сервиса (по событию добавления или началу периода действия)
  73.      *
  74.      * @param e
  75.      * @return Object
  76.      * @throws Exception
  77.      */
  78.     @Override
  79.     public Object serviceCreate(ServiceActivatorEvent e) throws Exception {
  80.         logger.info(TAG + " -> serviceCreate");
  81.         Object suObj = super.serviceCreate(e);
  82.  
  83.         // отключение
  84.         if (e.getNewState() == InetServ.STATE_DISABLE) {
  85.             logger.info(TAG + " -> serviceCreate: InetServ.STATE_DISABLE");
  86.             simDisable(e);
  87.         } else {
  88.             logger.info(TAG + " -> serviceCreate: InetServ.STATE_ENABLED");
  89.         }
  90.  
  91.         return suObj;
  92.     }
  93.  
  94.     /**
  95.      * Изменение сервиса (подключение/отключение/изменение скорости).
  96.      * Вызывается при изменении набора опций или изменении состояния сервиса
  97.      *
  98.      * @param e
  99.      * @return
  100.      * @throws Exception
  101.      * @see ServiceActivatorEvent
  102.      * @see {@link ServiceActivatorEvent#getNewState()}
  103.      */
  104.     @Override
  105.     public Object serviceModify(ServiceActivatorEvent e) throws Exception {
  106.         logger.info(TAG + " -> serviceModify");
  107.         Object suObj = super.serviceModify(e);
  108.  
  109.         // отключение
  110.         if (e.getNewState() == InetServ.STATE_DISABLE) {
  111.             return simDisable(e);
  112.         }
  113.         // включение
  114.         else if (e.getOldState() == InetServ.STATE_DISABLE) {
  115.             return simEnable(e);
  116.         }
  117.  
  118.         return suObj;
  119.     }
  120.  
  121.     /**
  122.      * Удаление сервиса (по событию удаления или окончания периода действия).
  123.      *
  124.      * @param e
  125.      * @return
  126.      * @throws Exception
  127.      */
  128.     @Override
  129.     public Object serviceCancel(ServiceActivatorEvent e) throws Exception {
  130.         logger.info(TAG + " -> serviceCancel");
  131.         Object suObj = super.serviceCancel(e);
  132.  
  133.         // do not disable sim here, do it on enable only
  134.         // simDisable(e);
  135.  
  136.         return suObj;
  137.     }
  138.  
  139.     protected Object simEnable(ServiceActivatorEvent e) throws Exception {
  140.         final InetServ inetServ = e.getInetServRuntime().getInetServ();
  141.         logger.info(TAG + " -> simEnable -> login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
  142.  
  143.         String provider = inetServ.getContractComment();
  144.         String number = inetServ.getLogin();
  145.         int contractId = inetServ.getContractId();
  146.  
  147.         try {
  148.             SimLockService service = CreateSimLockService(provider, number, contractId);
  149.             boolean res = service.SIMUnlock(number);
  150.             logger.info(TAG + " -> simEnable Number: " + number + (res ? " UNLOCKED" : " ERROR: CAN'T UNLOCK"));
  151.         } catch (Exception ex) {
  152.             logger.info(TAG + " -> simEnable Exception: " + ex.getMessage());
  153.             throw ex;
  154.         }
  155.  
  156.         return null;
  157.     }
  158.  
  159.     protected Object simDisable(ServiceActivatorEvent e) throws Exception {
  160.         final InetServ inetServ = e.getInetServRuntime().getInetServ();
  161.  
  162.         logger.info(TAG + " -> simDisable -> login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
  163.  
  164.         String provider = inetServ.getContractComment();
  165.         String number = inetServ.getLogin();
  166.         int contractId = inetServ.getContractId();
  167.         int errorCounter = 0;
  168.         try {
  169.  
  170.             SimLockService service = CreateSimLockService(provider, number, contractId);
  171.             boolean res = service.SIMLock(number);
  172.             logger.info(TAG + " -> simDisable Number: " + number + (res ? " LOCKED" : " ERROR: CAN'T LOCK"));
  173.         } catch (Exception ex) {
  174.             if (errorCounter++ >= 1) {
  175.                 logger.info(TAG + " -> simDisable Exception: " + ex.getMessage());
  176.                 throw ex;
  177.             }
  178.             else {
  179.                 logger.info(TAG + " -> simDisable Exception: " + ex.getMessage());
  180.                 }
  181.         }
  182.  
  183.         return null;
  184.     }
  185.  
  186. //    private void logUserContract(final ServiceActivatorEvent e) {
  187. //        final InetServ inetServ = e.getInetServRuntime().getInetServ();
  188. //        logger.info(TAG + " -> logUserContract: login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
  189. //    }
  190.  
  191.     /**
  192.      * Обработка старта соединения.
  193.      *
  194.      * @param e
  195.      * @return
  196.      * @throws Exception
  197.      */
  198.     @Override
  199.     public Object onAccountingStart(final ServiceActivatorEvent e)
  200.             throws Exception {
  201. //        logger.info(TAG + " -> onAccountingStart");
  202. //        logUserContract(e);
  203.  
  204.         return super.onAccountingStart(e);
  205.     }
  206.  
  207.     /**
  208.      * Обработка стопа соединения.
  209.      *
  210.      * @param e
  211.      * @return
  212.      * @throws Exception
  213.      */
  214.     @Override
  215.     public Object onAccountingStop(final ServiceActivatorEvent e)
  216.             throws Exception {
  217. //        logger.info(TAG + " -> onAccountingStop");
  218. //        logUserContract(e);
  219.  
  220.         return super.onAccountingStop(e);
  221.     }
  222.  
  223.     private SimLockService CreateSimLockService(String provider, String number, int contractId) throws Exception {
  224.         try {
  225.         if (number == null || number.isEmpty()) throw new Exception("Inet login(phone number) is empty!");
  226.  
  227.         if (provider == null || provider.isEmpty()) {
  228.             JSONObject res = requestNumberOperator(number);
  229.             provider = res.getString("operator").toLowerCase();
  230.         }
  231.  
  232.         logger.info(TAG + " -> CreateSimLockService current operator: " + provider);
  233.  
  234.         String megafonLogin = config.get("sim.megafon.login", "");
  235.         String megafonPassword = config.get("sim.megafon.password", "");
  236.         String mtsCredentials = config.get("sim.mts.credentials_path", "");
  237.         if (megafonLogin.isEmpty()) throw new Exception("sim.megafon.login is not set in the config");
  238.         if (megafonPassword.isEmpty()) throw new Exception("sim.megafon.password is not set in the config");
  239.         if (mtsCredentials.isEmpty()) throw new Exception("sim.mts.credentials_path is not set in the config");
  240.  
  241.         switch (provider) {
  242.             case "mts":
  243.             case "мтс":
  244.                 return new MtsApiService(mtsCredentials);
  245.             case "megafon":
  246.             case "мегафон":
  247.                 return new MegafonApiService(megafonLogin, megafonPassword);
  248.             default:
  249.  
  250.                     throw new Exception(TAG + " -> CreateSimLockService there is no service for operator: " + provider + " number " + number + " contractId " + contractId);
  251.                 }
  252.  
  253.         }
  254.         catch (Exception ex) {
  255.             throw new Exception(TAG + " -> CreateSimLockService there is no service for operator: " + provider + " number " + number + " contractId " + contractId);
  256.         }
  257.     }
  258. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement