NamenodeJspHelper { static void redirectToRandomDataNode(ServletContext context, HttpServletRequest request, HttpServletResponse resp) throws IOException, InterruptedException { final NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context); final Configuration conf = (Configuration) context .getAttribute(JspHelper.CURRENT_CONF); FSNamesystem fsn = nn.getNamesystem(); DatanodeID datanode = null; if (fsn != null && fsn.getNumLiveDataNodes() >= 1) { datanode = getRandomDatanode(nn); } if (datanode == null) { throw new IOException("Can't browse the DFS since there are no " + "live nodes available to redirect to."); } UserGroupInformation ugi = JspHelper.getUGI(context, request, conf); String tokenString = getDelegationToken( nn.getRpcServer(), request, conf, ugi); InetSocketAddress rpcAddr = nn.getNameNodeAddress(); String rpcHost = rpcAddr.getAddress().isAnyLocalAddress() ? URI.create(request.getRequestURL().toString()).getHost() : rpcAddr.getAddress().getHostAddress(); String addr = rpcHost + ":" + rpcAddr.getPort(); final String redirectLocation = JspHelper.Url.url(request.getScheme(), datanode) + "/browseDirectory.jsp?namenodeInfoPort=" + request.getServerPort() + "&dir=/" + (tokenString == null ? "" : JspHelper.getDelegationTokenUrlParam(tokenString)) + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, addr); resp.sendRedirect(redirectLocation); }    }
@Test(expected=IOException.class) public void testRedirectToRandomDataNodeNullNamesystem() throws Exception { NameNode nn = mock(NameNode.class); when(nn.getNamesystem()).thenReturn(null); ServletContext context = mock(ServletContext.class); when(context.getAttribute("name.node")).thenReturn(nn); NamenodeJspHelper.redirectToRandomDataNode(context, mock(HttpServletRequest.class), mock(HttpServletResponse.class)); }
@Test(timeout = 15000) public void testNamenodeJspHelperRedirectToRandomDataNode() throws IOException, InterruptedException { final String urlPart = "browseDirectory.jsp?namenodeInfoPort="; ServletContext context = mock(ServletContext.class); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getParameter(UserParam.NAME)).thenReturn("localuser"); when(context.getAttribute(NAMENODE_ATTRIBUTE_KEY)).thenReturn( cluster.getNameNode()); when(context.getAttribute(JspHelper.CURRENT_CONF)).thenReturn(conf); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return null; } }).when(resp).sendRedirect(captor.capture()); NamenodeJspHelper.redirectToRandomDataNode(context, request, resp); assertTrue(captor.getValue().contains(urlPart)); }