Универсальный конвертер переносящий шлюзы IPN в устройства INET

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

Перейти к: навигация, поиск

Глобальный скрипт( java-класс) переносящий шлюзы IPN в устройства Inet. Шлюзы в IPN расположены в дереве все на одном уровне(все имеют общего предка).

В конвертере задаются : код модуля IPN, код шлюза - родительской папки в IPN, код типа шлюза в IPN, код модуля Inet, код типа устройства в Inet, код устройства - родительской папки в модуле Inet. Все константы соответственно прокомментированы в коде. Конвертер исходит из того, что ip шлюза уникален . Если он находит еще один шлюз с таким ip, то он его игнорирует.

Данный конвертер дополнительно переносит опцию vlan из конфигурации шлюза IPN (если она есть) в конфигурацию устройства Inet. Это специфику можно не использовать, или вообще комментировать данный участок кода.


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

package ru.televox.bgbilling.modules.inet.dyn.script;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
 
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.InetDeviceType;
import ru.bitel.bgbilling.modules.inet.api.common.service.InetDeviceService;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.Preferences;
import ru.bitel.common.sql.ConnectionSet;
import ru.bitel.oss.systems.inventory.resource.common.DeviceInterfaceService;
import ru.bitel.oss.systems.inventory.resource.common.bean.Device;
 
 
public class MoveEdgeCoreDevicesFromIPN
	extends GlobalScriptBase
{
	//код модуля IPN
	private static int IPN_MODULE_ID = 6;	
        // код шлюза - родительской папки в IPN
	private static int IPN_ROOT_DEVICE_ID = 17;
 
	//тип шлюза  в IPN
	private static int IPN_GATE_TYPE_ID = 4;
 
	//код модуля Inet
	private static int INET_MODULE_ID = 21;
 
	//код типа устройства  в Inet
	private static int INET_DEVICE_TYPE_ID = 5;
 
	//код корня  дерева устройств в модуле Inet
	private static int INET_ROOT_DEVICE_ID = 7;
 
 
	private  InetDeviceService wsDevice = null;;
 
	Logger logger = Logger.getLogger( MoveEdgeCoreDevicesFromIPN.class );
 
	@Override
	public void execute( Setup setup, ConnectionSet connectionSet )
		throws Exception
	{
		print ( "connectionSet.getAutoCommit()=" + connectionSet.getAutoCommit() );
 
		ServerContext context = ServerContext.get();
		wsDevice = context.getService( InetDeviceService.class, INET_MODULE_ID );		
 
		createDevices( connectionSet );  
		connectionSet.commit();
 
 		print ( "Ok" );
	}
 
 
 
 
	private void createDevices( ConnectionSet connectionSet )
        throws BGException, SQLException
    {
		List<InetDevice> inetDevicelist = new ArrayList<InetDevice>();
 
		inetDevicelist.addAll( wsDevice.deviceList( INET_DEVICE_TYPE_ID ) );
 
		Map<String, InetDevice> inetDeviceMap = new HashMap<String, InetDevice>();
 
		for ( InetDevice device : inetDevicelist )
		{
			inetDeviceMap.put( device.getHost(), device );
		}
 
		Map<String, Integer> ipnGateMap = new HashMap<String, Integer>();
 
 
 
		Connection con = connectionSet.getConnection();
 
		String tableName = "ipn_gate_" + IPN_MODULE_ID;
 
		String query =  " SELECT gate.*, parent.id as parentId FROM " + tableName + " as gate " + 
						" LEFT JOIN " + tableName + " as parent ON parent.id=gate.parent_id"  +
			" WHERE parent.id = " + IPN_ROOT_DEVICE_ID + 
			" AND gate.type =" + IPN_GATE_TYPE_ID ;
 
		PreparedStatement ps = con.prepareStatement( query );
		ResultSet rs = ps.executeQuery();
 
 
 
		int count =0;
 
		while ( rs.next() )
		{
			int gid = rs.getInt( "id" );			
			String host = rs.getString( "host" );
 
			Integer oldGatedId = ipnGateMap.get( host );
			if ( oldGatedId == null )
			{
				ipnGateMap.put( host, gid );
			}	
			else if ( gid != oldGatedId )
			{
				print ( "error: double gate for host=" + host + ";ids=" + gid + "," + oldGatedId );
				continue;
			}
 
			int port = rs.getInt( "port" );
			String config = rs.getString( "config" );
			String keyword = rs.getString( "keyword" );
 
			Preferences oldProps = new Preferences( config, "\r\n"  );
			Preferences newProps = new  Preferences();
			newProps.set( "vlan", oldProps.get( "vlan", "" )  );			
 
			String hostPort = host + ":" + port;
 
 
 
 
 
 
			InetDevice device = inetDeviceMap.get(  hostPort  );
 
			if ( device == null )
			{
 				print( "add new device " + host );
				device = new InetDevice();
				inetDeviceMap.put( hostPort, device );				
			}
 			device.setHost( hostPort );
			device.setSecret( "" );
 
			int typeId = INET_DEVICE_TYPE_ID;
			device.setDeviceTypeId( typeId );	
 			device.setDeviceGroupIds( new HashSet<Integer>() );
 
 
 
 			device.setParentId( INET_ROOT_DEVICE_ID );
 
			device.setPassword( keyword );								
			device.setUsername( oldProps.get( "login", "" ) );
			device.setConfig( newProps.toString() );
			device.setIdentifier( "" );
			device.setComment( "Перенесено из IPN" );
			device.setDeviceGroupIds( new HashSet<Integer>() );
 
 
			InetDeviceType type = wsDevice.deviceTypeGet( typeId );
			device.setTitle( Device.generateTitle( device, type ) );
 
			//print( "device.getId()=" + device.getId() );
 
			int id = wsDevice.deviceUpdate( device );
			connectionSet.commit();
 
 
 
			if ( device.getId() <= 0 )
			{
				device.setId( id );
			}
 
			wsDevice.deviceUpdate( device );
			connectionSet.commit();
		}
		ps.close();
    }
	}
Личные инструменты