Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package custom.bgbilling.modules.inet.dyn.device.sim;
- import custom.bgbilling.modules.inet.dyn.device.sim.interfaces.SimLockService;
- import custom.bgbilling.modules.inet.dyn.device.sim.megafon.MegafonApiService;
- import custom.bgbilling.modules.inet.dyn.device.sim.mts.MtsApiService;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- import org.apache.log4j.Logger;
- import org.json.JSONObject;
- import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivatorEvent;
- import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDevice;
- import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDeviceType;
- import ru.bitel.bgbilling.modules.inet.api.common.bean.InetServ;
- import ru.bitel.bgbilling.modules.inet.dyn.device.mikrotik.MikrotikServiceActivator;
- import ru.bitel.bgbilling.modules.inet.dyn.device.terminal.SSHServiceActivator;
- import ru.bitel.bgbilling.server.util.Setup;
- import ru.bitel.common.ParameterMap;
- import ru.bitel.bgbilling.kernel.contract.api.common.bean.Contract;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.stream.Collectors;
- /**
- * Блокировка/разблокировка сим при изменении статуса аккаунта
- *
- * @author
- */
- public class DynSimServiceActivator extends SSHServiceActivator {
- private static final String TAG = "DynSimServiceActivator";
- private static final Logger logger = Logger.getLogger(DynSimServiceActivator.class);
- private static JSONObject requestNumberOperator(String number) throws Exception {
- String body = "";
- try (CloseableHttpClient client = HttpClients.createDefault()) {
- HttpGet httpGet = new HttpGet("http://www.megafon.ru/api/mfn/info?msisdn=" + number);
- CloseableHttpResponse response;
- response = client.execute(httpGet);
- if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
- throw new Exception("Failed : HTTP error code : "
- + response.getStatusLine().getStatusCode());
- }
- HttpEntity entity = response.getEntity();
- try (BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
- body = buffer.lines().collect(Collectors.joining("\n"));
- }
- EntityUtils.consume(entity);
- return new JSONObject(body);
- } catch (Exception e) {
- logger.error(TAG + " -> requestNumberOperator Exception: " + e.getMessage() + "\n]\tResponse: " + body);
- throw e;
- }
- }
- @Override
- public Object init(Setup setup, int moduleId, InetDevice device, InetDeviceType deviceType, ParameterMap config)
- throws Exception {
- logger.info(TAG + " -> init");
- return super.init( setup, moduleId, device, deviceType, config );
- }
- /**
- * Создание сервиса (по событию добавления или началу периода действия)
- *
- * @param e
- * @return Object
- * @throws Exception
- */
- @Override
- public Object serviceCreate(ServiceActivatorEvent e) throws Exception {
- logger.info(TAG + " -> serviceCreate");
- Object suObj = super.serviceCreate(e);
- // отключение
- if (e.getNewState() == InetServ.STATE_DISABLE) {
- logger.info(TAG + " -> serviceCreate: InetServ.STATE_DISABLE");
- simDisable(e);
- } else {
- logger.info(TAG + " -> serviceCreate: InetServ.STATE_ENABLED");
- }
- return suObj;
- }
- /**
- * Изменение сервиса (подключение/отключение/изменение скорости).
- * Вызывается при изменении набора опций или изменении состояния сервиса
- *
- * @param e
- * @return
- * @throws Exception
- * @see ServiceActivatorEvent
- * @see {@link ServiceActivatorEvent#getNewState()}
- */
- @Override
- public Object serviceModify(ServiceActivatorEvent e) throws Exception {
- logger.info(TAG + " -> serviceModify");
- Object suObj = super.serviceModify(e);
- // отключение
- if (e.getNewState() == InetServ.STATE_DISABLE) {
- return simDisable(e);
- }
- // включение
- else if (e.getOldState() == InetServ.STATE_DISABLE) {
- return simEnable(e);
- }
- return suObj;
- }
- /**
- * Удаление сервиса (по событию удаления или окончания периода действия).
- *
- * @param e
- * @return
- * @throws Exception
- */
- @Override
- public Object serviceCancel(ServiceActivatorEvent e) throws Exception {
- logger.info(TAG + " -> serviceCancel");
- Object suObj = super.serviceCancel(e);
- // do not disable sim here, do it on enable only
- // simDisable(e);
- return suObj;
- }
- protected Object simEnable(ServiceActivatorEvent e) throws Exception {
- final InetServ inetServ = e.getInetServRuntime().getInetServ();
- logger.info(TAG + " -> simEnable -> login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
- String provider = inetServ.getContractComment();
- String number = inetServ.getLogin();
- int contractId = inetServ.getContractId();
- try {
- SimLockService service = CreateSimLockService(provider, number, contractId);
- boolean res = service.SIMUnlock(number);
- logger.info(TAG + " -> simEnable Number: " + number + (res ? " UNLOCKED" : " ERROR: CAN'T UNLOCK"));
- } catch (Exception ex) {
- logger.info(TAG + " -> simEnable Exception: " + ex.getMessage());
- throw ex;
- }
- return null;
- }
- protected Object simDisable(ServiceActivatorEvent e) throws Exception {
- final InetServ inetServ = e.getInetServRuntime().getInetServ();
- logger.info(TAG + " -> simDisable -> login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
- String provider = inetServ.getContractComment();
- String number = inetServ.getLogin();
- int contractId = inetServ.getContractId();
- int errorCounter = 0;
- try {
- SimLockService service = CreateSimLockService(provider, number, contractId);
- boolean res = service.SIMLock(number);
- logger.info(TAG + " -> simDisable Number: " + number + (res ? " LOCKED" : " ERROR: CAN'T LOCK"));
- } catch (Exception ex) {
- if (errorCounter++ >= 1) {
- logger.info(TAG + " -> simDisable Exception: " + ex.getMessage());
- throw ex;
- }
- else {
- logger.info(TAG + " -> simDisable Exception: " + ex.getMessage());
- }
- }
- return null;
- }
- // private void logUserContract(final ServiceActivatorEvent e) {
- // final InetServ inetServ = e.getInetServRuntime().getInetServ();
- // logger.info(TAG + " -> logUserContract: login: " + inetServ.getLogin() + " contractId: " + inetServ.getContractId());
- // }
- /**
- * Обработка старта соединения.
- *
- * @param e
- * @return
- * @throws Exception
- */
- @Override
- public Object onAccountingStart(final ServiceActivatorEvent e)
- throws Exception {
- // logger.info(TAG + " -> onAccountingStart");
- // logUserContract(e);
- return super.onAccountingStart(e);
- }
- /**
- * Обработка стопа соединения.
- *
- * @param e
- * @return
- * @throws Exception
- */
- @Override
- public Object onAccountingStop(final ServiceActivatorEvent e)
- throws Exception {
- // logger.info(TAG + " -> onAccountingStop");
- // logUserContract(e);
- return super.onAccountingStop(e);
- }
- private SimLockService CreateSimLockService(String provider, String number, int contractId) throws Exception {
- try {
- if (number == null || number.isEmpty()) throw new Exception("Inet login(phone number) is empty!");
- if (provider == null || provider.isEmpty()) {
- JSONObject res = requestNumberOperator(number);
- provider = res.getString("operator").toLowerCase();
- }
- logger.info(TAG + " -> CreateSimLockService current operator: " + provider);
- String megafonLogin = config.get("sim.megafon.login", "");
- String megafonPassword = config.get("sim.megafon.password", "");
- String mtsCredentials = config.get("sim.mts.credentials_path", "");
- if (megafonLogin.isEmpty()) throw new Exception("sim.megafon.login is not set in the config");
- if (megafonPassword.isEmpty()) throw new Exception("sim.megafon.password is not set in the config");
- if (mtsCredentials.isEmpty()) throw new Exception("sim.mts.credentials_path is not set in the config");
- switch (provider) {
- case "mts":
- case "мтс":
- return new MtsApiService(mtsCredentials);
- case "megafon":
- case "мегафон":
- return new MegafonApiService(megafonLogin, megafonPassword);
- default:
- throw new Exception(TAG + " -> CreateSimLockService there is no service for operator: " + provider + " number " + number + " contractId " + contractId);
- }
- }
- catch (Exception ex) {
- throw new Exception(TAG + " -> CreateSimLockService there is no service for operator: " + provider + " number " + number + " contractId " + contractId);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement