Example usage for org.dom4j Element elementText

List of usage examples for org.dom4j Element elementText

Introduction

In this page you can find the example usage for org.dom4j Element elementText.

Prototype

String elementText(QName qname);

Source Link

Usage

From source file:edu.ncsa.sstde.indexing.IndexManager.java

License:Apache License

public void configure(InputStream file) {

    try {//from w w w.j  av  a2  s .  c  om
        Document document = (new SAXReader()).read(file);
        @SuppressWarnings("unchecked")
        List<Element> indexerElms = document.getRootElement().elements("indexer");

        for (Element indexerElm : indexerElms) {
            String settingClass = indexerElm.elementText("setting-class").trim();
            //            Class.forName(settingClass);
            IndexerSettings indexerSettings = (IndexerSettings) Class.forName(settingClass).newInstance();
            Properties properties = new Properties();
            @SuppressWarnings("unchecked")
            List<Element> propElements = indexerElm.element("init").elements("property");
            for (Element propElm : propElements) {
                properties.put(propElm.attributeValue("name"), propElm.attributeValue("value"));
            }
            Element graphElm = indexerElm.element("indexGraph-setting");
            String pattern = graphElm.elementTextTrim("pattern");
            Collection<LiteralDef> literals = new ArrayList<LiteralDef>();
            for (Object literalDefElm : graphElm.elements("literal")) {
                Element literalDefElm2 = (Element) literalDefElm;
                literals.add(new LiteralDef(literalDefElm2.attributeValue("var"),
                        literalDefElm2.attributeValue("type")));
            }
            IndexGraph graph = new IndexGraph(pattern, literals);
            properties.put("index-graph", graph);
            properties.put("index-table", indexerElm.attributeValue("name"));
            indexerSettings.initProperties(properties);
            Indexer indexer = indexerSettings.createIndexer();
            indexer.setName(indexerElm.attributeValue("name"));
            getIndexers().add(indexer);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedQueryException e) {
        e.printStackTrace();
    } catch (UnsupportedQueryLanguageException e) {
        e.printStackTrace();
    }
}

From source file:eu.sisob.uma.crawler.ResearchersCrawlers.deprecated.LocalResearchersWebPagesExtractor.java

License:Open Source License

/**
 * Check effectivity of the recollection and recount found web pages. (of PROCESS STEP 1)
 * @param showOnlyBad/*from ww w.j a va2s . c  o m*/
 * @param topPercent
 */
public static void P1_checkEffectivityCollectResearcherLinks(String xmlFile, boolean showOnlyBad,
        float topPercent) {
    try {
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        org.dom4j.Document document = reader.read(xmlFile);
        org.dom4j.Element root = document.getRootElement();

        String sInstitutionName = "";
        String sWebAddress = "";
        String sUnitOfAssessment_Description = "";
        String sResearchGroupDescription = "";
        String sResearchers = "";
        String sResearchersInitials = "";

        int[] counterSuccess = new int[2];
        int[] counterTotal = new int[2];
        for (int i = 0; i < counterSuccess.length; i++)
            counterSuccess[i] = 0;
        for (int i = 0; i < counterTotal.length; i++)
            counterTotal[i] = 0;

        if (showOnlyBad) {
            ProjectLogger.LOGGER.info("Show only departments with less than " + topPercent + "%.\r\n");
        }

        for (Iterator i1 = root.elementIterator(XMLTags.INSTITUTION); i1.hasNext();) {
            org.dom4j.Element e1 = (org.dom4j.Element) i1.next();

            sInstitutionName = e1.element(XMLTags.INSTITUTION_NAME).getText();
            sWebAddress = e1.element(XMLTags.INSTITUTION_WEBADDRESS).getText();

            for (Iterator i2 = e1.elementIterator(XMLTags.UNIT_OF_ASSESSMENT); i2.hasNext();) {
                org.dom4j.Element e2 = (org.dom4j.Element) i2.next();

                sUnitOfAssessment_Description = e2.element(XMLTags.UNIT_OF_ASSESSMENT_DESCRIPTION).getText();
                //FIXME if(sUnitOfAssessment_Description.length() > 20) sUnitOfAssessment_Description = sUnitOfAssessment_Description.substring(0, 20);

                boolean bExistDept = false;
                String sURLs = "";

                for (Iterator i5 = e2.elementIterator(XMLTags.DEPARTMENT_WEB_ADDRESS); i5.hasNext();) {
                    org.dom4j.Element e5 = (org.dom4j.Element) i5.next();

                    sURLs += " " + e5.getText();
                    bExistDept = true;
                }

                //                    if(e2.element(XMLTags.DEPARTMENT_WEB_ADDRESS) != null)
                //                    {
                //                        bExistDept = true;
                //                        //ProjectLogger.LOGGER.info("\tExist departments webaddress for " + sUnitOfAssessment_Description);
                //                    }
                //                    else
                //                    {
                //                        bExistDept = false;
                //                    }

                String sOut = "";
                if (!bExistDept) {
                    sOut = "FAIL: " + sInstitutionName + "(" + sWebAddress + ") departments webaddress: "
                            + sUnitOfAssessment_Description;
                } else {
                    sOut = "SUCCESS: " + sInstitutionName + "(" + sWebAddress + ") departments webaddress: "
                            + sUnitOfAssessment_Description + " URLS= " + sURLs;
                }

                counterTotal[0] = 0;
                counterSuccess[0] = 0;

                String researchersText = "";
                String researchersMissText = "";
                for (Iterator i3 = e2.elementIterator(XMLTags.RESEARCHGROUP); i3.hasNext();) {
                    org.dom4j.Element e3 = (org.dom4j.Element) i3.next();
                    sResearchGroupDescription = e3.element(XMLTags.RESEARCHGROUP_DESCRIPTION).getText();

                    for (Iterator i4 = e3.elementIterator(XMLTags.RESEARCHER); i4.hasNext();) {
                        org.dom4j.Element e4 = (org.dom4j.Element) i4.next();
                        counterTotal[0]++;
                        if (e4.element(XMLTags.RESEARCHER_WEB_ADDRESS) != null
                                && e4.element(XMLTags.RESEARCHER_WEB_ADDRESS).elements().size() > 0) {
                            researchersText += ", " + e4.elementText(XMLTags.RESEARCHER_LASTNAME) + " "
                                    + e4.elementText(XMLTags.RESEARCHER_INITIALS);
                            counterSuccess[0]++;
                        } else {
                            researchersMissText += ", " + e4.elementText(XMLTags.RESEARCHER_LASTNAME) + " "
                                    + e4.elementText(XMLTags.RESEARCHER_INITIALS);
                        }
                    }
                }

                int percent = (counterSuccess[0] * 100) / counterTotal[0];
                if (showOnlyBad) {
                    if (percent <= topPercent) {
                        ProjectLogger.LOGGER.info("");
                        ProjectLogger.LOGGER.info("BAD RESULTS: " + sOut);
                        ProjectLogger.LOGGER.info("\tResearchers found: " + counterSuccess[0] + "/"
                                + counterTotal[0] + "\t(" + percent + " %)");
                        ProjectLogger.LOGGER.info("\tFound: " + researchersText);
                        ProjectLogger.LOGGER.info("\tMiss: " + researchersMissText);
                    }
                } else {
                    ProjectLogger.LOGGER.info("");
                    ProjectLogger.LOGGER.info(sOut);
                    ProjectLogger.LOGGER.info("\tResearchers found: " + counterSuccess[0] + "/"
                            + counterTotal[0] + "\t(" + percent + " %)");
                    ProjectLogger.LOGGER.info("\tFound: " + researchersText);
                    ProjectLogger.LOGGER.info("\tMiss: " + researchersMissText);
                }

                counterTotal[1] += counterTotal[0];
                counterSuccess[1] += counterSuccess[0];
            }
        }

        ProjectLogger.LOGGER.info("");
        ProjectLogger.LOGGER.info("TOTAL Researchers found: " + counterSuccess[1] + "/" + counterTotal[1]);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.info(ex.getMessage());
    }
}

From source file:guineu.util.NumberFormatter.java

License:Open Source License

public void importFromXML(Element xmlElement) {
    String pattern = xmlElement.elementText(PATTERN_ELEMENT_NAME);
    FormatterType type = FormatterType.valueOf(xmlElement.elementText(TYPE_ELEMENT_NAME));
    setFormat(type, pattern);//from  w  ww  .j  a  va2 s.c  o m
}

From source file:hudson.tasks.junit.CaseResult.java

License:Open Source License

CaseResult(SuiteResult parent, Element testCase, String testClassName, boolean keepLongStdio) {
    // schema for JUnit report XML format is not available in Ant,
    // so I don't know for sure what means what.
    // reports in http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
    // indicates that maybe I shouldn't use @classname altogether.

    //String cn = testCase.attributeValue("classname");
    //if(cn==null)
    //    // Maven seems to skip classname, and that shows up in testSuite/@name
    //    cn = parent.getName();

    /*/* w  ww  .ja  v a2 s .  c om*/
    According to http://www.nabble.com/NPE-(Fatal%3A-Null)-in-recording-junit-test-results-td23562964.html
    there's some odd-ball cases where testClassName is null but
    @name contains fully qualified name.
     */
    String nameAttr = testCase.attributeValue("name");
    if (testClassName == null && nameAttr.contains(".")) {
        testClassName = nameAttr.substring(0, nameAttr.lastIndexOf('.'));
        nameAttr = nameAttr.substring(nameAttr.lastIndexOf('.') + 1);
    }

    className = testClassName;
    testName = nameAttr;
    errorStackTrace = getError(testCase);
    errorDetails = getErrorMessage(testCase);
    this.parent = parent;
    duration = parseTime(testCase);
    skipped = isMarkedAsSkipped(testCase);
    skippedMessage = getSkippedMessage(testCase);
    @SuppressWarnings("LeakingThisInConstructor")
    Collection<CaseResult> _this = Collections.singleton(this);
    stdout = possiblyTrimStdio(_this, keepLongStdio, testCase.elementText("system-out"));
    stderr = possiblyTrimStdio(_this, keepLongStdio, testCase.elementText("system-err"));
}

From source file:hudson.tasks.junit.SuiteResult.java

License:Open Source License

/**
 * @param xmlReport//from w  ww. ja  v  a  2  s.c  o  m
 *      A JUnit XML report file whose top level element is 'testsuite'.
 * @param suite
 *      The parsed result of {@code xmlReport}
 */
private SuiteResult(File xmlReport, Element suite, boolean keepLongStdio)
        throws DocumentException, IOException {
    this.file = xmlReport.getAbsolutePath();
    String name = suite.attributeValue("name");
    if (name == null)
        // some user reported that name is null in their environment.
        // see http://www.nabble.com/Unexpected-Null-Pointer-Exception-in-Hudson-1.131-tf4314802.html
        name = '(' + xmlReport.getName() + ')';
    else {
        String pkg = suite.attributeValue("package");
        if (pkg != null && pkg.length() > 0)
            name = pkg + '.' + name;
    }
    this.name = TestObject.safe(name);
    this.timestamp = suite.attributeValue("timestamp");
    this.id = suite.attributeValue("id");

    Element ex = suite.element("error");
    if (ex != null) {
        // according to junit-noframes.xsl l.229, this happens when the test class failed to load
        addCase(new CaseResult(this, suite, "<init>", keepLongStdio));
    }

    @SuppressWarnings("unchecked")
    List<Element> testCases = (List<Element>) suite.elements("testcase");
    for (Element e : testCases) {
        // https://issues.jenkins-ci.org/browse/JENKINS-1233 indicates that
        // when <testsuites> is present, we are better off using @classname on the
        // individual testcase class.

        // https://issues.jenkins-ci.org/browse/JENKINS-1463 indicates that
        // @classname may not exist in individual testcase elements. We now
        // also test if the testsuite element has a package name that can be used
        // as the class name instead of the file name which is default.
        String classname = e.attributeValue("classname");
        if (classname == null) {
            classname = suite.attributeValue("name");
        }

        // https://issues.jenkins-ci.org/browse/JENKINS-1233 and
        // http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
        // are at odds with each other --- when both are present,
        // one wants to use @name from <testsuite>,
        // the other wants to use @classname from <testcase>.

        addCase(new CaseResult(this, e, classname, keepLongStdio));
    }

    String stdout = CaseResult.possiblyTrimStdio(cases, keepLongStdio, suite.elementText("system-out"));
    String stderr = CaseResult.possiblyTrimStdio(cases, keepLongStdio, suite.elementText("system-err"));
    if (stdout == null && stderr == null) {
        // Surefire never puts stdout/stderr in the XML. Instead, it goes to a separate file (when ${maven.test.redirectTestOutputToFile}).
        Matcher m = SUREFIRE_FILENAME.matcher(xmlReport.getName());
        if (m.matches()) {
            // look for ***-output.txt from TEST-***.xml
            File mavenOutputFile = new File(xmlReport.getParentFile(), m.group(1) + "-output.txt");
            if (mavenOutputFile.exists()) {
                try {
                    stdout = CaseResult.possiblyTrimStdio(cases, keepLongStdio, mavenOutputFile);
                } catch (IOException e) {
                    throw new IOException2("Failed to read " + mavenOutputFile, e);
                }
            }
        }
    }

    this.stdout = stdout;
    this.stderr = stderr;
}

From source file:imageviewer.tools.annotation.LIDCAnnotationReader.java

License:Open Source License

public void readFile(File f, ArrayList<? extends Image> images) {

    SeriesAnnotation sa = new SeriesAnnotation();

    try {/*from  w w w  . j av a2  s  .  co  m*/
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(f);
        Element root = doc.getRootElement();
        Iterator responseHeaderIter = root.elementIterator("ResponseHeader");
        String seriesUID = "";
        String studyUID = "";
        while (responseHeaderIter.hasNext()) {
            Element responseHeader = (Element) responseHeaderIter.next();
            sa.setUID(responseHeader.elementText("SeriesInstanceUid"));
            //sa.setUID(responseHeader.elementText("StudyInstanceUID"));
        }
        Iterator readingSessionIter = root.elementIterator("readingSession");
        while (readingSessionIter.hasNext()) {
            Element readingSessionElem = (Element) readingSessionIter.next();
            Iterator unblindedIter = readingSessionElem.elementIterator("unblindedReadNodule");
            while (unblindedIter.hasNext()) {
                Element unblindedElem = (Element) unblindedIter.next();
                Iterator roiIter = unblindedElem.elementIterator("roi");
                while (roiIter.hasNext()) {
                    Element roi = (Element) roiIter.next();
                    String imageUID = roi.elementText("imageSOP_UID");
                    String inclusion = roi.elementText("inclusion");
                    ImageAnnotation imageA = new ImageAnnotation(imageUID);
                    imageA.setNodule(true);
                    if (inclusion.equalsIgnoreCase(("true"))) {
                        imageA.setInclusion(true);
                    } else {
                        imageA.setInclusion(false);
                    }
                    Iterator edgeMapIter = roi.elementIterator("edgeMap");
                    while (edgeMapIter.hasNext()) {
                        Element edgeMapElem = (Element) edgeMapIter.next();
                        String x = edgeMapElem.elementText("xCoord");
                        String y = edgeMapElem.elementText("yCoord");
                        // System.out.println("[debug] nodule adding for " + imageUID + ": " + x + "," + y);
                        imageA.addPoint(Integer.valueOf(x), Integer.valueOf(y));
                    }
                    sa.addAnnotation(imageA);
                }
            }
            Iterator nonNoduleIter = readingSessionElem.elementIterator("nonNodule");
            while (nonNoduleIter.hasNext()) {
                Element nonNoduleElem = (Element) nonNoduleIter.next();
                String imageUID = nonNoduleElem.elementText("imageSOP_UID");
                ImageAnnotation imageA = new ImageAnnotation(imageUID);
                imageA.setNodule(false);
                Iterator locusIter = nonNoduleElem.elementIterator("locus");
                while (locusIter.hasNext()) {
                    Element locusElem = (Element) locusIter.next();
                    String x = locusElem.elementText("xCoord");
                    String y = locusElem.elementText("yCoord");
                    // System.out.println("[debug] nonNodule adding for " + imageUID + ": " + x + "," + y);
                    imageA.addPoint(Integer.valueOf(x), Integer.valueOf(y));
                }
                sa.addAnnotation(imageA);
            }
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    // Given the series annotation, create the appropriate data layers
    // per annotation

    for (int loop = 0, n = sa.numAnnotations(); loop < n; loop++) {
        ImageAnnotation ia = sa.getAnnotation(loop);
        String annotationUID = ia.getUID();
        for (Iterator i = images.iterator(); i.hasNext();) {
            Image img = (Image) i.next();
            String imageUID = (String) img.getProperties().get("SOPInstanceUID");
            if ((imageUID != null) && (imageUID.equals(annotationUID))) {
                ShapeDataLayer sdl = (ShapeDataLayer) img.findDataLayer(DataLayer.SHAPE);
                if (sdl == null) {
                    sdl = new ShapeDataLayer();
                    img.addDataLayer(sdl);
                }
                Polygon polygon = new Polygon();
                for (int j = 0, m = ia.numPoints(); j < m; j++) {
                    Point pt = ia.getPoint(j);
                    polygon.addPoint(pt.x, pt.y);
                }
                StylizedShape ss = new StylizedShape(polygon, null, 1.0f, 0.75f);
                // ss.setFilled(isFilled);
                ss.setStrokeColor(STROKE_COLOR);
                ss.setFillColor(FILL_COLOR);
                ss.setFillAlphaComposite(0.5f);
                sdl.addShape(ss);
            }
        }
    }
}

From source file:it.polito.iconvis.integration.db.IconvisDAO.java

License:Open Source License

public void getConnectionDataFromXml() throws MalformedURLException, DocumentException {
    log.debug("[QueryManager::getConnectionDataFromXml] BEGIN");
    File xml = new File(IconvisBean.ontologyFolderPath + "/query_mapping.xml");
    SAXReader reader = new SAXReader();
    Document doc = reader.read(xml);
    Element root = doc.getRootElement();
    Element database = root.element("database");
    IconvisBean.databaseURL = database.elementText("url");
    IconvisBean.databaseVendor = database.elementText("vendor");
    IconvisBean.databaseDriver = database.elementText("driver");
    IconvisBean.databaseUser = database.elementText("user");
    IconvisBean.databasePassword = database.elementText("password");
    log.info("[iconviz] Got DB connection data from XML. USERNAME: " + IconvisBean.databaseUser + " PASSWORD: "
            + IconvisBean.databasePassword + " URL: " + IconvisBean.databaseURL);
    log.debug("[QueryManager::getConnectionDataFromXml] END");
}

From source file:it.polito.iconvis.integration.db.QueryManager.java

License:Open Source License

public void mapIndividualToQuery() throws IconvisQueryManagementException {
    log.debug("[QueryManager::mapIndividualToQuery] BEGIN");
    try {//from  ww  w .  j av a2  s .  c om
        IconvisBean.individualQueryMap = new HashMap<String, String>();
        // if in query_mapping.xml something is missing, individual with no query associated return a "NoQuerySet" string.
        for (String s : allIndividuals) {
            IconvisBean.individualQueryMap.put(s, "NoQuerySet");
        }
        File xml = new File(IconvisBean.ontologyFolderPath + "/query_mapping.xml");
        SAXReader reader = new SAXReader();
        Document doc = reader.read(xml);
        Element root = doc.getRootElement();

        List<Element> classlist = new ArrayList<Element>();
        classlist = root.elements("class");
        if (classlist != null && !classlist.isEmpty()) {
            for (Element elem : classlist) {
                String classId = elem.attributeValue("id");
                ArrayList<String> arr = IconvisBean.individualsOfClassesTable.get(classId);
                if (!arr.isEmpty()) {
                    for (String indiv : arr) {
                        String sql = elem.elementText("class_query");
                        if (IconvisBean.labelMap.get(indiv) != null) {
                            IconvisBean.individualQueryMap.put(indiv,
                                    sql.replace("#default#", IconvisBean.labelMap.get(indiv)));
                        } else {
                            log.debug("[QueryManager::mapIndividualToQuery] No labels set on the node \""
                                    + indiv
                                    + "\". This could affect the outcome of database queries, if you have not set a different behavior in query_mapping.xml.");
                        }
                    }
                }
            }
        }
        List<Element> indivlist = new ArrayList<Element>();
        indivlist = root.elements("indiv");
        if (indivlist != null && !indivlist.isEmpty()) {
            for (Element elem : indivlist) {
                String indivId = elem.attributeValue("id");
                String sql = elem.elementText("indiv_query");
                IconvisBean.individualQueryMap.put(indivId,
                        sql.replace("#default#", IconvisBean.labelMap.get(indivId)));
            }
        }
    } catch (Exception e) {
        log.error("[QueryManager::mapIndividualToQuery] Exception: ", e);
        throw new IconvisQueryManagementException(
                "Exception generated during the mapping of individuals to SQL query.");
    }
    log.debug("[QueryManager::mapIndividualToQuery] END");
}

From source file:it.polito.iconvis.integration.lod.LODQueryManager.java

License:Open Source License

public void mapIndividualToSPARQLQuery() throws IconvisLODManagementException {
    log.debug("[QueryManager::mapIndividualToSPARQLQuery] BEGIN");
    try {/* www .  j  ava2s  .  c om*/
        IconvisBean.individualSPARQLQueryMap = new HashMap<String, String>();
        // if in LOD_query_mapping.xml something is missing, individual with no SPARQL query associated return a "NoQuerySet" string.
        for (String s : IconvisBean.allIndividuals) {
            IconvisBean.individualSPARQLQueryMap.put(s, "NoQuerySet");
        }
        File xml = new File(IconvisBean.ontologyFolderPath + "/LOD_mapping.xml");
        SAXReader reader = new SAXReader();
        Document doc = reader.read(xml);
        Element root = doc.getRootElement();

        List<Element> classlist = new ArrayList<Element>();
        classlist = root.elements("class");
        if (classlist != null && !classlist.isEmpty()) {
            for (Element elem : classlist) {
                String classId = elem.attributeValue("id");
                ArrayList<String> arr = IconvisBean.individualsOfClassesTable.get(classId);
                if (!arr.isEmpty()) {
                    for (String indiv : arr) {
                        String endpoint = elem.elementText("class_endpoint");
                        String sql = elem.elementText("class_query");
                        if (IconvisBean.labelMap.get(indiv) != null) {
                            IconvisBean.individualSPARQLQueryMap.put(indiv,
                                    sql.replace("#default#", IconvisBean.labelMap.get(indiv)) + SEPARATOR_1
                                            + endpoint);
                        } else {
                            log.debug("[QueryManager::mapIndividualToSPARQLQuery] No labels set on the node \""
                                    + indiv
                                    + "\". This could affect the outcome of SPARQL queries, if you have not set a different behavior in LOD_mapping.xml.");
                        }
                    }
                }
            }
        }
        List<Element> indivlist = new ArrayList<Element>();
        indivlist = root.elements("indiv");
        if (indivlist != null && !indivlist.isEmpty()) {
            for (Element elem : indivlist) {
                String indivId = elem.attributeValue("id");
                String endpoint = elem.elementText("indiv_endpoint");
                String sql = elem.elementText("indiv_query");
                if (IconvisBean.labelMap.get(indivId) != null) {
                    IconvisBean.individualSPARQLQueryMap.put(indivId,
                            sql.replace("#default#", IconvisBean.labelMap.get(indivId)) + SEPARATOR_1
                                    + endpoint);
                } else {
                    log.debug("[QueryManager::mapIndividualToSPARQLQuery] No labels set on the node \""
                            + indivId
                            + "\". This could affect the outcome of SPARQL queries, if you have not set a different behavior in LOD_mapping.xml.");
                }
            }
        }
    } catch (Exception e) {
        log.error("[QueryManager::mapIndividualToSPARQLQuery] Exception: ", e);
        throw new IconvisLODManagementException(
                "Exception generated during the mapping of individuals to SQL query.");
    }
    log.debug("[QueryManager::mapIndividualToSPARQLQuery] END");
}

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

License:Open Source License

/**
 *  /invite/* ww  w .  j a  v a 2 s. c  o m*/
 *
 *
 */
@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());
    }
}