Example usage for org.dom4j Element addElement

List of usage examples for org.dom4j Element addElement

Introduction

In this page you can find the example usage for org.dom4j Element 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.ctvit.vdp.services.sysconfiguration.user.UserService.java

/**
 * ?????XML//from  ww  w . j a va2  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 object tree into XML file./* w w w .ja  va2 s .com*/
 * 
 * @param fieldClass
 * @param fieldName
 * @param fieldValue
 * @param parent
 * @param adapterClass
 * @throws IllegalArgumentException
 * @throws IllegalAccessException 
 */
private void store(Class fieldClass, String fieldName, Object fieldValue, Element parent,
        Class<? extends PersistentAdapterIF> adapterClass)
        throws IllegalArgumentException, IllegalAccessException {

    if (fieldClass.isArray()) {

        if (fieldName.endsWith("[]")) {
            fieldName = fieldName.substring(0, fieldName.length() - 2);
        }
        Object[] array = (Object[]) fieldValue;
        Element arrayEle = parent.addElement(fieldName);
        String arryType = fieldClass.getName();
        arryType = arryType.substring(arryType.lastIndexOf("[") + 2, arryType.length() - 1);
        arrayEle.addAttribute(GlobalConstant.CLASS, GlobalConstant.ARRAY);
        arrayEle.addAttribute(GlobalConstant.ARRAY_TYPE, arryType);
        arrayEle.addAttribute(GlobalConstant.ARRAY_LENGTH, array.length + "");

        for (int i = 0; i < array.length; i++) {

            List<Field> arrFields = getPreferenceFieldList(array[i].getClass());
            if (arrFields.size() > 0) {

                Element child = arrayEle.addElement(getName(array[i].getClass()));
                child.addAttribute(GlobalConstant.CLASS, array[i].getClass().getName());
                for (int j = 0; j < arrFields.size(); j++) {
                    store(array[i], arrFields.get(j), child);
                }
            } else {
                store(array[i].getClass(), array[i].getClass().getSimpleName(), array[i], arrayEle,
                        adapterClass);
            }
        }

    } else if (fieldValue instanceof Collection) {
        Element lstEle = parent.addElement(fieldName);
        lstEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

        Collection coll = (Collection) fieldValue;
        Iterator iter = coll.iterator();
        while (iter.hasNext()) {
            Object item = iter.next();
            List<Field> lstFields = getPreferenceFieldList(item.getClass());
            if (lstFields.size() > 0) {

                Element child = lstEle.addElement(getName(item.getClass()));
                child.addAttribute(GlobalConstant.CLASS, item.getClass().getName());
                for (int j = 0; j < lstFields.size(); j++) {
                    store(item, lstFields.get(j), child);
                }
            } else {
                store(item.getClass(), item.getClass().getSimpleName(), item, lstEle, adapterClass);
            }
        }

    } else if (fieldValue instanceof Map) {

        Element mapEle = parent.addElement(fieldName);
        mapEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

        Map map = (Map) fieldValue;
        Iterator iter = map.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object value = map.get(key);
            Element keyEle = mapEle.addElement(GlobalConstant.KEY);
            keyEle.setText(key.toString());// Not suppert any adapter!
            keyEle.addAttribute(GlobalConstant.CLASS, key.getClass().getName());

            List<Field> vFields = getPreferenceFieldList(value.getClass());
            if (vFields.size() > 0) {

                Element valueEle = keyEle.addElement(getName(value.getClass()));
                valueEle.addAttribute(GlobalConstant.CLASS, value.getClass().getName());
                for (int j = 0; j < vFields.size(); j++) {
                    store(value, vFields.get(j), valueEle);
                }
            } else {
                store(value.getClass(), value.getClass().getSimpleName(), value, keyEle, adapterClass);
            }
        }

    } else {

        List<Field> pFields = getPreferenceFieldList(fieldValue.getClass());
        if (pFields.size() > 0) {
            Element child = parent.addElement(fieldName);
            child.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

            for (int i = 0; i < pFields.size(); i++) {
                store(fieldValue, pFields.get(i), child);
            }
        } else {
            Element attrEle = parent.addElement(fieldName);
            attrEle.setText(getValue(fieldValue, adapterClass));
            attrEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());
            if (adapterClass != DefaultPersistentAdapter.class) {
                attrEle.addAttribute(GlobalConstant.ADAPTER, adapterClass.getName());
            }
        }
    }
}

From source file:com.doculibre.constellio.izpack.UsersToXmlFile.java

License:Open Source License

public static void run(AbstractUIProcessHandler handler, String[] args) {
    if (args.length != 3) {
        System.out.println("file login password");
        return;//w ww  . j  a  va 2s . c  om
    }

    String target = args[0];

    File xmlFile = new File(target);

    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(xmlFile));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    try {
        for (String line : Arrays.asList(emptyFileLines)) {
            writer.write(line + System.getProperty("line.separator"));
        }

        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String login = args[1];

    String passwd = args[2];

    UsersToXmlFile elem = new UsersToXmlFile();

    ConstellioUser dataUser = elem.new ConstellioUser(login, passwd, null);
    dataUser.setFirstName("System");
    dataUser.setLastName("Administrator");
    dataUser.getRoles().add(Roles.ADMIN);

    Document xmlDocument;
    try {
        xmlDocument = new SAXReader().read(target);
        Element root = xmlDocument.getRootElement();

        BaseElement user = new BaseElement(USER);
        user.addAttribute(FIRST_NAME, dataUser.getFirstName());
        user.addAttribute(LAST_NAME, dataUser.getLastName());
        user.addAttribute(LOGIN, dataUser.getUsername());
        user.addAttribute(PASSWORD_HASH, dataUser.getPasswordHash());

        if (dataUser.getLocale() != null) {
            user.addAttribute(LOCALE, dataUser.getLocaleCode());
        }

        Set<String> constellioRoles = dataUser.getRoles();
        if (!constellioRoles.isEmpty()) {
            Element roles = user.addElement(ROLES);
            for (String constellioRole : constellioRoles) {
                Element role = roles.addElement(ROLE);
                role.addAttribute(VALUE, constellioRole);
            }
        }

        root.add(user);

        OutputFormat format = OutputFormat.createPrettyPrint();

        xmlFile = new File(target);
        // FIXME recrire la DTD
        // xmlDocument.addDocType(arg0, arg1, arg2)
        XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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 w ww  . j  a v a  2  s.  co  m
        }
    }

    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()));
    }/*w ww.  ja  v  a  2 s  .  c om*/
    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// www. j a  v  a  2 s.  co  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;
}

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

License:Open Source License

private void updateConfig(RecordCollection collection) {

    SolrConfig config = collection.getSolrConfiguration();
    SolrConfigServices solrConfigServices = ConstellioSpringUtils.getSolrConfigServices();
    SolrConfig defaultConfig = solrConfigServices.getDefaultConfig();

    if (config == null) {
        config = defaultConfig;/*w  w  w.j ava2s.c  om*/
    }
    ensureCore(collection);
    String collectionName = collection.getName();

    Document solrConfigDocument = readSolrConfig(collection);
    Element rootElement = solrConfigDocument.getRootElement();
    Element queryElement = rootElement.element("query");
    if (queryElement == null) {
        queryElement = rootElement.addElement("query");
    }
    updateNotNullConfigCache(queryElement, "fieldValueCache",
            (Cache) getPropertyValue(config, defaultConfig, "fieldValueCacheConfig"));
    updateNotNullConfigCache(queryElement, "filterCache",
            (Cache) getPropertyValue(config, defaultConfig, "filterCacheConfig"));
    updateNotNullConfigCache(queryElement, "queryResultCache",
            (Cache) getPropertyValue(config, defaultConfig, "queryResultCacheConfig"));
    updateNotNullConfigCache(queryElement, "documentCache",
            (Cache) getPropertyValue(config, defaultConfig, "documentCacheConfig"));

    addNotNullElement(queryElement, "useFilterForSortedQuery",
            getPropertyValue(config, defaultConfig, "useFilterForSortedQuery"));
    addNotNullElement(queryElement, "queryResultWindowSize",
            getPropertyValue(config, defaultConfig, "queryResultWindowSize"));
    Element hashDocSet = queryElement.element("HashDocSet");
    if (hashDocSet != null) {
        queryElement.remove(hashDocSet);
    }
    Object hashDocSetMaxSize = getPropertyValue(config, defaultConfig, "hashDocSetMaxSize");
    Object hashDocSetLoadFactor = getPropertyValue(config, defaultConfig, "hashDocSetLoadFactor");
    if (hashDocSetMaxSize != null || hashDocSetLoadFactor != null) {
        hashDocSet = queryElement.addElement("HashDocSet");
        addNotNullAttribute(hashDocSet, "maxSize", hashDocSetMaxSize);
        addNotNullAttribute(hashDocSet, "loadFactor", hashDocSetLoadFactor);
    }
    writeSolrConfig(collection, solrConfigDocument);
    initCore(collection);

}

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

License:Open Source License

private void updateNotNullConfigCache(Element rootElement, String cacheType, Cache cache) {
    removeAll(rootElement, cacheType);//  ww w  .  j  a  v a  2  s  . c  o m
    if (cache != null) {
        Element cacheElement = rootElement.addElement(cacheType);
        addNotNullAttribute(cacheElement, "class", cache.getCacheClass());
        addNotNullAttribute(cacheElement, "size", cache.getSize());
        addNotNullAttribute(cacheElement, "initialSize", cache.getInitialSize());
        addNotNullAttribute(cacheElement, "autowarmCount", cache.getAutowarmCount());
        addNotNullAttribute(cacheElement, "acceptableSize", cache.getAcceptableSize());
        addNotNullAttribute(cacheElement, "minSize", cache.getMinSize());
        addNotNullAttribute(cacheElement, "regenerator", cache.getRegeneratorClass());
        addNotNullAttribute(cacheElement, "cleanupThread", cache.isCleanupThread());
    }
}

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

License:Open Source License

private static Element addNotNullElement(Element element, String tag, Object content) {
    removeAll(element, tag);/*from   www.  j  a va 2  s .c o m*/
    if (content != null) {
        Element innerElement = element.addElement(tag);
        innerElement.setText(content.toString());
        return innerElement;
    }
    return null;
}

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

License:Open Source License

private Element getDismaxElement(RecordCollection collection) {
    BaseElement disMaxElement = new BaseElement("requestHandler");
    disMaxElement.addAttribute("name", DISMAX_ATTRIBUTE_NAME);
    disMaxElement.addAttribute("class", "solr.SearchHandler");
    disMaxElement.addAttribute("default", "true");

    Element lst = disMaxElement.addElement("lst");
    lst.addAttribute("name", "defaults");

    Element defType = lst.addElement("str");
    defType.addAttribute("name", "defType");
    defType.setText("edismax");// au lieu de "dismax" pour utiliser le
    // plugin//  www.j av a  2s. c o  m
    // :com.doculibre.constellio.solr.handler.component.DisMaxQParserPlugin

    Element qf = lst.addElement("str");
    qf.addAttribute("name", "qf");

    StringBuilder boostsDismaxField = new StringBuilder();
    for (IndexField current : collection.getIndexedIndexFields()) {
        if (current.getBoostDismax() != 1 || IndexField.DEFAULT_SEARCH_FIELD.equals(current.getName())) {
            boostsDismaxField.append(" " + current.getName() + "^" + current.getBoostDismax());
        }
    }
    qf.setText(boostsDismaxField.toString());

    Element tie = lst.addElement("float");
    tie.addAttribute("name", "tie");
    tie.setText("0.01");

    // <requestHandler name="dismax" class="solr.SearchHandler"
    // default="true">
    // <lst name="defaults">
    // <str name="defType">dismax</str>
    // <str name="qf">a_name a_alias^0.8 a_member_name^0.4</str>
    // <float name="tie">0.1</float>
    // </lst>
    // </requestHandler>

    return disMaxElement;
}