Код:
package ru.bitel.bgbilling.modules.inet.dyn.device.terminal;
import java.util.Set;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Date;
import org.apache.log4j.Logger;
import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivator;
import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivatorEvent;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetConnection;
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.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Utils;
import bitel.billing.common.TimeUtils;
import bitel.billing.server.util.telnet.TelnetSession;
/**
* {@inheritDoc}
* @see AbstractTerminalServiceActivator
*/
public class TestTelnetServiceActivator
extends AbstractTerminalServiceActivator
implements ServiceActivator
{
private static final Logger logger = Logger.getLogger( TelnetServiceActivator.class );
protected String endSequence;
protected TelnetSession session;
protected boolean lazyConnect;
@Override
public Object init( Setup setup, int moduleId, InetDevice device, InetDeviceType deviceType, ParameterMap config )
throws Exception
{
super.init( setup, moduleId, device, deviceType, config );
if( this.port <= 0 )
{
this.port = 23;
}
this.endSequence = config.get( "sa.endSequence", "#" );
this.lazyConnect = config.getInt( "sa.lazyConnect", 0 ) > 0;
return null;
}
@Override
public Object destroy()
throws Exception
{
return super.destroy();
}
@Override
public Object connect()
throws Exception
{
if( lazyConnect )
{
return null;
}
return connectImpl();
}
protected Object connectImpl()
throws Exception
{
TelnetSession session = new TelnetSession( host, port );
session.setTimeout( timeout );
session.setReadWait( readWait );
session.setEndString( ":" );
session.connect();
logger.info( "Connected" );
this.session = session;
logger.info( session.doCommand( username ) );
logger.info( "Login entered" );
if( Utils.notBlankString( endSequence ) )
{
session.setEndString( endSequence );
}
logger.info( session.doCommand( password ) );
logger.info( "Password entered" );
// logger.info( session.doCommand( "terminal length 0" ) );
// logger.info( session.doCommand( "terminal width 0" ) );
return super.connect();
}
protected TelnetSession getSession()
throws Exception
{
if( session != null )
{
return session;
}
connectImpl();
return session;
}
@Override
public Object disconnect()
throws Exception
{
if( session != null )
{
try
{
super.disconnect();
logger.info( "executeAsync: " + this.exitCommand );
session.doCommandAsync( this.exitCommand );
}
finally
{
session.disconnect();
session = null;
logger.debug( "Disconnected" );
}
}
return null;
}
@Override
protected void executeCommand( final String command )
throws Exception
{
final TelnetSession session = getSession();
logger.info( "execute: " + command );
logger.info( session.doCommand( command ) );
}
@Override
protected Object executeCommands( ServiceActivatorEvent e, InetServ serv, InetConnection connection, Set<Integer> options, String[] commands )
throws Exception
{
if ( e == null )
{
return super.executeCommands( e, serv, connection, options, commands );
}
if( commands == null )
{
return null;
}
if( this.workingOptions != null )
{
options = new HashSet<Integer>( options );
options.retainAll( this.workingOptions );
}
List<InetServ> childrens = serv.getChildren();
List<InetServ> servs = new ArrayList<>();
//если потомков у сервиса нет, то мы только его обрабатываем
// if( childrens.size() == 0 )
// {
servs.add( serv );
// }// если есть дети , то обратывваем только детей
// else
// {
servs.addAll( childrens );
// }
//logger.info( "servs=" + servs );
String fullCommand = generateRule( commands, serv, servs, e, connection, options );
//fullCommand = fullCommand.replaceAll( "\\\\t", "\t" );
//fullCommand = fullCommand.replaceAll( "\n", "|" );
fullCommand = fullCommand.replaceAll( "ifaceTitle", Matcher.quoteReplacement("$ifaceTitle"));
//logger.info( "fullCommand=" + fullCommand );
fullCommand = this.macrosFormat.format( fullCommand, e, serv, connection, options );
//logger.info( "fullCommand=" + fullCommand );
if( Utils.notBlankString( fullCommand ) )
{
executeCommand( fullCommand.trim() );
}
return null;
}
public final String generateRule( String[] commands, InetServ mainServ, List<InetServ> servs, ServiceActivatorEvent e, InetConnection connection, Set<Integer> options )
{
String commandStr = "";
for( String command : commands )
{
commandStr += command + "\n";
//logger.info( "commandStr =" + commandStr);
}
//Если указан макрос multiParam, учитываем его
//commandStr = getParamMulti( commandStr );
StringBuffer resultBuf = null;
resultBuf = new StringBuffer ();
String loopPattern = "(<LOOP>.*?</LOOP>)?(.*?)<LOOP>(.*?)</LOOP>";
Pattern pattern = Pattern.compile( loopPattern, Pattern.DOTALL );
Matcher m = pattern.matcher( commandStr );
boolean find = false;
while( m.find() )
{
find = true;
String block = m.group( 3 ).trim();
//logger.info( "block =" + block + "qqq");
block = processBlock( block, servs, e, connection, options ).toString();
//logger.info( "block1 =" + block + "qqq");
String beforeLoop = m.group( 2 );
beforeLoop = this.macrosFormat.format( beforeLoop, e, mainServ, connection, options );
resultBuf.append( beforeLoop.trim() + "\n" );
resultBuf.append( block.trim() );
}
if (find)
{
//хвост(ищем жадным алгоритмом) или если вообще нет ни одного цикла
loopPattern = "(?:<LOOP>(?:.*)</LOOP>)(.*)\\z";
pattern = Pattern.compile( loopPattern, Pattern.DOTALL );
m = pattern.matcher( commandStr );
if( m.find() )
{
String afterLoop = m.group( 1 ).trim();
afterLoop = this.macrosFormat.format( afterLoop, e, mainServ, connection, options );
resultBuf.append( afterLoop.trim());
//logger.info( "afterloop=" + afterLoop);
}
}
else
{
commandStr = this.macrosFormat.format( commandStr, e, mainServ, connection, options );
resultBuf.append( commandStr );
}
return resultBuf.toString();
}
private StringBuffer processBlock( String ruleText, List<InetServ> servs, ServiceActivatorEvent e, InetConnection connection, Set<Integer> options )
{
StringBuffer result = new StringBuffer();
List<PatternItem> items = new ArrayList<PatternItem>( 10 );
Map<String, Integer> letterMaxNumbers = new HashMap<String, Integer>();
Pattern pattern = Pattern.compile( "\\{([A-Z]+)(\\d+)\\}" );
Matcher m = pattern.matcher( ruleText );
while( m.find() )
{
String letter = m.group( 1 );
int number = Utils.parseInt( m.group( 2 ), 0 );
PatternItem item = new PatternItem();
item.number = number;
item.letter = letter;
items.add( item );
Integer maxNumber = letterMaxNumbers.get( letter );
if( maxNumber == null || maxNumber < number )
{
letterMaxNumbers.put( letter, number );
}
}
final int size = servs.size();
for( int i = 0; i < size; i++ )
{
//String address = IPUtils.convertLongIpToString( Utils.parseLong( addreses[i], 0 ) );
String addressRule = new String( ruleText );
InetServ serv = servs.get( i );
for( PatternItem item : items )
{
int number = i*(letterMaxNumbers.get( item.letter ) + 1) + item.number;
addressRule = addressRule.replaceAll(
"\\{" + item.letter + item.number + "\\}",
"{" + item.letter + number + "}" );
}
String str = addressRule;
if ( TimeUtils.dateBeforeOrEq(new Date(), serv.getDateTo()) || serv.getDateTo() == null)
{
str = this.macrosFormat.format( str, e, serv, connection, options );
result.append( str + "\n" );
}
}
return result;
}
private static class PatternItem
{
public String letter;
public int number;
}
@Override
protected Object getValue( ServiceActivatorEvent e, InetServ serv, InetConnection connection, Set<Integer> options, String macros, Object[] args, Object[] globalArgs )
throws Exception
{
if( "setEndSequence".equals( macros ) )
{
if( args.length > 0 )
{
String endSequence = (String)args[0];
if( Utils.notEmptyString( endSequence ) )
{
getSession().setEndString( (String)args[0] );
return "";
}
}
getSession().setEndString( this.endSequence );
return "";
}
else
{
return super.getValue( e, serv, connection, options, macros, args, globalArgs );
}
}
}