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.bullx.demo.xml.XMLParser.java

License:Open Source License

public static void bookListToXML(List<Book> books) {
    Document document = DocumentHelper.createDocument();
    // XMLbooks/*  ww  w .  j av  a2 s . c  o  m*/
    Element booksElement = document.addElement("books");
    //  
    booksElement.addComment("This is a test for dom4j, liubida, 2012.8.11");

    for (Book book : books) {
        // 
        Element bookElement = booksElement.addElement("book");
        // : show
        bookElement.addAttribute("show", book.getShow() ? "yes" : "no");
        // title
        bookElement.addElement("title").setText(book.getTitle());
        // express
        bookElement.addElement("express").setText(book.getExpress());
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    StringWriter out = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(out, format);
    try {
        xmlWriter.write(document);
        xmlWriter.flush();
        String s = out.toString();
        System.out.println(s);
        Log.info("xml done!");
    } catch (Exception e) {
        Log.error("xml error!");
    } finally {
        try {
            if (null != xmlWriter) {
                xmlWriter.close();
            }
            if (null != out) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.chingo247.structureapi.plan.document.PlanDocumentGenerator.java

License:Open Source License

public void generate(File targetFolder) {
    // Scan the folder called 'SchematicToPlan' for schematic files
    Iterator<File> it = FileUtils.iterateFiles(targetFolder, new String[] { "schematic" }, true);
    System.out.println("Files: " + targetFolder.listFiles().length);

    int count = 0;
    long start = System.currentTimeMillis();

    // Generate Plans
    while (it.hasNext()) {
        File schematic = it.next();

        Document d = DocumentHelper.createDocument();
        d.addElement(Elements.ROOT).addElement(Elements.SETTLERCRAFT).addElement(Elements.SCHEMATIC)
                .setText(schematic.getName());

        File plan = new File(schematic.getParent(), FilenameUtils.getBaseName(schematic.getName()) + ".xml");

        try {/*from  w  w w  .j a v a 2s  .com*/

            XMLWriter writer = new XMLWriter(new FileWriter(plan));
            writer.write(d);
            writer.close();

            StructurePlan sp = new StructurePlan();
            PlanDocument pd = new PlanDocument(structureAPI.getPlanDocumentManager(), plan);
            pd.putPluginElement("SettlerCraft", new PlanDocumentPluginElement("SettlerCraft", pd,
                    (Element) d.selectSingleNode("StructurePlan/SettlerCraft")));
            sp.load(pd);

            if (sp.getCategory().equals("Default")
                    && !schematic.getParentFile().getName().equals(targetFolder.getName())) {
                sp.setCategory(schematic.getParentFile().getName());
            }

            sp.save();

        } catch (DocumentException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | StructureDataException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        count++;
    }
    if (count > 0) {
        StructureAPI.print("Generated " + count + " plans in " + (System.currentTimeMillis() - start) + "ms");
    }
}

From source file:com.collabnet.ccf.core.hospital.Ambulance.java

License:Open Source License

public Object[] process(Object data) {
    log.warn("Artifact reached ambulance");
    if (data instanceof MessageException) {
        MessageException exception = (MessageException) data;
        Object dataObj = exception.getData();
        String source = exception.getOriginatingModule();
        Exception rootCause = exception.getException();
        Document doc = createXMLDocument("UTF-8");
        Element failure = doc.addElement("Failure");
        Element failureSource = failure.addElement("Source");
        if (source != null)
            failureSource.setText(source);
        Element exceptionDetail = failure.addElement("Exception");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream st = new PrintStream(bos);
        rootCause.printStackTrace(st);// w w w  . j a v  a  2s.com
        exceptionDetail.setText(new String(bos.toByteArray()));
        Element dataElement = failure.addElement("Data");
        if (dataObj instanceof Document) {
            Document dataDoc = (Document) dataObj;
            String artifactFileName = null;
            try {
                artifactFileName = CCFUtils.getTempFileName(dataDoc);
            } catch (GenericArtifactParsingException e) {
                log.warn("The data that reached the hospital is not a Generic Artifact");
            }
            if (artifactFileName == null) {
                artifactFileName = "sync-info";
            }
            String tempFilePath = null;
            FileOutputStream fos = null;
            try {
                File tempFile = File.createTempFile(artifactFileName, ".xml", artifactsDirectoryFile);
                fos = new FileOutputStream(tempFile);
                String dataXML = dataDoc.asXML();
                fos.write(dataXML.getBytes());
                fos.flush();
                fos.close();
                tempFilePath = tempFile.getAbsolutePath();
            } catch (IOException e) {
                log.error("Could not create temporary File", e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        log.warn("Could not close temp file stream", e);
                    }
                }
            }
            dataElement.setText(tempFilePath);
        }
        String writeData = failure.asXML();
        try {
            fos.write(writeData.getBytes());
            fos.write(System.getProperty("line.separator").getBytes());
            fos.flush();
        } catch (IOException e) {
            log.error("An IO-Exception occured in the hospital: " + e.getMessage());
            return null;
        }
    }
    return new Object[0];
}

From source file:com.collabnet.ccf.schemageneration.XSLTInitialMFDGenerator.java

License:Apache License

/**
 * Generates an intial MFD document that can be used for the graphical data mapping
 * @param sourceSchemaName file name of the source schema
 * @param targetSchemaName file name of the target schema
 * @return//  w  ww .  j  a  v  a  2 s.  c  o  m
 * @throws TransformerException
 */
public Document generateInitialMFD(String sourceSchemaName, String targetSchemaName)
        throws TransformerException {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    Element rootElement = document.addElement("CreateInitialMFDDocument");
    rootElement.addAttribute("sourceSchemaName", sourceSchemaName);
    rootElement.addAttribute("targetSchemaName", targetSchemaName);
    return transform(initialMFDFileTransformer, document);
}

From source file:com.cosmosource.common.service.UserMgrManager.java

/**
 * @??: ?xml?/*from   ww w  .j  a  va2s. c  o  m*/
 * @param nodeId
 * @param orgid
 * @return
 */
public String getOrgTreeData(String orgid, String ctx, String type) {
    if ("init".equals(type)) {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("tree");
        root.addAttribute("id", "0");

        TAcOrg org = (TAcOrg) dao.findById(TAcOrg.class, new Long(orgid));
        Element el = root.addElement("item");
        el.addAttribute("text", org.getOrgname());
        el.addAttribute("id", org.getOrgid() + "");
        // el.addAttribute("open", "1");
        el.addAttribute("child", "1");
        Element elx = el.addElement("userdata");
        elx.addAttribute("name", "url");
        elx.addText(ctx + "/common/userMgr/list.act?nodeId=" + org.getOrgid() + "&orgtype=" + org.getOrgtype());

        // getOrgTreeDoc(new Long(orgid), el, ctx, org.getOrgtype());
        return doc.asXML();
    } else {
        Element root = DocumentHelper.createElement("tree");
        root.addAttribute("id", orgid);
        List<TAcOrg> list = dao
                .findByHQL("select t from TAcOrg t where t.parentid=" + orgid + " order by orgcode ");
        if (list.size() <= 500) {
            for (TAcOrg org : list) {
                Element el = root.addElement("item");
                el.addAttribute("text", org.getOrgname());
                el.addAttribute("id", org.getOrgid() + "");
                if ("1".equals(org.getIsbottom())) {
                    el.addAttribute("child", "1");
                } else {
                    el.addAttribute("child", "0");
                }
                // if(org.getParentid()==0){
                // el.addAttribute("open", "1");
                // }
                Element elx = el.addElement("userdata");
                elx.addAttribute("name", "url");
                if (!org.getOrgtype().equals("3")) {
                    elx.addText(ctx + "/common/userMgr/list.act?nodeId=" + org.getOrgid() + "&orgtype="
                            + org.getOrgtype());
                } else {
                    elx.addText(ctx + "/common/userMgr/orgFrame.act?nodeId=" + org.getOrgid());
                }
            }
        }
        return root.asXML();
    }

}

From source file:com.ctvit.vdp.services.sysconfiguration.user.UserService.java

/**
 * ?????XML//from   ww  w .ja  v  a 2 s.c  om
 **/
public Map<String, String> getXML(Map xmlRightIds, Map thirdRightIds) throws DocumentException {
    String baseXML = systemConfigDao.selectByPrimaryKey("Rights").getValue();//??XML
    Document doc = DocumentHelper.parseText(baseXML);
    Document topDoc = DocumentHelper.createDocument();

    Element baseElement = doc.getRootElement();
    Element topEl = topDoc.addElement("Rights");//?XML
    List<Element> secMenuList = new ArrayList<Element>();
    String topIdFlag = "";

    Iterator elementIter = baseElement.elementIterator();
    while (elementIter.hasNext()) {//??
        Element element01 = (Element) elementIter.next();
        Iterator elementIter01 = element01.elementIterator();
        while (elementIter01.hasNext()) {//??
            Element element02 = (Element) elementIter01.next();
            Iterator elementIter02 = element02.elementIterator();
            String idFlag = "";
            if (xmlRightIds.get(element02.attributeValue("id")) != null) {//??ID?ID
                Element tempEl = element02.getParent();//?
                if (topEl.nodeCount() > 0 && !topIdFlag.equals(tempEl.attributeValue("id"))) {
                    topEl.addElement(tempEl.getName()).addAttribute("id", element01.attributeValue("id"))
                            .addAttribute("name", element01.attributeValue("name"));
                }
                if (topEl.nodeCount() == 0) {
                    topEl.addElement(tempEl.getName()).addAttribute("id", element01.attributeValue("id"))
                            .addAttribute("name", element01.attributeValue("name"));
                }
                topIdFlag = tempEl.attributeValue("id");
                secMenuList.add(element02);
            }
        }
    }

    StringBuffer secXML = new StringBuffer();
    secXML.append("<Rights>");
    Element tempTopEl = topEl.createCopy();
    //      System.out.println("tempTopEl: "+tempTopEl.asXML());
    Iterator secIt = tempTopEl.elementIterator();//????
    String flag = "";
    while (secIt.hasNext()) {
        Element op = (Element) secIt.next();
        for (Element eo : secMenuList) {//eo?? 
            if (eo.attributeValue("id").substring(0, 2).equals(op.attributeValue("id"))
                    && !flag.equals(eo.attributeValue("id"))) {
                flag = eo.attributeValue("id");
                Document secDoc = DocumentHelper.createDocument();
                Element secEle = secDoc.addElement("SecMenu");
                secEle.addAttribute("id", eo.attributeValue("id"));
                secEle.addAttribute("name", eo.attributeValue("name"));
                secEle.addAttribute("source", eo.attributeValue("source"));

                Iterator eoIter = eo.elementIterator();
                while (eoIter.hasNext()) {//??
                    Element thirdEl = (Element) eoIter.next();
                    if (thirdRightIds.get(thirdEl.attributeValue("id")) != null) {
                        Document document = DocumentHelper.createDocument();
                        Element tempEle = document.addElement("ThirdMenu");
                        tempEle.addAttribute("id", thirdEl.attributeValue("id"));
                        tempEle.addAttribute("name", thirdEl.attributeValue("name"));
                        tempEle.addAttribute("source", thirdEl.attributeValue("source"));
                        secEle.add(tempEle);//
                    }
                }
                op.add(secEle);//
            }
            //System.out.println("************ op: "+op.asXML());
        }
        secXML.append(op.asXML());
    }
    secXML.append("</Rights>");
    Map<String, String> xmlMap = new HashMap<String, String>();

    xmlMap.put("topMenu", topEl.asXML());
    xmlMap.put("treeMenu", secXML.toString());
    xmlMap.put("baseXML", baseElement.asXML());
    //      this.getElementList(baseElement,xmlRightIds);
    return xmlMap;
}

From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java

License:Apache License

/**
 * Store user preference information to a specified file.
 * //from   w  w w .  j  a  va  2s  . c  om
 * @param obj 
 * @param fullPath Specified the full path of the configuration file.
 */
public void store(Object obj, String fullPath) {
    try {
        FileWriter out;
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(getName(obj.getClass()));
        root.addAttribute(GlobalConstant.CLASS, obj.getClass().getName());

        List<Field> pFields = getPreferenceFieldList(obj.getClass());
        for (int i = 0; i < pFields.size(); i++) {
            store(obj, pFields.get(i), root);
        }

        OutputFormat format = new OutputFormat("  ", true);
        out = new FileWriter(new File(fullPath));
        XMLWriter w = new XMLWriter(out, format);
        w.write(document);
        w.close();
        out.close();

    } catch (IOException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

private Element setConnectorConfig(ConnectorManager connectorManager, String connectorName,
        String connectorType, Map<String, String[]> requestParams, boolean update, Locale locale) {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_CONNECTOR_CONFIG);

    root.addElement(ServletUtil.QUERY_PARAM_LANG).addText(locale.getLanguage());
    root.addElement(ServletUtil.XMLTAG_CONNECTOR_NAME).addText(connectorName);
    root.addElement(ServletUtil.XMLTAG_CONNECTOR_TYPE).addText(connectorType);
    root.addElement(ServletUtil.XMLTAG_UPDATE_CONNECTOR).addText(Boolean.toString(update));

    for (String paramName : requestParams.keySet()) {
        if (!paramName.startsWith("wicket:")) {
            String[] paramValues = requestParams.get(paramName);
            for (String paramValue : paramValues) {
                Element paramElement = root.addElement(ServletUtil.XMLTAG_PARAMETERS);
                paramElement.addAttribute("name", paramName);
                paramElement.addAttribute("value", paramValue);
            }//from   ww  w.  ja  va  2s .c  om
        }
    }

    Element response = ConnectorManagerRequestUtils.sendPost(connectorManager, "/setConnectorConfig", document);
    Element statusIdElement = response.element(ServletUtil.XMLTAG_STATUSID);
    if (statusIdElement != null) {
        String statusId = statusIdElement.getTextTrim();
        if (!statusId.equals("" + ConnectorMessageCode.SUCCESS)) {
            return response;
        } else {
            BackupServices backupServices = ConstellioSpringUtils.getBackupServices();
            backupServices.backupConfig(connectorName, connectorType);
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

@Override
public void setSchedule(ConnectorManager connectorManager, String connectorName, Schedule schedule) {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_CONNECTOR_SCHEDULES);
    root.addElement(ServletUtil.XMLTAG_CONNECTOR_NAME).addText(connectorName);
    if (schedule.isDisabled()) {
        root.addElement(ServletUtil.XMLTAG_DISABLED).addText(Boolean.toString(schedule.isDisabled()));
    }//from  w  w w .jav  a 2s  .  com
    root.addElement(ServletUtil.XMLTAG_LOAD).addText(Integer.toString(schedule.getLoad()));
    root.addElement(ServletUtil.XMLTAG_DELAY).addText(Integer.toString(schedule.getRetryDelayMillis()));
    root.addElement(ServletUtil.XMLTAG_TIME_INTERVALS).addText(schedule.getTimeIntervalsAsString());
    ConnectorManagerRequestUtils.sendPost(connectorManager, "/setSchedule", document);

    String connectorType = getConnectorType(connectorManager, connectorName);
    BackupServices backupServices = ConstellioSpringUtils.getBackupServices();
    backupServices.backupConfig(connectorName, connectorType);
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* w  w w  . j  av a  2s.c o  m*/
public List<Record> authorizeByConnector(List<Record> records, Collection<UserCredentials> userCredentialsList,
        ConnectorManager connectorManager) {
    List<Record> authorizedRecords = new ArrayList<Record>();

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_AUTHZ_QUERY);
    Element connectorQueryElement = root.addElement(ServletUtil.XMLTAG_CONNECTOR_QUERY);

    Map<ConnectorInstance, UserCredentials> credentialsMap = new HashMap<ConnectorInstance, UserCredentials>();
    Set<ConnectorInstance> connectorsWithoutCredentials = new HashSet<ConnectorInstance>();
    Map<String, Record> recordsByURLMap = new HashMap<String, Record>();
    boolean recordToValidate = false;
    for (Record record : records) {
        // Use to accelerate the matching between response urls and actual entities
        recordsByURLMap.put(record.getUrl(), record);
        ConnectorInstance connectorInstance = record.getConnectorInstance();
        UserCredentials connectorCredentials = credentialsMap.get(connectorInstance);
        if (connectorCredentials == null && !connectorsWithoutCredentials.contains(connectorInstance)) {
            RecordCollection collection = connectorInstance.getRecordCollection();
            for (CredentialGroup credentialGroup : collection.getCredentialGroups()) {
                if (credentialGroup.getConnectorInstances().contains(connectorInstance)) {
                    for (UserCredentials userCredentials : userCredentialsList) {
                        if (userCredentials.getCredentialGroup().equals(credentialGroup)) {
                            connectorCredentials = userCredentials;
                            credentialsMap.put(connectorInstance, userCredentials);
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (connectorCredentials == null) {
            connectorsWithoutCredentials.add(connectorInstance);
            LOGGER.warning("Missing credentials for connector " + connectorInstance.getName());
        } else {
            String username = connectorCredentials.getUsername();
            if (StringUtils.isNotBlank(username)) {
                String password = EncryptionUtils.decrypt(connectorCredentials.getEncryptedPassword());
                String domain = connectorCredentials.getDomain();
                Element identityElement = connectorQueryElement.addElement(ServletUtil.XMLTAG_IDENTITY);
                identityElement.setText(username);
                if (StringUtils.isNotBlank(domain)) {
                    identityElement.addAttribute(ServletUtil.XMLTAG_DOMAIN_ATTRIBUTE, domain);
                }
                identityElement.addAttribute(ServletUtil.XMLTAG_PASSWORD_ATTRIBUTE, password);

                Element resourceElement = identityElement.addElement(ServletUtil.XMLTAG_RESOURCE);
                resourceElement.setText(record.getUrl());
                resourceElement.addAttribute(ServletUtil.XMLTAG_CONNECTOR_NAME_ATTRIBUTE,
                        connectorInstance.getName());
                recordToValidate = true;
            }
        }
    }

    if (recordToValidate) {
        Element response = ConnectorManagerRequestUtils.sendPost(connectorManager, "/authorization", document);
        Element authzResponseElement = response.element(ServletUtil.XMLTAG_AUTHZ_RESPONSE);
        List<Element> answerElements = authzResponseElement.elements(ServletUtil.XMLTAG_ANSWER);
        for (Element answerElement : answerElements) {
            Element decisionElement = answerElement.element(ServletUtil.XMLTAG_DECISION);
            boolean permit = decisionElement.getTextTrim().equals("Permit");
            if (permit) {
                Element resourceElement = answerElement.element(ServletUtil.XMLTAG_RESOURCE);
                String recordUrl = resourceElement.getTextTrim();
                Record record = recordsByURLMap.get(recordUrl);
                authorizedRecords.add(record);
            }
        }
    }
    return authorizedRecords;
}