1 10 package org.mortbay.http.handler; 11 12 import java.io.IOException ; 13 import java.util.Hashtable ; 14 15 import org.mortbay.http.HttpException; 16 import org.mortbay.http.HttpRequest; 17 import org.mortbay.http.HttpResponse; 18 19 44 public class IPAccessHandler extends AbstractHttpHandler 45 { 46 47 48 boolean standard = false; 49 50 51 Hashtable ips; 52 53 56 public IPAccessHandler() 57 { 58 super(); 59 ips = new Hashtable (); 60 } 61 62 68 public boolean checkIP(String ipstring) 69 { 70 Boolean ipconstrain = (Boolean ) ips.get(ipstring); 71 if (ipconstrain != null) 72 { 73 return ipconstrain.booleanValue(); 74 } 75 else 76 { 77 return standard; 78 } 79 } 80 81 89 public void handle(String pathInContext, String pathParams, HttpRequest request, 90 HttpResponse response) throws HttpException, IOException 91 { 92 93 if (request.getAttribute("javax.servlet.error.status_code") != null) return; 96 97 try 98 { 99 100 String ip = request.getRemoteAddr(); 101 boolean authorized = checkIP(ip); 102 103 if (!authorized) 104 { 105 response.sendError(HttpResponse.__403_Forbidden); 107 request.setHandled(true); 108 return; 109 } 110 else 111 { 112 return; 114 } 115 } 116 catch (Exception ex) 117 { 118 System.out.println(ex); 119 response.sendError(HttpResponse.__500_Internal_Server_Error); 120 request.setHandled(true); 121 } 122 } 123 124 129 public void setAllowIP(String ipstring) 130 { 131 ips.put(ipstring, Boolean.TRUE); 132 } 133 134 139 public void setDenyIP(String ipstring) 140 { 141 ips.put(ipstring, Boolean.FALSE); 142 } 143 144 149 public void setStandard(String s) 150 { 151 s = s.toLowerCase(); 152 if (s.indexOf("allow") > -1) 153 { 154 standard = true; 155 } 156 else 157 { 158 standard = false; 159 } 160 } 161 162 166 private static void main(String [] args) 167 { 168 IPAccessHandler ipah = new IPAccessHandler(); 169 ipah.setStandard("deny"); 170 ipah.setAllowIP("217.215.71.167"); 171 ipah.setDenyIP("217.215.71.149"); 172 System.out.println(ipah.checkIP("217.215.71.245") + " = false"); 173 System.out.println(ipah.checkIP("217.215.71.167") + " = true"); 174 System.out.println(ipah.checkIP("217.215.71.149") + " = false"); 175 System.out.println(ipah.checkIP("0.0.0.0") + " = false"); 176 177 IPAccessHandler ipah2 = new IPAccessHandler(); 178 ipah2.setStandard("allow"); 179 ipah2.setAllowIP("217.215.71.167"); 180 ipah2.setDenyIP("217.215.71.149"); 181 System.out.println(ipah2.checkIP("217.215.71.245") + " = true"); 182 System.out.println(ipah2.checkIP("217.215.71.167") + " = true"); 183 System.out.println(ipah2.checkIP("217.215.71.149") + " = false"); 184 System.out.println(ipah2.checkIP("0.0.0.0") + " = true"); 185 } 186 } | Popular Tags |