NetworkUtil { public static String replaceExpression(String pValue) { if (pValue == null) { return null; } Matcher matcher = EXPRESSION_EXTRACTOR.matcher(pValue); StringBuffer ret = new StringBuffer(); try { while (matcher.find()) { String var = matcher.group(1); String value; if (var.equalsIgnoreCase("host")) { value = getLocalAddress().getHostName(); } else if (var.equalsIgnoreCase("ip")) { value = getLocalAddress().getHostAddress(); } else { String key = extractKey(var,"env"); if (key != null) { value = System.getenv(key); } else { key = extractKey(var,"prop"); if (key != null) { value = System.getProperty(key); } else { throw new IllegalArgumentException("Unknown expression " + var + " in " + pValue); } } } matcher.appendReplacement(ret, value != null ? value.trim() : null); } matcher.appendTail(ret); } catch (IOException e) { throw new IllegalArgumentException("Cannot lookup host" + e, e); } return ret.toString(); } private  NetworkUtil(); static void main(String[] args); static InetAddress getLocalAddress(); static InetAddress getLocalAddressWithMulticast(); static InetAddress findLocalAddressViaNetworkInterface(); static boolean isMulticastSupported(); static boolean isMulticastSupported(NetworkInterface pNif); static boolean isMulticastSupported(InetAddress pAddr); static List<InetAddress> getMulticastAddresses(); static String getAgentId(int objectId, String type); static String sanitizeLocalUrl(String pRequestURL); static String dumpLocalNetworkInfo(); static String replaceExpression(String pValue);  }
@Test public void replaceExpression() throws SocketException, UnknownHostException { String host = NetworkUtil.getLocalAddress().getHostName(); String ip = NetworkUtil.getLocalAddress().getHostAddress(); System.getProperties().setProperty("test.prop", "testy"); System.getProperties().setProperty("test2:prop", "testx"); String[] testData = { "$host",host, "bla ${host} blub","bla " + host + " blub", "$ip$host",ip + host, "${ ip }",ip, "|${prop:test.prop}|","|testy|", "${prop:test2:prop}","testx" }; for (int i = 0; i < testData.length; i+=2) { assertEquals(NetworkUtil.replaceExpression(testData[i]),testData[i+1],"Checking " + testData[i]); } }
@Test public void replaceExpressionWithEnv() { if (!System.getProperty("os.name").startsWith("Windows")) { String path = NetworkUtil.replaceExpression("Hello ${EnV:PATH} World"); assertTrue(path.contains("bin")); assertTrue(path.startsWith("Hello")); assertTrue(path.endsWith("World")); } }
@Test public void invalidExpression() { String[] testData = { "$unknown", "$hostunknown", "${prop: with space}" }; for (String t : testData) { try { NetworkUtil.replaceExpression(t); fail(t+ " has been parsed"); } catch (IllegalArgumentException exp) { } } }