package cn.vlabs.sso.vo.servlet;import java.io.IOException;
import java.io.Writer;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import cn.ac.ntarl.umt.api.ServiceContext;
import cn.ac.ntarl.umt.api.ServiceException;
import cn.ac.ntarl.umt.api.simpleAuth.VOTreeService;import cn.ac.ntarl.umt.tree.GroupTree;
import cn.ac.ntarl.umt.tree.Node;
import cn.vlabs.commons.principal.GroupPrincipal;
public class VOTreeServlet extends HttpServlet {
    private static final long serialVersionUID = 3257225521875313204L;
//    Logger log = Logger.getLogger(VOTreeServlet.class);
    ServiceContext service;    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {        String cmd = request.getParameter("cmd");
        
        if ((cmd == null) || (cmd.equals("query"))) {
            // ESAC root of the tree which program wants.
            queryVOTree(request, response, "VO");
            return;
        } else if (cmd.equals("querygroups")) {            String groupNamesStr = this.getGroupName(request);
            // groupNamesStr="[[\"ESAC\"],[\"QingHaiHu\"],[\"11\"]]";
            // writeToResponse(response,
            // "[[\"ESAC\"],[\"QingHaiHu\"],[\"11\"]]");
            writeToResponse(response, groupNamesStr);            return;
        }
        return;
    }    private String getGroupName(HttpServletRequest request) {
        Collection<Principal> principals = (Collection<Principal>) request.getSession()
                .getAttribute("principals");
        PrincipalsWrapper pWrapper = null;
        if (principals != null) {
            pWrapper = new PrincipalsWrapper();
            pWrapper.addPrincipals(principals);
        }
        
        boolean isLogged = pWrapper != null && pWrapper.isLoggedin();
        ArrayList<String> groupNames = new ArrayList<String>();
        if (isLogged) {// 用户已经登陆
            for (Principal prin : principals) {
                if (prin instanceof GroupPrincipal) {
                    if (!groupNames.contains(prin.getName())
                            && !prin.getName().equalsIgnoreCase("VO"))
                        groupNames.add(prin.getName());
                }
            }
            String groupNamesStr = "";
            if (groupNames != null && groupNames.size() > 0) {
                while (!groupNames.isEmpty()) {
                    groupNamesStr += "['" + groupNames.remove(0) + "']" + ",";
                }            }
            if (groupNamesStr != null && groupNamesStr.length() > 1) {
                groupNamesStr = groupNamesStr.substring(0, groupNamesStr
                        .length() - 1);
                groupNamesStr = "[" + groupNamesStr + "]";
                return groupNamesStr;
            }        }
        return "";    }    private boolean checkLogin(HttpServletRequest request) {
        Collection<Principal> principals = (Collection<Principal>) request.getSession()
                .getAttribute("principals");
        PrincipalsWrapper pWrapper = null;
        if (principals != null) {
            pWrapper = new PrincipalsWrapper();
            pWrapper.addPrincipals(principals);
        }        boolean isLogged = pWrapper != null && pWrapper.isLoggedin();        if (isLogged) {// 用户已经登陆            return true;
        }
        return false;
    }    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {
        doGet(req, res);
    }    private void queryVOTree(HttpServletRequest request,
            HttpServletResponse response, String VO) {
        String vo = request.getParameter("node");        response.setCharacterEncoding("UTF-8");        if ((vo == null) || (vo.equals("")) || (vo.equals("VO"))) {
            vo = VO;
        }        VOTreeService treeService = new VOTreeService(service);        getTree(treeService, response, vo);
    }    private void getTree(VOTreeService treeService,
            HttpServletResponse response, String vo) {
        try {
            GroupTree tree = treeService.getTree("VO");            if (tree != null) {
                // while (vo.contains("/"))
                // vo = vo.substring(vo.indexOf("/")+1);
                VOTreeJSONDumper dumper = new VOTreeJSONDumper(vo, service);
                while (vo.contains("/"))
                    vo = vo.substring(vo.indexOf("/") + 1);
                Node node = tree.getGroupByName(vo);
                if (node == null)
                    node = tree.getPositionByName(vo);
                if (node == null)
                    node = tree.getUserNodeByName(vo);
                if (node != null) {
                    dumper.visitChildren(node);                    
                    writeToResponse(response, dumper.toString());
                }
            }
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            log.error(e.getMessage());
        }
    }    private void writeToResponse(HttpServletResponse response, String xml) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            Writer wr = response.getWriter();
            wr.write(xml);
            System.out.println(xml+"VOTREESERLVET");
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
//            log.debug("Write xml to response error!", e);
        }
    }    public void init() {
//        service = InitUctContext.getUmtContext();            umtcontext.properties
        String webRoot=getServletContext().getRealPath("/")+"WEB-INF/umtcontext.properties";
        System.out.println(webRoot);
        Config config = Config.getInstance(webRoot);
        service = new ServiceContext();
        service.setAppname(config.getStringProp(
                "umt.appname", "umt"));
        service.setApppassword(config.getStringProp(
                "umt.apppassword", "umt"));
        service.setServerURL(config.getStringProp(
                "umt.service.url", ""));
        
    }}