Конвертер: at-8000 в сервисы INET

Материал из BiTel WiKi

Версия от 10:41, 20 декабря 2012; Stark (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Конвертер переносит данные из договоров в сервисы inet


Код конвертера:

package ru.maglan.bgbilling.script.global;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.apache.log4j.Logger;
 
import ru.bitel.bgbilling.common.BGException;
import ru.bitel.bgbilling.kernel.container.managed.ServerContext;
import ru.bitel.bgbilling.kernel.script.server.dev.GlobalScriptBase;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDevice;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetServ;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetServOption;
import ru.bitel.bgbilling.modules.inet.api.common.service.InetDeviceService;
import ru.bitel.bgbilling.modules.inet.api.common.service.InetServService;
import ru.bitel.bgbilling.server.util.ModuleSetup;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.sql.ConnectionSet;
import bitel.billing.common.TimeUtils;
import bitel.billing.common.module.ipn.IPNContractStatus;
import bitel.billing.server.contract.bean.ContractModuleManager;
import bitel.billing.server.ipn.bean.IPNContractStatusManager;
import bitel.billing.server.contract.bean.ContractScript;
import bitel.billing.server.contract.bean.ContractScriptManager;
 
 
public class ConvertIPNAT8000ToInetServices
	extends GlobalScriptBase
{
 
	//код модуля IPN
	private static int IPN_MODULE_ID = 1;
	private static int IPN_ROOT_DEVICE_ID = 4;
	private static int IPN_AT8000_GATE_TYPE_ID = 24;
	private static int IPN_UNUSED_FOLDER = 6;
 
 
	private static int INET_MODULE_ID = 18;
	private static int INET_SERV_TYPE_AT8000_ID = 2;
	private static int INET_AT8000_DEVICE_TYPE_ID = 3;
	private static int	INET_CONTRACT_STATUS_SCRIPT_ID = 7;
 
 
	private InetServService wsServ = null;
	private  InetDeviceService wsDevice = null;
 
	Logger logger = Logger.getLogger( ConvertIPNAT8000ToInetServices.class );
 
	@Override
	public void execute( Setup setup, ConnectionSet connectionSet )
		throws Exception
	{
		ServerContext context = ServerContext.get();
		wsServ = context.getService( InetServService.class, INET_MODULE_ID );
		wsDevice = context.getService( InetDeviceService.class, INET_MODULE_ID );
 
		Map<Integer, InetDevice> ipnInetDeviceMap = new HashMap<Integer, InetDevice>();
 
		getDevices( connectionSet, ipnInetDeviceMap );
 
		createServices( connectionSet, ipnInetDeviceMap );
 
		print( "OK" );
	}
 
 
	private void getDevices( ConnectionSet connectionSet, Map<Integer, InetDevice> ipnInetDeviceMap  )
       throws BGException, SQLException
   {
 
		List<InetDevice> inetDevicelist = new ArrayList<InetDevice>();
 
		inetDevicelist.addAll( wsDevice.deviceList( INET_AT8000_DEVICE_TYPE_ID ) );
 
 
		Map<String, InetDevice> inetDeviceMap = new HashMap<String, InetDevice>();
 
		for ( InetDevice device : inetDevicelist )
		{
			inetDeviceMap.put( device.getHost(), device );
		}
 
		Connection con = connectionSet.getConnection();
 
		logger.info( "loading devices...." );
 
		String tableName = "ipn_gate_" + IPN_MODULE_ID;
 
		String query =  " SELECT gate.* FROM " + tableName + " as gate " + 
						" LEFT JOIN " + tableName + " as parent ON parent.id=gate.parent_id"  +
						" LEFT JOIN " + tableName + " as parentParent ON parentParent.id=parent.parent_id"  +
			" WHERE parentParent.id = " + IPN_ROOT_DEVICE_ID + 
			" AND gate.type=" + IPN_AT8000_GATE_TYPE_ID;
 
 
		PreparedStatement ps = con.prepareStatement( query );
		ResultSet rs = ps.executeQuery();
 
		while ( rs.next() )
		{
			String host = rs.getString( "host" );
			int port = rs.getInt( "port" );
			int gid =  rs.getInt( "id" );
			String hostPort = host + ":" + port;
 
			InetDevice device = inetDeviceMap.get(  hostPort  );
 
			if ( device == null )
			{
				print( "device is NULL " + gid );
				continue;
			}
 
 
			ipnInetDeviceMap.put( gid, device );
			device.setId( device.getId() );
			device.setHost( hostPort );	
 
		}
		ps.close();
 
		logger.info( " devices loaded" );
   }
 
	private void createServices( ConnectionSet connectionSet,	                            
	                             Map<Integer, InetDevice> ipnInetDeviceMap ) 
		throws SQLException, BGException
    {
	    Connection con = connectionSet.getConnection();
 
		//обязательно чтобы мы с этого места могли делать rollback если что
		connectionSet.commit();
 
		logger.info( "creating services..." );	
 
		String query = "SELECT * FROM contract  " +
						" LEFT JOIN contract_module as cm  ON contract.id = cm.cid " +
						" WHERE cm.mid = " + IPN_MODULE_ID;
						//" LIMIT 0,10 ";
 
		PreparedStatement ps = con.prepareStatement( query );
		ResultSet rs = ps.executeQuery();
 
		ContractModuleManager cmm = new ContractModuleManager( con );
		ContractScriptManager contractScriptManager = new ContractScriptManager( con );	
 
 
		ModuleSetup ipnSetup = new ModuleSetup( con, IPN_MODULE_ID );
 
		IPNContractStatusManager statusManager = new IPNContractStatusManager( con , IPN_MODULE_ID, ipnSetup );
 
 
 
		Date now = new Date(); 
 
		int portIdx = 0 ;
 
		int idx = 0 ;
 
		Map<Integer,Map<Integer, InetServ>> servMap = new HashMap<Integer,Map<Integer, InetServ>>();
		Map<Integer,Map<Integer, InetServ>> servMapСopy = new HashMap<Integer,Map<Integer, InetServ>>();
 
 
		while ( rs.next() )
		{
			int cid = rs.getInt( "contract.id" );				
 
			int ipnStatus = statusManager.getContractStatus( cid );
 
			//print( "cid = " + cid );
 
			/*
			//удаленные договора игнорим 
			if( ipnStatus == IPNContractStatus.STATUS_REMOVED )
			{
				continue;
			}
 */
 
			int inetStatus = InetServ.STATUS_ACTIVE;
 
			switch ( ipnStatus )
			{
				case IPNContractStatus.STATUS_LOCK : 
				case IPNContractStatus.STATUS_OPEN : inetStatus = InetServ.STATUS_ACTIVE; break;
				case IPNContractStatus.STATUS_REMOVED:
				case IPNContractStatus.STATUS_CLOSED : inetStatus = InetServ.STATUS_CLOSED; break;
 
				case IPNContractStatus.STATUS_HARD_LOCK : inetStatus = InetServ.STATUS_LOCKED; break;						 
			}
 
			int count = 0;
 
			List<InetServ> list =  wsServ.inetServList( cid );
 
			//print( "list.size() = " + list.size() );
 
 			//
 
 
			for ( InetServ oldServ : list )
			{				
 
				if ( oldServ.getTypeId() ==  INET_SERV_TYPE_AT8000_ID )
				{
 
					/*
					//во такой вот костыль чтобы удалить сервис, иначе не дает
					logger.info( "delete serviceIdx =" + idx++ );
					connectionSet.commit();
					if ( oldServ.getDateTo() == null || TimeUtils.dateBefore(  now, oldServ.getDateTo() ) )
					{
						oldServ.setDateTo( TimeUtils.getPrevDay( now ) );
 
						try
	                    {
							//logger.info( "updating serv date for cid = " + cid );
							wsServ.inetServUpdate( oldServ, new ArrayList<InetServOption>(), false, false, 0  );							
 
	                    }
	                    catch( Exception e )
	                    {
	                    	//printError( cid, e, "Error while updating service date for contract "  + cid +  ";" + oldServ.getDeviceId()  + ";port=" + oldServ.getInterfaceId() + ":" + e.getMessage() );
	                    	//logger.error( "", e );	                    	
	                    }
					}
 
 
 
				    try
	                {
 
	                	wsServ.inetServDelete( oldServ.getId() );
						count ++;
					}
					catch( Exception e )
	                {
	                	printError( cid, e, "Error while deleting service date for contract " + cid +  ";" + oldServ.getDeviceId()  + ";port=" + oldServ.getInterfaceId() + ":" + e.getMessage()   );
	                   //logger.error( "", e );
	                   continue;	                    	
	                 }
					*/
 
					Map<Integer, InetServ> deviceMap = servMap.get( oldServ.getDeviceId() );
					Map<Integer, InetServ> deviceMapCopy = servMapСopy.get( oldServ.getDeviceId() );
 
					if ( deviceMap == null )
					{
						deviceMap = new HashMap<Integer, InetServ>();
						servMap.put( oldServ.getDeviceId(),  deviceMap );
						//еще один экземляр
						deviceMapCopy = new HashMap<Integer, InetServ>();
						servMapСopy.put( oldServ.getDeviceId(),  deviceMapCopy );	
					}
 
					if ( deviceMap.get( oldServ.getInterfaceId() ) != null )
					{
						print( "contract " + cid + " has already the port " + oldServ.getInterfaceId() );							
					}	
 
					deviceMap.put( oldServ.getInterfaceId(), oldServ );		
					deviceMapCopy.put( oldServ.getInterfaceId(), oldServ );		
 
					/*
 
					if ( oldServ.getDeviceId() == 212 && oldServ.getInterfaceId() == 3 )
					{
						print ( "ccccc cid=" + cid );
					}
					*/	
 
				}
 
 
 
 
			}
 
			//print( count + " services was deleted" );
 
			connectionSet.commit();
 
 
			query = "SELECT * FROM " + "ipn_gate_contract_port_" + IPN_MODULE_ID + " AS port " + 
			" LEFT JOIN ipn_gate_" + IPN_MODULE_ID + " AS gate ON gate.id = port.gid " + 
			" WHERE port.cid = " + cid +
			" AND gate.parent_id != " +  IPN_UNUSED_FOLDER;
			//" LIMIT 0, 10";
 
 
			PreparedStatement psPort = con.prepareStatement( query );
			ResultSet rsPort = psPort.executeQuery();
 
			boolean flag = false;
 
			//print( "cid before ports = " + cid );
 
 
			while ( rsPort.next() )
			{
				int gid = rsPort.getInt( "gid" );
				int port = rsPort.getInt( "port" );
 
				logger.info( "create port idx=" + portIdx++ );
 
				//в первый раз добавляем модуль и скрипт поведения
				if ( !flag )
				{
					try
		            {
			            Set<Integer> moduleSet = cmm.getContractModuleSet( cid );
 
			            if( !moduleSet.contains( INET_MODULE_ID ) )
			            {	            				
			            	cmm.addContractModule( cid, INET_MODULE_ID );
			            	//EventProcessor.getInstance().publishAfterCommit( new ContractModifiedEvent( User.USER_SERVER, cid ) );
			            }	            
 
						boolean found = false;
						List<ContractScript> contractScriptList = contractScriptManager.getContractScriptList( cid );
 
						for( ContractScript script : contractScriptList )
						{
							if ( script.getScriptId() == INET_CONTRACT_STATUS_SCRIPT_ID )
							{
								found = true;
								break;
							}	
						}
						if ( !found )
						{
							ContractScript  script = new ContractScript();
							script.setDate1( TimeUtils.convertDateToCalendar( now ) );
							script.setContractId( cid );
							script.setScriptId( INET_CONTRACT_STATUS_SCRIPT_ID );
							script.setComment( "Добавлен при импорте" );
 
 
							contractScriptManager.updateContractScript( "new", script );
						}
 
						connectionSet.commit();
 
		            }
		            catch( Exception e )
		            {
		            	print("error=" +  e.getMessage() );
		            	logger.error( "", e );
						connectionSet.rollback();
						continue;
		            }
		            flag = true;
				}
 
				InetDevice device = ipnInetDeviceMap.get( gid );;
 
				if ( device == null )
				{
					//print( "device is null for contract " + cid );
					logger.info( "Device for IPN id =" + gid + " is null for contract " + cid );
					print( "Device for IPN id =" + gid + " is null for contract " + cid );
					continue;
				}
 
				Map<Integer, InetServ> deviceMap = servMap.get( device.getId() );
 
				if ( deviceMap == null )
				{
					deviceMap = new HashMap<Integer, InetServ>();
					servMap.put( device.getId(), deviceMap );
				}
 
				Map<Integer, InetServ> deviceMapCopy = servMapСopy.get( device.getId() );
				if ( deviceMapCopy == null )
				{
					deviceMapCopy = new HashMap<Integer, InetServ>();
					servMapСopy.put( device.getId(), deviceMapCopy );
				}
 
 
				InetServ serv = deviceMap.get(port );
				boolean needUpdate = false;
 
				if ( serv == null ) 
				{
					print( "add  new service for cid " + cid + ";deviceId" + device.getId() + ";port " + port ); 
					serv = new InetServ();
					serv.setContractId( cid );
					serv.setComment( "Импортирован из IPN" );
					serv.setDateFrom( now );
					serv.setLogin( "" );
					serv.setPassword( "" );
					serv.setTypeId( INET_SERV_TYPE_AT8000_ID );
					needUpdate = true;
 
				}	
 
				if ( serv.getDateTo() != null )
				{
					print( "dateTo changed");
					serv.setDateTo( null );
					needUpdate = true;
				} 
 
				/*if ( device.getId() == 212 && deviceMapCopy.get( 3 ) != null )
				{
					print( "bbbbb deviceId = 212;port - 3; cid = " + cid );
				} 
 
				if ( device.getId() == 212 && port == 3 ) 
				{
					print( "aaaaa deviceId = 212;port - 3; cid = " + cid );
				}
 
				*/
 
				//удаляем чтобы потом найти те, которые не использовались
				deviceMapCopy.remove( port );
 
 
 
 
				if ( serv.getStatus() !=  inetStatus )
				{
					print( "status changed");
					serv.setStatus( inetStatus );
					needUpdate = true;	
				}
 
				if ( serv.getDeviceId() !=  device.getId() )
				{
					print( "device changed");
					serv.setDeviceId( device.getId() );
					needUpdate = true;
				}
 
				if( serv.getInterfaceId() != port )
				{
					print( "interface changed");
					serv.setInterfaceId( port );
					needUpdate = true;
				}
 
				try
			    {
 
 
			    	if ( needUpdate ) 
					{
			    		logger.info( "updating serv for cid = " + cid + ";deviceId" + device.getId()  + 
							";device host " + 	device.getHost() + 
							";port=" + port );
 
						wsServ.inetServUpdate( serv, new ArrayList<InetServOption>(), false, false, 0 );
					}
			    }
			    catch( Exception e )
			    {
			    	printError(  cid, e, "Error while updating  service  for contract " + cid +  ";deviceId" + device.getId()  + 
						";device host " + 	device.getHost() + 
						";port=" + port + ":" + e.getMessage() );
		 			//logger.error( "", e );
 
					connectionSet.rollback();
			    }
 
				connectionSet.commit();
 
			}
 
			psPort.close();
 
			;
 
		}
 
			//delete extra services
			int extraIdx = 0;	
			connectionSet.commit();
 
			for ( Map.Entry<Integer,Map<Integer, InetServ>> entry : servMapСopy.entrySet() )
			{
				Map<Integer, InetServ> deviceMapCopy = entry.getValue();
				for ( Map.Entry<Integer, InetServ> entry2 : deviceMapCopy.entrySet() )
				{
					InetServ serv = entry2.getValue();
					print ( "deleting serv " + serv.getId()  + ";serv.getDeviceId()=" + serv.getDeviceId() 
						+ ";port=" + serv.getInterfaceId()  + ";contract id =" + serv.getContractId() );
 
 
					//во такой вот костыль чтобы удалить сервис, иначе не дает
					logger.info( "delete extra service =" + extraIdx++ );
					connectionSet.commit();
					if ( serv.getDateTo() == null || TimeUtils.dateBefore(  now, serv.getDateTo() ) )
					{
						serv.setDateTo( TimeUtils.getPrevDay( now ) );
 
						try
	                    {
							//logger.info( "updating serv date for cid = " + cid );
							wsServ.inetServUpdate( serv, new ArrayList<InetServOption>(), false, false, 0  );							
 
	                    }
	                    catch( Exception e )
	                    {
	                    	printError( serv.getContractId(), e, "Error while updating extra service date for contract "  + serv.getContractId() +  ";" + serv.getDeviceId()  + ";port=" + serv.getInterfaceId() + ":" + e.getMessage() );
	                    	//logger.error( "", e );	                    	
	                    }
					}
 
 
 
				    try
	                {
 
	                	wsServ.inetServDelete( serv.getId() );
					}
					catch( Exception e )
	                {
	                	printError( serv.getContractId(), e, "Error while deleting extra  service date for contract " + serv.getContractId() +  ";" + serv.getDeviceId()  + ";port=" + serv.getInterfaceId() + ":" + e.getMessage()   );
	                   //logger.error( "", e );
						connectionSet.commit();
	                   continue;	                    	
	                 }
 
					connectionSet.commit();
 
				} 
			}
 
		ps.close();
 
    }
 
 
	private void printError( int cid, Exception e, String message )
    {
	    logger.error( message, e );
	    print( message );
    }
 
}
Личные инструменты