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:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * creates a package-info.xml from the SoundPackage Bean
 *
 * @param soundPackage a SoundPackage Bean containing all the meta information
 * @return a dom4j document/*  www  . ja  v a2  s.c  o m*/
 */
public static Document createPackageInfoXml(final SoundPackage soundPackage) {

    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(ENCODING);

    Element rootNode = document.addElement(SoundPackageNodes.axboSounds.toString());
    rootNode.addElement(SoundPackageNodes.packageName.toString()).addText(soundPackage.getName());
    rootNode.addElement(SoundPackageNodes.creator.toString()).addText(soundPackage.getCreator());
    rootNode.addElement(SoundPackageNodes.creationDate.toString())
            .addText(new SimpleDateFormat(pattern).format(soundPackage.getCreationDate()));

    Element securityNode = rootNode.addElement(SoundPackageNodes.security.toString());
    securityNode.addElement(SoundPackageNodes.serialNumber.toString()).addText(soundPackage.getSerialNumber());
    securityNode.addElement(SoundPackageNodes.enforced.toString())
            .addText("" + soundPackage.isSecurityEnforced());

    Element soundsNode = rootNode.addElement(SoundPackageNodes.sounds.toString());
    int id = 1;
    for (Sound sound : soundPackage.getSounds()) {
        Element soundNode = soundsNode.addElement(SoundPackageNodes.sound.toString());
        soundNode.addAttribute(SoundPackageAttributes.id.toString(), String.valueOf(id));
        soundNode.addElement(SoundPackageNodes.displayName.toString()).addText(sound.getName());

        Element axboFileNode = soundNode.addElement(SoundPackageNodes.axboFile.toString());
        axboFileNode.addElement(SoundPackageNodes.path.toString()).setText(sound.getAxboFile().extractName());
        axboFileNode.addElement(SoundPackageNodes.type.toString())
                .setText(sound.getAxboFile().getType().toString());

        id++;
    }
    return document;
}

From source file:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

/**
 * Serialize a script dispatch into jobs.xml format
 *
 * @param dispatchdef the script dispatch descriptor
 *
 * @return the XML Document/*from   w w  w .  j a  va 2  s  .  c om*/
 * @throws java.io.IOException if the input IDispatchedScript throws it when accessing script stream input.
 */
public static Document serialize(final IDispatchedScript dispatchdef) throws IOException {
    if (null == dispatchdef) {
        throw new IllegalArgumentException("cannot be null");
    }
    final Document doc = DocumentFactory.getInstance().createDocument();
    final Element root = doc.addElement("joblist");
    final String loglevelstr = ExecutionUtils.getMessageLogLevel(dispatchdef.getLoglevel(), Constants.MSG_INFO)
            .toUpperCase();

    final Element job = addJobBasic(root, "dispatch commandline job", loglevelstr);

    addScriptDispatch(dispatchdef, job);

    addNodefilters(job, dispatchdef.getNodeThreadcount(), dispatchdef.isKeepgoing(),
            dispatchdef.getNodeExcludePrecedence(), dispatchdef.getNodeFilter());

    return doc;
}

From source file:com.dtolabs.rundeck.core.cli.util.MvnPomInfoTool.java

License:Apache License

Document generateData() {
    Document doc = DocumentHelper.createDocument();
    Element el = doc.addElement("packages");
    String basepath = basedir.getAbsolutePath();
    if (basepath.endsWith("/")) {
        basepath = basepath.substring(0, basepath.length() - 1);
    }//from  ww  w. j a  va 2s.  c  om
    el.addAttribute("basedir", basepath);
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext();) {
        String file = (String) iterator.next();
        Map data = (Map) this.data.get(file);
        logger.info(file + ": " + data);
        Element pkgelem = el.addElement("package");
        pkgelem.addAttribute("name",
                data.get("artifactId") + "-" + data.get("version") + "." + data.get("packaging"));
        File f = new File(file);

        String relpom = file.substring(basepath.length() + 1);
        pkgelem.addAttribute("pom-path", relpom);

        String groupId = (String) data.get("groupId");
        String relpath = groupId.replaceAll("\\.", "/");
        pkgelem.addAttribute("repo-path", relpath);

    }
    return doc;
}

From source file:com.dtolabs.shared.resources.ResourceXMLGenerator.java

License:Apache License

/**
 * Generate and store the XML file//  w  ww.  j  a  v  a  2s . c om
 *
 * @throws IOException on error
 */
public void generate() throws IOException {
    final Document doc = DocumentFactory.getInstance().createDocument();
    final Element root = doc.addElement("project");
    //iterate through entities in correct order
    for (final ResourceXMLParser.Entity entity : entities) {
        if (NODE_ENTITY_TAG.equals(entity.getResourceType())) {
            final Element ent = genEntityCommon(root, entity);
            genNode(ent, entity);
        }
    }

    if (null != file) {
        FileOutputStream out = new FileOutputStream(file);
        try {
            serializeDocToStream(out, doc);
        } finally {
            out.close();
        }
    } else if (null != output) {
        serializeDocToStream(output, doc);
    }
}

From source file:com.ethercis.compositionservice.CompositionService.java

License:Apache License

@QuerySetting(dialect = {
        @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.STANDARD, httpMethod = "GET", method = "create", path = "vehr/composition", responseType = ResponseType.Json),
        @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.EHRSCAPE, httpMethod = "POST", method = "post", path = "rest/v1/composition", responseType = ResponseType.Json) })
public Object create(I_SessionClientProperties props) throws Exception {

    auditSetter.handleProperties(getDataAccess(), props);
    String sessionId = auditSetter.getSessionId();
    String templateId = props.getClientProperty(I_CompositionService.TEMPLATE_ID, (String) null);
    UUID ehrId = retrieveEhrId(sessionId, props);

    UUID committerUuid = auditSetter.getCommitterUuid();
    UUID systemUuid = auditSetter.getSystemUuid();

    I_CompositionService.CompositionFormat format = I_CompositionService.CompositionFormat
            .valueOf(props.getClientProperty(I_CompositionService.FORMAT, "XML"));

    if ((format == CompositionFormat.FLAT || format == CompositionFormat.ECISFLAT)
            && (templateId == null || templateId.length() == 0))
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Template Id must be specified");

    //get body stuff
    String content = props.getClientProperty(Constants.REQUEST_CONTENT, (String) null);

    if (content == null)
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Content cannot be empty for a new composition");

    Integer contentLength = (Integer) props.getClientProperty(Constants.REQUEST_CONTENT_LENGTH, (Integer) 0);

    if (content.length() != contentLength)
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Content may be altered found length =" + content.length() + " expected:" + contentLength);

    //        String contentType = props.getClientProperty(Constants.REQUEST_CONTENT_TYPE, "");

    UUID compositionId;// w ww.j  a  v  a 2  s.  co m

    switch (format) {
    case XML:
        CanonicalHandler canonicalHandler = new CanonicalHandler(knowledgeCache.getKnowledgeCache(), templateId,
                null);
        Composition composition = canonicalHandler.build(getGlobal(), content);
        templateId = composition.getArchetypeDetails().getTemplateId().getValue();
        I_CompositionAccess compositionAccess = I_CompositionAccess.getNewInstance(getDataAccess(), composition,
                DateTime.now(), ehrId);
        I_EntryAccess entryAccess = I_EntryAccess.getNewInstance(getDataAccess(), templateId, 0,
                compositionAccess.getId(), composition);
        compositionAccess.addContent(entryAccess);
        compositionId = compositionAccess.commit(committerUuid, systemUuid, auditSetter.getDescription());

        //create an XML response
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("compositionCreateRestResponseData");
        root.addElement("action").addText("CREATE");
        root.addElement("compositionUid").addText(encodeUuid(compositionId, 1));
        root.addElement("meta").addElement("href")
                .addText(Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_XML);
        return document;

    case ECISFLAT:
        PvCompoHandler pvCompoHandler = new PvCompoHandler(this.getDataAccess(), templateId, null);
        Map<String, String> kvPairs = FlatJsonUtil
                .inputStream2Map(new StringReader(new String(content.getBytes())));
        compositionId = pvCompoHandler.storeComposition(ehrId, kvPairs, auditSetter.getCommitterUuid(),
                auditSetter.getSystemUuid(), auditSetter.getDescription());

        //create json response
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_JSON);
        Map<String, Object> retmap = new HashMap<>();
        retmap.put("action", "CREATE");
        retmap.put(COMPOSITION_UID, encodeUuid(compositionId, 1));
        Map<String, Map<String, String>> metaref = MetaBuilder.add2MetaMap(null, "href",
                Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        retmap.putAll(metaref);
        return retmap;

    case FLAT:
        I_FlatJsonCompositionConverter flatJsonCompositionConverter = FlatJsonCompositionConverter
                .getInstance(getDataAccess().getKnowledgeManager());
        Map flatMap = FlatJsonUtil.inputStream2Map(new StringReader(new String(content.getBytes())));
        Composition newComposition = flatJsonCompositionConverter.toComposition(templateId, flatMap);
        I_CompositionAccess access = I_CompositionAccess.getNewInstance(getDataAccess(), newComposition,
                DateTime.now(), ehrId);
        I_EntryAccess entry = I_EntryAccess.getNewInstance(getDataAccess(), templateId, 0, access.getId(),
                newComposition);
        access.addContent(entry);
        compositionId = access.commit(committerUuid, systemUuid, auditSetter.getDescription());
        //create json response
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_JSON);
        retmap = new HashMap<>();
        retmap.put("action", "CREATE");
        retmap.put(COMPOSITION_UID, encodeUuid(compositionId, 1));
        metaref = MetaBuilder.add2MetaMap(null, "href",
                Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        retmap.putAll(metaref);
        return retmap;

    default:
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "This format is not supported:" + format);
    }
}

From source file:com.ewcms.content.particular.service.ProjectBasicService.java

License:Open Source License

public Document exportXml(List<Long> projectBasicIds) {
    Document document = DocumentHelper.createDocument();

    Element root = document.addElement("MetaDatas");
    Element metaViewData = root.addElement("MetaViewData");

    if (projectBasicIds.isEmpty())
        return document;

    for (Long projectBasicId : projectBasicIds) {
        ProjectBasic projectBasic = projectBasicDAO.get(projectBasicId);

        Element projects = metaViewData.addElement("PROPERTIES");

        Element code = projects.addElement("?");
        code.addText(projectBasic.getCode() == null ? "" : projectBasic.getCode());

        Element name = projects.addElement("??");
        name.addText(projectBasic.getName() == null ? "" : projectBasic.getName());

        Element buildTime = projects.addElement("");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (projectBasic.getBuildTime() != null) {
            buildTime.addText(dateFormat.format(projectBasic.getBuildTime()));
        } else {// www. j  ava  2  s .  c o  m
            buildTime.addText("");
        }

        Element investmentScale = projects.addElement("");
        investmentScale
                .addText(projectBasic.getInvestmentScale() == null ? "" : projectBasic.getInvestmentScale());

        Element overview = projects.addElement("");
        overview.addText(projectBasic.getOverview() == null ? "" : projectBasic.getOverview());

        Element buildUnit = projects.addElement("??");
        buildUnit.addText(projectBasic.getBuildUnit() == null ? "" : projectBasic.getBuildUnit());

        Element unitPhone = projects.addElement("????");
        unitPhone.addText(projectBasic.getUnitPhone() == null ? "" : projectBasic.getUnitPhone());

        Element unitAddress = projects.addElement("???");
        unitAddress.addText(projectBasic.getUnitAddress() == null ? "" : projectBasic.getUnitAddress());

        Element zoningCode_code = projects.addElement("?");
        if (projectBasic.getZoningCode() != null)
            zoningCode_code.addText(projectBasic.getZoningCode().getCode() == null ? ""
                    : projectBasic.getZoningCode().getCode());
        else
            zoningCode_code.addText("");

        Element organizationCode = projects.addElement("?");
        organizationCode
                .addText(projectBasic.getOrganizationCode() == null ? "" : projectBasic.getOrganizationCode());

        Element industryCode_code = projects.addElement("?");
        if (projectBasic.getIndustryCode() != null)
            industryCode_code.addText(projectBasic.getIndustryCode().getCode() == null ? ""
                    : projectBasic.getIndustryCode().getCode());
        else
            industryCode_code.addText("");

        Element category = projects.addElement("");
        category.addText(projectBasic.getCategory() == null ? "" : projectBasic.getCategory());

        Element unitId = projects.addElement("???");
        unitId.addText(projectBasic.getUnitId() == null ? "" : projectBasic.getUnitId());

        Element approvalRecord_code = projects.addElement("?");
        if (projectBasic.getApprovalRecord() != null)
            approvalRecord_code.addText(projectBasic.getApprovalRecord().getCode() == null ? ""
                    : projectBasic.getApprovalRecord().getCode());
        else
            approvalRecord_code.addText("");

        Element address = projects.addElement("?");
        address.addText(projectBasic.getAddress() == null ? "" : projectBasic.getAddress());

        Element bildNature = projects.addElement("");
        if (projectBasic.getBildNature() != null)
            bildNature.addText(projectBasic.getBildNature().getDescription() == null ? ""
                    : projectBasic.getBildNature().getDescription());
        else
            bildNature.addText("");

        Element contact = projects.addElement("?");
        contact.addText(projectBasic.getContact() == null ? "" : projectBasic.getContact());

        Element phone = projects.addElement("??");
        phone.addText(projectBasic.getPhone() == null ? "" : projectBasic.getPhone());

        Element email = projects.addElement("??");
        email.addText(projectBasic.getEmail() == null ? "" : projectBasic.getEmail());
    }
    return document;
}

From source file:com.example.sample.pMainActivity.java

License:Apache License

public Document createXMLDocument() {
    Document doc = null;
    doc = DocumentHelper.createDocument();
    doc.addComment("edited with XMLSpy v2005 rel. 3 U (http://www.altova.com) by  ()");
    //  doc.addDocType("class","//By Jack Chen","saveXML.xsd");
    Element root = doc.addElement("class");
    Element company = root.addElement("company");
    Element person = company.addElement("person");
    person.addAttribute("id", "11");
    person.addElement("name").setText("Jack Chen");
    person.addElement("sex").setText("");
    person.addElement("date").setText("2001-04-01");
    person.addElement("email").setText("chen@163.com");
    person.addElement("QQ").setText("2366001");
    return doc;/*from   w  w  w . java 2  s.c  o  m*/
}

From source file:com.fivepebbles.ProcessFiles.java

License:MIT License

@Override
public void setFiles(String[][] valuesin) {

    //Create a XML file to hold AWS bucket names and related files/folders
    Document mydoc = DocumentHelper.createDocument();
    Element root = mydoc.addElement("s3backup");
    Element bucket1 = null;/*from w w w .  j a v a  2  s  .c  o  m*/

    for (int a1 = 0; a1 < valuesin.length; a1++) {

        for (int b1 = 0; b1 < valuesin[a1].length; b1++) {
            //Bucket names are in index 0
            if (b1 == 0) {
                bucket1 = root.addElement("bucket").addAttribute("name", valuesin[a1][b1]);
            } else {
                if (bucket1 != null & valuesin[a1][b1] != null) {
                    bucket1.addElement("file").addText(valuesin[a1][b1]);
                }
            }
        }
        bucket1 = null;
    }

    //Save files and folders in file system
    FileWriter fWriter2;
    try {
        fWriter2 = new FileWriter(new File("target", "s3files.xml"));
        mydoc.write(fWriter2);
        fWriter2.flush();
        fWriter2.close();
    } catch (IOException e) {
        //***TODO*** log message
        e.printStackTrace();
    }
}

From source file:com.flaptor.hounder.crawler.modules.IndexerModule.java

License:Apache License

private void deleteFromIndex(Page page) {
    org.dom4j.Document dom = DocumentHelper.createDocument();
    Element root = dom.addElement("documentDelete");

    root.addElement("documentId").addText(getDocumentId(page));
    try {// w w w. j a va  2 s. co  m
        int i = pageMapper.mapPage(page);
        while (indexers[i].index(dom) == IndexerReturnCode.RETRY_QUEUE_FULL) {
            try {
                Thread.sleep(indexerBusyRetryTime * 1000);
            } catch (InterruptedException e) {
                logger.debug("Sleep interrupted: " + e, e);
            }
        }
        page.setEmitted(false);
    } catch (Exception e) {
        logger.error(e, e);
    }
}

From source file:com.flaptor.hounder.crawler.modules.IndexerModule.java

License:Apache License

@SuppressWarnings("unchecked")
protected void addToIndex(FetchDocument doc) {

    byte[] content = doc.getContent();
    if (0 == content.length) {
        logger.warn("Page has no data. Ignoring this document.");
        return;/* w w w.  ja  va2s.  c o  m*/
    }

    Set<String> categories = doc.getCategories();
    Map<String, Object> attributes = doc.getAttributes();
    Map<String, Object> indexableAttributes = doc.getIndexableAttributes();

    // build xml doc
    org.dom4j.Document dom = DocumentHelper.createDocument();
    Element root = dom.addElement("documentAdd");
    Page page = doc.getPage();
    String text = doc.getText();
    String url = page.getUrl();
    String host = getHost(url);
    String title = doc.getTitle(titleLengthLimit);
    String tokenizedHost = tokenizeHost(host);
    String anchorText = getAnchorText(page);

    float categoryBoost = calculateCategoryBoost(attributes);
    float pagerankBoost = calculatePagerankBoost(page);
    float spamrankBoost = calculateSpamrankBoost(page);
    float logBoost = calculateLogBoost(page);
    float freshnessBoost = calculateFreshnessBoost(page);

    // add overall score
    float f1 = factor("category", categoryBoost, categoryBoostDamp);
    float f2 = factor("pagerank", pagerankBoost, pagerankBoostDamp);
    float f3 = factor("spamrank", spamrankBoost, spamrankBoostDamp);
    float f4 = factor("log", logBoost, logBoostDamp);
    float f5 = factor("freshness", freshnessBoost, freshnessBoostDamp);
    float f6 = ((Double) attributes.get("boost")).floatValue(); // as calculated by the boost module, or 1.0 if no boost module is defined.
    float boost = f1 * f2 * f3 * f4 * f5 * f6;

    // System.out.println("BOOST url=["+url+"]  category="+f1+" ("+categoryBoost+":"+categoryBoostDamp+")  pagerank="+f2+" ("+pagerankBoost+":"+pagerankBoostDamp+")  log="+f3+" ("+logBoost+":"+logBoostDamp+")  freshness="+f4+" ("+freshnessBoost+":"+freshnessBoostDamp+") moduleBoost="+f5+"  Boost="+boost);

    if (boost < 1e-6f) {
        logger.warn("Boost too low! (" + boost + ")  category=" + f1 + " (" + categoryBoost + ":"
                + categoryBoostDamp + ")  pagerank=" + f2 + " (" + pagerankBoost + ":" + pagerankBoostDamp
                + ")  spamrank=" + f3 + " (" + spamrankBoost + ":" + spamrankBoostDamp + ")  log=" + f4 + " ("
                + logBoost + ":" + logBoostDamp + ")  freshness=" + f5 + " (" + freshnessBoost + ":"
                + freshnessBoostDamp + ") moduleBoost=" + f6);
        boost = 1e-6f;
    }

    if (null == title || "".equals(title)) {
        title = "Untitled";
    }

    root.addElement("boost").addText(String.valueOf(boost));
    root.addElement("documentId").addText(getDocumentId(page));

    Map<String, Double> boostMap = (Map<String, Double>) attributes.get("field_boost");

    // add the search fields
    addField(root, "url", url, true, true, true, boostMap);
    addField(root, "site", host, true, true, false, boostMap);
    addField(root, "tokenizedHost", tokenizedHost, false, true, true, boostMap);
    addField(root, "title", title, true, true, true, boostMap);
    addField(root, "text", text, true, true, true, boostMap);
    addField(root, "anchor", anchorText, false, true, true, boostMap);
    addField(root, "crawl", crawlName, false, true, true, boostMap);

    if (sendContent) {
        addBody(root, doc, content);
    }

    // for debugging only
    //addField(root, "boostinfo", "category="+f1+" ("+categoryBoost+":"+categoryBoostDamp+")  pagerank="+f2+" ("+pagerankBoost+":"+pagerankBoostDamp+")  log="+f3+" ("+logBoost+":"+logBoostDamp+")  freshness="+f4+" ("+freshnessBoost+":"+freshnessBoostDamp+") moduleBoost="+f5+"  Boost="+boost, true, false, false, null);

    addAdditionalFields(root, page, boostMap);

    // Adding metainfo from attributes
    Set<Entry<String, Object>> attributeSet = indexableAttributes.entrySet();
    for (Entry<String, Object> attribute : attributeSet) {
        addField(root, attribute.getKey(), attribute.getValue() == null ? "" : attribute.getValue().toString(),
                true, true, true, boostMap);
    }

    StringBuffer assignedCategories = new StringBuffer();
    if (null != categories) {
        // iterate through the classes the page belongs to add each category and its score
        for (Iterator<String> iter = categories.iterator(); iter.hasNext();) {
            assignedCategories.append(iter.next());
            assignedCategories.append(" ");

            // repeat the field times proportional to the score (this is a way to boost the document by category);
            //for (int rep = 0; rep < score*10; rep++) {
            //    addField(root, "categoryBoost", categ, false, true, false);
            //}
        }
        addField(root, "categories", assignedCategories.toString().trim(), true, true, true, boostMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Indexing dom: " + DomUtil.domToString(dom));
    }
    // Send the document to the indexer. If the queue is full, wait and retry.
    try {
        int i = pageMapper.mapPage(page);
        while (indexers[i].index(dom) == IndexerReturnCode.RETRY_QUEUE_FULL) {
            try {
                Thread.sleep(indexerBusyRetryTime * 1000);
            } catch (InterruptedException e) {
                logger.debug("Sleep interrupted: " + e, e);
            }
        }
        page.setEmitted(true);
    } catch (Exception e) {
        logger.error(e, e);
    }
}