1 22 package org.jboss.ejb3.test.dd.web.servlets; 23 24 import java.io.IOException ; 25 import java.io.PrintWriter ; 26 import java.security.Principal ; 27 import java.util.ArrayList ; 28 import javax.servlet.ServletConfig ; 29 import javax.servlet.ServletException ; 30 import javax.servlet.http.HttpServlet ; 31 import javax.servlet.http.HttpServletRequest ; 32 import javax.servlet.http.HttpServletResponse ; 33 34 import org.jboss.util.Strings; 35 36 53 public class UserInRoleServlet extends HttpServlet 54 { 55 56 private String [] expectedUserRoles; 57 58 private String [] unexpectedUserRoles; 59 60 public void init(ServletConfig config) throws ServletException 61 { 62 super.init(config); 63 String param = config.getInitParameter("expectedUserRoles"); 64 expectedUserRoles = Strings.split(param, ","); 65 param = config.getInitParameter("unexpectedUserRoles"); 66 unexpectedUserRoles = Strings.split(param, ","); 67 } 68 69 protected void processRequest(HttpServletRequest request, HttpServletResponse response) 70 throws ServletException , IOException 71 { 72 Principal user = request.getUserPrincipal(); 73 response.setContentType("text/html"); 74 PrintWriter out = response.getWriter(); 75 out.println("<html>"); 76 out.println("<head><title>UserInRoleServlet</title></head>"); 77 out.println("<body>"); 78 out.println("You have accessed this servlet as user:"+user); 79 80 out.println("<h1>ExpectedUserRoles</h1>"); 81 out.println("<ul>"); 82 ArrayList errors = new ArrayList (); 83 for(int n = 0; n < expectedUserRoles.length; n ++) 84 { 85 String role = expectedUserRoles[n]; 86 boolean inRole = request.isUserInRole(role); 87 out.println("<li>isUserInRole("+role+") = "+inRole+"</li>"); 88 if( inRole == false ) 89 errors.add(role); 90 } 91 out.println("</ul>"); 92 if( errors.size() > 0 ) 93 { 94 String value = errors.toString(); 95 response.addHeader("X-ExpectedUserRoles-Errors", value); 96 } 97 98 errors.clear(); 99 out.println("<h1>UnexpectedUserRoles</h1>"); 100 out.println("<ul>"); 101 for(int n = 0; n < unexpectedUserRoles.length; n ++) 102 { 103 String role = unexpectedUserRoles[n]; 104 boolean inRole = request.isUserInRole(role); 105 out.println("<li>isUserInRole("+role+") = "+inRole+"</li>"); 106 if( inRole == true ) 107 errors.add(role); 108 } 109 if( errors.size() > 0 ) 110 { 111 String value = errors.toString(); 112 response.addHeader("X-UnexpectedUserRoles-Errors", value); 113 } 114 out.println("</ul>"); 115 116 out.println("</body></html>"); 117 out.close(); 118 } 119 120 protected void doGet(HttpServletRequest request, HttpServletResponse response) 121 throws ServletException , IOException 122 { 123 processRequest(request, response); 124 } 125 126 protected void doPost(HttpServletRequest request, HttpServletResponse response) 127 throws ServletException , IOException 128 { 129 processRequest(request, response); 130 } 131 132 } 133 134 | Popular Tags |