package demo;
/*
* RequestIP.java
*/
import java.util.*;
import java.util.Map.*;
import java.util.regex.*;
import javax.swing.*;
public class RequestIP {
private HashMap<String, String> hm;
public RequestIP() {
this.hm = new HashMap<String, String>();
this.hm.put("BERLIN", "192.168.1.1");
this.hm.put("MUENCHEN", "192.168.1.2");
this.hm.put("HAMBURG", "192.168.1.3");
this.hm.put("KOELN", "192.168.1.4");
this.hm.put("FRANKFURT", "192.168.1.5");
}
public String cityToIp(final String city) {
return hm.get(city.trim().toUpperCase());
}
public String ipToCity(final String ip) {
Pattern regex = Pattern.compile("\\b" +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\.)" +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\.)" +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\.)" +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
Matcher matcher = regex.matcher(ip.trim());
StringBuilder ipVal = new StringBuilder();
if (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
ipVal.append(matcher.group(i).replaceAll("^[0]+", ""));
}
String ipValue = ipVal.toString();
Set<Entry<String, String>> es = hm.entrySet();
for (Entry<String, String> entry : es) {
if (entry.getValue().equals(ipValue)) {
return entry.getKey();
}
}
return "(IP missing in city table)";
}
return "(invalid IP)";
}
public static void main(final String[] args) {
String city = " Berlin ";
String ip = "192.168.01.001 ";
RequestIP g = new RequestIP();
JOptionPane.showMessageDialog(null,
"'" + city + "' to IP = " + g.cityToIp(city) + "\n" +
"'" + ip + "' to city = " + g.ipToCity(ip));
}
}