Mercurial > stress-tester
changeset 1010:82c2ce110b91
StaticMACAddressResolver
author | Devel 2 |
---|---|
date | Tue, 24 Mar 2020 10:03:56 +0100 |
parents | 654309b16935 |
children | 1f46460b2580 |
files | stress-tester/src/main/java/com/passus/st/emitter/StaticMACAddressResolver.java |
diffstat | 1 files changed, 74 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/stress-tester/src/main/java/com/passus/st/emitter/StaticMACAddressResolver.java Tue Mar 24 10:03:56 2020 +0100 @@ -0,0 +1,74 @@ +package com.passus.st.emitter; + +import com.passus.commons.Assert; +import com.passus.net.IpAddress; +import com.passus.net.MACAddress; +import com.passus.st.Pair; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +public class StaticMACAddressResolver implements MACAddressResolver { + + private final Map<IpAddress, MACAddress> map = new HashMap<>(); + + public void add(String pairStr) throws ParseException { + Pair<IpAddress, MACAddress> pair = parse(pairStr); + add(pair); + } + + public void add(Pair<IpAddress, MACAddress> pair) { + add(pair.getValue1(), pair.getValue2()); + } + + public void add(IpAddress ip, MACAddress mac) { + Assert.notNull(ip, "ip"); + Assert.notNull(mac, "mac"); + map.put(ip, mac); + } + + @Override + public MACAddress resolve(IpAddress ip) { + return map.get(ip); + } + + public static boolean validate(String pairStr) { + try { + parse(pairStr); + return true; + } catch (ParseException e) { + return false; + } + } + + public static Pair<IpAddress, MACAddress> parse(String pairStr) throws ParseException { + String separator = "->"; + + int pos = pairStr.indexOf(separator); + if (pos != -1) { + MACAddress mac; + IpAddress ip; + + String ipStr = pairStr.substring(0, pos).trim(); + try { + ip = IpAddress.parse(ipStr); + } catch (Exception e) { + throw new ParseException(e.getMessage(), pos); + } + + pos += separator.length(); + String macStr = pairStr.substring(pos); + try { + mac = new MACAddress(macStr.trim()); + } catch (Exception e) { + throw new ParseException(e.getMessage(), pos); + } + + return new Pair<>(ip, mac); + } + + throw new ParseException("Invalid MAC-IP pair.", 0); + } + +}