Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /groupUsers/*w w w.j  av  a  2  s  .c  om*/
 *
 *  Output:
 *      User List XML
 *
 */
@ContentType("text/xml")
public void webGroupUsers(HttpServletRequest request, HttpServletResponse response) throws Exception {

    User self = (User) request.getUserPrincipal();

    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();
    UserSpace uspace = self.getUserSpace();

    HibernateUtil.getSession().refresh(uspace);

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("group");

    String groupId = request.getParameter("groupId");
    if (!Check.isEmpty(groupId)) {
        Group grp = uspace.getGroup(groupId);
        if (grp != null) {
            root.addAttribute("id", grp.getGroupId());
            root.addAttribute("name", grp.getSimpleName());
        }
        for (User user : uspace.getGroupUsers(grp)) {
            Element uElem = root.addElement("user");
            uElem.addAttribute("id", user.getUserId());
            uElem.addAttribute("name", user.getSimpleName());
            uElem.addAttribute("email", user.getName());
            uElem.addAttribute("positions", StringHelper.stringFromSet(uspace.getGroupRoles(grp, user)));
        }
    }

    HibernateUtil.commitTransaction();
    ServletUtil.setExpired(response);
    doc.write(response.getWriter());
}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /guestList/* w  w w  . j  a  v  a 2s  . c  o  m*/
 *
 *  Output:
 *      Guest User List XML
 *
 */
@ContentType("text/xml")
public void webGuestList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    UserEntity self = (UserEntity) request.getUserPrincipal();

    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();
    UserSpace uspace = self.getUserSpace();

    HibernateUtil.getSession().refresh(uspace);

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("list");
    root.addAttribute("name", uspace.getName());
    root.addAttribute("self", self.getUserId());
    root.addAttribute("self-roles", self.getUSpaceUser().getRoleStr());
    for (User user : uspace.getUsersInRole("guest")) {
        Element uElem = root.addElement("user");
        uElem.addAttribute("id", user.getUserId());

        // email source may change here....
        uElem.addAttribute("email", user.getName());
        uElem.addAttribute("name", user.getSimpleName());
    }

    HibernateUtil.commitTransaction();

    // let the list live a bit
    ServletUtil.cacheTimeout(response, 12);
    doc.write(response.getWriter());
}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /getUserMan/*from   w w w.ja va  2 s . c o  m*/
 *
 *
 */
@ContentType("text/xml")
public void webGetUserMan(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AuthenticatedUser self = (AuthenticatedUser) request.getUserPrincipal();
    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();

    if (!self.getRoles().contains("admin"))
        throw new UserSpaceException("Admin role required");

    String id = request.getParameter("id");
    if (!Check.isEmpty(id)) {
        UserSpace uspace = self.getUserSpace();
        HibernateUtil.getSession().refresh(uspace);
        UserEntity uEnt = (UserEntity) uspace.resolve(new DefaultUser(id));
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("user");
        root.addAttribute("id", id);
        root.addElement("name").setText(uEnt.getSimpleName());
        root.addElement("email").setText(uEnt.getName());
        root.addElement("roles").setText(uEnt.getUserSpaceUsers().get(uspace).getRoleStr());
        HibernateUtil.commitTransaction();
        ServletUtil.setExpired(response);
        doc.write(response.getWriter());
    }

}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 * /getMember/*from ww  w . jav  a 2  s  .  c  o m*/
 *     <member xmlns="">
 *           <group/>
 *           <user/>
 *           <positions/>
 *      </member>
 */
@ContentType("text/xml")
public void webGetMember(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AuthenticatedUser self = (AuthenticatedUser) request.getUserPrincipal();
    Map<String, String> params = RequestUtil.readParameters(request, new String[] { "user", "group" });
    String userId = params.get("user");
    String groupId = params.get("group");
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("member");
    if (!Check.isEmpty(userId) && !Check.isEmpty(groupId)) {
        HibernateUtil.beginTransaction();
        HibernateUtil.readOnlySession();
        root.addElement("user").setText(userId);
        root.addElement("group").setText(groupId);
        UserSpace uspace = self.getUserSpace();
        Set<String> roles = uspace.getGroupRoles(new DefaultGroup(groupId), new DefaultUser(userId));
        if (!Check.isEmpty(roles)) {
            root.addElement("positions").setText(StringHelper.stringFromSet(roles));
        }
        HibernateUtil.commitTransaction();
    }
    ServletUtil.setExpired(response);
    doc.write(response.getWriter());
}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /getSelf/*w w w . j  a v  a 2 s. c  o  m*/
 *
 *
 */
@ContentType("text/xml")
public void webGetSelf(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getUserPrincipal();

    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();
    UserEntity uEnt = (UserEntity) user;

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("user");
    root.addElement("name").setText(uEnt.getSimpleName());
    root.addElement("email").setText(uEnt.getName());
    root.addElement("flags").setText(uEnt.getFlagStr() != null ? uEnt.getFlagStr() : "");
    root.addElement("timezone").setText(uEnt.getTimezoneStr());
    HibernateUtil.commitTransaction();
    ServletUtil.setExpired(response);
    doc.write(response.getWriter());
}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /invite/*from   www.  j a  v  a  2  s.  c  om*/
 *
 *
 */
@ContentType("text/xml")
public void webInvite(HttpServletRequest request, HttpServletResponse response) throws Exception {

    User user = (User) request.getUserPrincipal();
    Document doc = XMLDocument.readStream(request.getInputStream());
    Element root = doc.getRootElement();
    if ("invite".equals(root.getName())) {
        MailService mailer = getMailer();
        InternetAddress fromAddr = new InternetAddress(
                mailer.getProperties().getProperty("alert.from.email", "alert@itensil.com"),
                mailer.getProperties().getProperty("alert.from.name", "Alert"));

        HibernateUtil.beginTransaction();
        UserSpace uspace = user.getUserSpace();
        String name = root.elementTextTrim("name");
        String email = root.elementTextTrim("email");
        boolean asGuest = "1".equals(root.elementTextTrim("guest"));
        boolean guestLog = "1".equals(root.elementTextTrim("log"));

        String password = root.elementTextTrim("password");

        String comment = root.elementText("comment");

        StringBuffer buf = new StringBuffer("You are invited to join ");
        buf.append(user.getSimpleName());
        buf.append("'s community.\n");
        buf.append(uspace.getBaseUrl());
        buf.append("\n\n");
        HibernateUtil.getSession().refresh(uspace);
        String pass = Check.isEmpty(password) ? PasswordGen.generatePassword() : password;
        HashSet<String> roles = new HashSet<String>(1);
        if (asGuest) {
            roles.add("guest");
            if (guestLog)
                roles.add("actlog");
        } else {
            roles.add("inviter");
        }
        UserEntity newUser = (UserEntity) uspace.createUser(email, name, pass, roles, user.getLocale(),
                user.getTimeZone());

        Group createGroup = null;
        Group editGroup = null;
        Group guestGroup = null;
        for (Group grp : uspace.getGroups()) {
            if ("Creators".equals(grp.getSimpleName()))
                createGroup = grp;
            else if ("Editors".equals(grp.getSimpleName()))
                editGroup = grp;
            else if ("Guests".equals(grp.getSimpleName()))
                guestGroup = grp;
        }
        if (asGuest) {
            if (guestGroup != null)
                uspace.addGroupUser(guestGroup, newUser);
        } else if (editGroup != null && user.isUserInGroup(editGroup)) {
            uspace.addGroupUser(editGroup, newUser);
        } else {
            if (createGroup != null)
                uspace.addGroupUser(createGroup, newUser);
        }

        // created users have non-null provider
        if (newUser != null) {
            buf.append("Username:\n");
            buf.append(email.trim());

            if (newUser.getUserSpaceUsers().size() == 1) {
                buf.append('\n');
                buf.append("\nPassword:\n");
                buf.append(pass.trim());
            } else {
                buf.append("\nPlease use your existing password for this community.");
            }
        }

        if (!Check.isEmpty(comment)) {
            buf.append("\n\n");
            buf.append(comment);
            buf.append('\n');
        }

        // email only a generated password

        HibernateUtil.commitTransaction();

        Document resDoc = DocumentHelper.createDocument();
        Element resRoot = resDoc.addElement("invite");
        resRoot.addAttribute("userId", newUser.getUserId());
        resRoot.addAttribute("email", email);
        resRoot.addElement("body").setText(buf.toString());

        resDoc.write(response.getWriter());
    }
}

From source file:itensil.security.web.UserSpaceServlet.java

License:Open Source License

/**
 *  /timezones/*from   w w  w  .  j a  va 2 s .  c om*/
 *
 *
 */
@ContentType("text/xml")
public void webTimezones(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("timezones");
    for (Map.Entry<String, String> zone : TimeZoneList.zoneNames.entrySet()) {
        Element zEl = root.addElement("zone");

        zEl.addAttribute("id", zone.getValue());
        zEl.addAttribute("name", zone.getKey());
    }
    doc.write(response.getWriter());
}

From source file:itensil.timecard.web.TimecardServlet.java

License:Open Source License

/**
  *  /contractRoles//from ww  w .  jav a2 s .c  o m
  *
  *  Distinct list of roles across contracts:
  *  
  *  <roles>
  *      <role></role>
  *  </roles>
  */
@ContentType("text/xml")
public void webContractRoles(HttpServletRequest request, HttpServletResponse response) throws Exception {

    AuthenticatedUser self = (AuthenticatedUser) request.getUserPrincipal();
    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();
    Query qry = HibernateUtil.getSession().getNamedQuery("Timecard.allRoles");
    qry.setString("usid", self.getUserSpaceId());

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("roles");

    for (Object roleStr : qry.list()) {
        root.addElement("role").setText(roleStr.toString());
    }

    HibernateUtil.commitTransaction();

    doc.write(response.getWriter());
}

From source file:itensil.timecard.web.TimecardServlet.java

License:Open Source License

/**
 *  /getContract/*from  www  .  ja  va  2s .  c  om*/
 *  
 * Params:
 * 
 *       contract_id  - optional, empty = new
 *
 * Get a contract:
 *
 *      <contract id="123">
 *        <clientName/>
 *          <name/>
 *          <team/>
 *          <estMonths/>
 *          <status/>
 *          <billTerms/>
 *          <billOverages/>
 *          <moneyBudget/>
 *          <hoursBudget/>
 *          <openDate/>
 *          <closeDate/>
 *        <manager/>
 *     
 *        <projects>
 *           <project>Main</project>
 *           ...
 *        </projects>
 *     
 *        <role id="122" rate="25">General</role>
 *        ...
 *     </contract>
 */
@ContentType("text/xml")
public void webGetContract(HttpServletRequest request, HttpServletResponse response) throws Exception {

    AuthenticatedUser self = (AuthenticatedUser) request.getUserPrincipal();
    HibernateUtil.beginTransaction();
    HibernateUtil.readOnlySession();

    String contractId = request.getParameter("contract_id");

    ContractEntity cont;
    if (Check.isEmpty(contractId)) {
        cont = ContractEntity.createBlankContract();
    } else {
        cont = (ContractEntity) HibernateUtil.getSession().load(ContractEntity.class, contractId);
        if (cont == null || !cont.getUserSpaceId().equals(self.getUserSpaceId())) {
            throw new NotFoundException("Contract id:" + contractId);
        }
    }

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("contract");
    root.addAttribute("id", String.valueOf(cont.getId()));
    root.addElement("clientName").setText(cont.getClientName());
    root.addElement("name").setText(cont.getName());
    root.addElement("team").setText(cont.getTeam());

    HibernateUtil.commitTransaction();

    doc.write(response.getWriter());
}

From source file:itensil.web.MethodServlet.java

License:Open Source License

protected void errorXML(HttpServletRequest request, HttpServletResponse response, Throwable th)
        throws IOException {

    Document doc = DocumentHelper.createDocument();
    Element error = doc.addElement("error");
    error.addAttribute("exception", th.getClass().getName());
    Element message = error.addElement("message");
    String msg = th.getMessage();
    message.addText(msg == null ? th.toString() : msg);
    if (logger.isInfoEnabled()) {
        Element details = error.addElement("details");
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        details.addCDATA(sw.toString());
    }//from www . j  a va  2s.c  om
    if (th.getCause() != null) {
        error.addAttribute("cause", th.getCause().getClass().getName());
    }
    ServletUtil.noCache(response);
    doc.write(response.getWriter());
}