Example usage for org.dom4j Element add

List of usage examples for org.dom4j Element add

Introduction

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

Prototype

void add(Namespace namespace);

Source Link

Document

Adds the given Namespace to this element.

Usage

From source file:com.cladonia.xngreditor.actions.ToolsConvertNodeAction.java

License:Open Source License

/**
 * add one of various types of node to the xpath - selected nodes
 * //from  w  w w .j  a  v  a2s  .  c om
 * @param document
 * @param xpathPredicate
 * @param nodeType
 * @return
 */
public String convertNode(ExchangerDocument document, String xpathPredicate, String nodeType) {

    Vector nodeList = document.search(xpathPredicate);
    Vector attributeList = new Vector();
    String warning = "";
    if (nodeList.size() > 0) {
        try {
            for (int cnt = 0; cnt < nodeList.size(); ++cnt) {
                Node node = (Node) nodeList.get(cnt);
                if (node instanceof Element) {
                    XElement e = (XElement) node;
                    Element parentE = e.getParent();
                    if ((e.hasChildElements()) || (e.attributeCount() > 0)) {
                        if ((e.hasChildElements())) {
                            MessageHandler.showError(parent, "Cannont convert since node has child elements ",
                                    "Tools Convert Node Error");
                            return (null);
                        } else if (e.attributeCount() > 0) {
                            MessageHandler.showError("Cannont convert since node has attributes",
                                    "Tools Convert Node Error");
                            return (null);
                        }
                        cnt = nodeList.size();

                    } else {
                        if (nodeType.equalsIgnoreCase("Element Node")) {
                            MessageHandler.showError(parent, "Node is already an Element",
                                    "Tools Convert Node Error");
                            //end loop
                            cnt = nodeList.size();
                            return (null);
                        } else if (nodeType.equalsIgnoreCase("Attribute Node")) {
                            //check if it has child elements
                            QName qname = e.getQName();
                            //resolve the namespace string
                            parentE.add(new XAttribute(qname, e.getValue()));
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Text Node")) {
                            FlyweightText newNode = new FlyweightText(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("CDATA Section Node")) {
                            FlyweightCDATA newNode = new FlyweightCDATA(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Processing Instruction Node")) {
                            FlyweightProcessingInstruction newNode = new FlyweightProcessingInstruction(
                                    e.getText(), "");
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Comment Node")) {
                            FlyweightComment newNode = new FlyweightComment(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        }
                    }
                } else if (node instanceof Attribute) {
                    XAttribute e = (XAttribute) node;
                    Element parentE = e.getParent();
                    if (nodeType.equalsIgnoreCase("Element Node")) {
                        QName qname = e.getQName();
                        //resolve the namespace string
                        XElement newE = new XElement(qname);
                        parentE.add(newE);
                        newE.setValue(e.getValue());
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Attribute Node")) {
                        MessageHandler.showError(parent, "Node is already an Attribute",
                                "Tools Convert Node Error");
                        //end loop
                        cnt = nodeList.size();
                        return (null);
                    } else if (nodeType.equalsIgnoreCase("Text Node")) {
                        FlyweightText newNode = new FlyweightText(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("CDATA Section Node")) {
                        FlyweightCDATA newNode = new FlyweightCDATA(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Processing Instruction Node")) {
                        FlyweightProcessingInstruction newNode = new FlyweightProcessingInstruction(e.getText(),
                                "");
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Comment Node")) {
                        FlyweightComment newNode = new FlyweightComment(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    }
                } else {
                    //can only handle elements
                    MessageHandler
                            .showError(parent,
                                    "Can only Convert Nodes to elements\n+" + "XPath: " + xpathPredicate
                                            + "refers to a" + node.getNodeTypeName(),
                                    "Tools Convert Node Error");
                    //end for loop
                    cnt = nodeList.size();
                }
            }
        } catch (NullPointerException e) {
            MessageHandler.showError(parent, "XPath: " + xpathPredicate + "\nCannot be resolved",
                    "Tools Convert Node Error");
            return (null);
        } catch (Exception e) {
            MessageHandler.showError(parent, "Error Adding Node", "Tools Convert Node Error");
            return (null);
        }
        document.update();
    } else {
        MessageHandler.showError(parent, "No nodes could be found for:\n" + xpathPredicate,
                "Tools Convert Node Error");
        return (null);
    }
    return (document.getText());
}

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

/**
 * ?????XML//from  www  .j  a  v a2 s.  com
 **/
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.devoteam.srit.xmlloader.master.master.utils.DataMaster.java

License:Open Source License

private void parse() throws Exception {
    this.testDatas = new LinkedList<DataTest>();

    List<Element> parametersMaster = (List<Element>) root.elements("parameter");

    /* Duplicate the parameter elements from the <master> level and copy
     * them at the begining of the <test> element, before the <test>
     * element's own parameter elements.
     *///from w ww. ja  v a  2  s.  c  o  m
    List<Element> tests = (List<Element>) root.elements("test");
    for (Element test : tests) {
        List<Element> parametersTest = (List<Element>) test.elements("parameter");
        for (Element parameter : parametersTest) {
            test.remove(parameter);
        }

        for (Element parameter : parametersMaster) {
            test.add(parameter.createCopy());
        }

        for (Element parameter : parametersTest) {
            test.add(parameter);
        }

        testDatas.add(new DataTest(test, this.xmlDocument.getXMLFile()));
    }

    //
    // Test for TestData names uniqueness
    HashSet hashSet = new HashSet();
    for (DataTest testData : testDatas) {
        if (hashSet.contains(testData.getName())) {
            throw new Exception("Test name should be unique (" + testData.getName() + ").");
        } else {
            hashSet.add(testData.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 v  a 2 s . 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.ElevateServicesImpl.java

License:Open Source License

private Element buildQueryElementFromCache(String queryText, String queryDisplayText, String collectionName) {
    Element queryElement;

    Map<String, List<String>> solrCoreElevationCache = elevationCache.get(collectionName);
    List<String> queryElevationCache = solrCoreElevationCache.get(queryText);

    Map<String, List<String>> solrCoreExclusionCache = exclusionCache.get(collectionName);
    List<String> queryExclusionCache = solrCoreExclusionCache.get(queryText);

    if ((queryElevationCache != null && !queryElevationCache.isEmpty())
            || (queryExclusionCache != null && !queryExclusionCache.isEmpty())) {
        queryElement = DocumentHelper.createElement("query");
        queryElement.addAttribute("text", queryText);
        queryElement.addAttribute("displayText", queryDisplayText);
        if (queryElevationCache != null) {
            for (String elevatedDocId : queryElevationCache) {
                Element docElement = DocumentHelper.createElement("doc");
                docElement.addAttribute("id", elevatedDocId);
                queryElement.add(docElement);
            }//from w  w  w.  ja  v  a 2s.co  m
        }

        if (queryExclusionCache != null) {
            for (String excludedDocId : queryExclusionCache) {
                Element docElement = DocumentHelper.createElement("doc");
                docElement.addAttribute("id", excludedDocId);
                docElement.addAttribute("exclude", "true");
                queryElement.add(docElement);
            }
        }
    } else {
        queryElement = null;
    }
    return queryElement;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private synchronized void replaceQueryElement(String queryText, Element newQueryElement,
        String collectionName) {//w w  w  .  j ava2s  .c o m
    Document document = SolrServicesImpl.readXMLConfigInCloud(collectionName, "elevate.xml");
    Element rootElement = document.getRootElement();
    int beanNodeIndex = -1;
    int i = 0;
    for (Node rootContent : (List<Node>) rootElement.content()) {
        if (rootContent instanceof Element) {
            Element possibleBeanElement = (Element) rootContent;
            if (queryText.equals(possibleBeanElement.attributeValue("text"))) {
                beanNodeIndex = i;
                break;
            }
        }
        i++;
    }

    if (beanNodeIndex != -1) {
        if (newQueryElement != null) {
            rootElement.content().set(beanNodeIndex, newQueryElement);
        } else {
            rootElement.content().remove(beanNodeIndex);
        }
    } else if (newQueryElement != null) {
        rootElement.add(newQueryElement);
    }

    // lets write to a file
    SolrServicesImpl.writeXMLConfigInCloud(collectionName, "elevate.xml", document);
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private void updateSchemaFields(RecordCollection collection, Document schemaDocument) {
    Element fieldsElement = schemaDocument.getRootElement().element("fields");
    List<Element> fieldElements = fieldsElement.elements("field");
    for (Iterator<Element> it = fieldElements.iterator(); it.hasNext();) {
        it.next();//w w  w  . java  2 s. com
        it.remove();
    }

    List<Element> copyFields = schemaDocument.getRootElement().elements("copyField");
    for (Iterator<Element> it = copyFields.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<Element> dynamicFieldElements = fieldsElement.elements("dynamicField");
    for (Iterator<Element> it = dynamicFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<String> addedFieldNames = new ArrayList<String>();
    Collection<IndexField> indexFields = collection.getIndexFields();
    for (IndexField indexField : indexFields) {
        if (!addedFieldNames.contains(indexField.getName())) {
            addedFieldNames.add(indexField.getName());

            FieldType fieldType = indexField.getFieldType();
            Analyzer analyzer = indexField.getAnalyzer();
            if (fieldType == null) {
                throw new RuntimeException(indexField.getName() + " has no type");
            }
            Element fieldElement;
            if (indexField.isDynamicField()) {
                fieldElement = DocumentHelper.createElement("dynamicField");
            } else {
                fieldElement = DocumentHelper.createElement("field");
            }
            fieldsElement.add(fieldElement);
            addNotNullAttribute(fieldElement, "name", indexField.getName());
            addNotNullAttribute(fieldElement, "type", fieldType.getName());
            addNotNullAttribute(fieldElement, "indexed", indexField.isIndexed());
            addNotNullAttribute(fieldElement, "stored", true);
            addNotNullAttribute(fieldElement, "multiValued", indexField.isMultiValued());
            if (analyzer != null) {
                fieldElement.addAttribute("analyzer", analyzer.getAnalyzerClass().getClassName());
            }
        }
    }

    // used by solrcloud
    Element fieldElement = DocumentHelper.createElement("field");
    addNotNullAttribute(fieldElement, "name", "_version_");
    addNotNullAttribute(fieldElement, "type", "long");
    addNotNullAttribute(fieldElement, "indexed", true);
    addNotNullAttribute(fieldElement, "stored", true);
    fieldsElement.add(fieldElement);

    List<Element> uniqueKeyElements = schemaDocument.getRootElement().elements("uniqueKey");
    for (Iterator<Element> it = uniqueKeyElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
    if (uniqueKeyField != null) {
        Element uniqueKeyElement = DocumentHelper.createElement("uniqueKey");
        uniqueKeyElement.setText(uniqueKeyField.getName());
        schemaDocument.getRootElement().add(uniqueKeyElement);
    }

    List<Element> defaultSearchFieldElements = schemaDocument.getRootElement().elements("defaultSearchField");
    for (Iterator<Element> it = defaultSearchFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField defaultSearchField = collection.getDefaultSearchIndexField();
    if (defaultSearchField != null) {
        Element defaultSearchFieldElement = DocumentHelper.createElement("defaultSearchField");
        defaultSearchFieldElement.setText(defaultSearchField.getName());
        schemaDocument.getRootElement().add(defaultSearchFieldElement);
    }

    List<Element> solrQueryParserElements = schemaDocument.getRootElement().elements("solrQueryParser");
    for (Iterator<Element> it = solrQueryParserElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    String queryParserOperator = collection.getQueryParserOperator();
    if (queryParserOperator != null) {
        Element solrQueryParserElement = DocumentHelper.createElement("solrQueryParser");
        solrQueryParserElement.addAttribute("defaultOperator", queryParserOperator);
        schemaDocument.getRootElement().add(solrQueryParserElement);
    }

    for (IndexField indexField : indexFields) {
        if (!indexField.isDynamicField()) {
            for (CopyField copyFieldDest : indexField.getCopyFieldsDest()) {
                Element copyFieldElement = DocumentHelper.createElement("copyField");
                String source;
                if (copyFieldDest.isSourceAllFields()) {
                    source = "*";
                } else {
                    IndexField indexFieldSource = copyFieldDest.getIndexFieldSource();
                    source = indexFieldSource.getName();
                }
                copyFieldElement.addAttribute("source", source);
                copyFieldElement.addAttribute("dest", copyFieldDest.getIndexFieldDest().getName());
                addNotNullAttribute(copyFieldElement, "maxChars", copyFieldDest);
                // Ajout Rida
                schemaDocument.getRootElement().add(copyFieldElement);
            }
        }
    }

    writeSchema(collection.getName(), schemaDocument);
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  ww  w . j a v  a  2 s. c o  m*/
public void updateSchemaFieldTypes(RecordCollection collection) {
    String collectionName = SolrCoreContext.DEFAULT_COLLECTION_NAME;
    if (collection != null) {
        collectionName = collection.getName();
    }
    Document schemaDocument = readSchema(collectionName);
    Element typesElement = schemaDocument.getRootElement().element("types");
    List<Element> fieldTypeElements = typesElement.elements("fieldType");
    for (Iterator<Element> it = fieldTypeElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    FieldTypeServices fieldTypeServices = ConstellioSpringUtils.getFieldTypeServices();
    for (FieldType fieldType : fieldTypeServices.list()) {
        Element fieldTypeElement = DocumentHelper.createElement("fieldType");
        typesElement.add(fieldTypeElement);
        FieldTypeClass fieldTypeClass = fieldType.getFieldTypeClass();

        addNotNullAttribute(fieldTypeElement, "name", fieldType);
        addNotNullAttribute(fieldTypeElement, "class", fieldTypeClass.getClassName());
        addNotNullAttribute(fieldTypeElement, "indexed", fieldType);
        // Always true
        addNotNullAttribute(fieldTypeElement, "stored", true);
        addNotNullAttribute(fieldTypeElement, "multiValued", fieldType);
        addNotNullAttribute(fieldTypeElement, "omitNorms", fieldType);
        addNotNullAttribute(fieldTypeElement, "precisionStep", fieldType);
        addNotNullAttribute(fieldTypeElement, "positionIncrementGap", fieldType);
        addNotNullAttribute(fieldTypeElement, "sortMissingLast", fieldType);

        Analyzer analyzer = fieldType.getAnalyzer();
        Analyzer queryAnalyzer = fieldType.getQueryAnalyzer();

        if (analyzer != null) {
            Element analyzerElement = DocumentHelper.createElement("analyzer");
            fieldTypeElement.add(analyzerElement);
            if (queryAnalyzer != null) {
                analyzerElement.addAttribute("type", "index");
            }

            AnalyzerClass analyzerClass = analyzer.getAnalyzerClass();
            if (analyzerClass != null) {
                analyzerElement.addAttribute("class", analyzerClass.getClassName());
            }

            TokenizerClass tokenizerClass = analyzer.getTokenizerClass();
            if (tokenizerClass != null) {
                Element tokenizerElement = DocumentHelper.createElement("tokenizer");
                analyzerElement.add(tokenizerElement);
                tokenizerElement.addAttribute("class", tokenizerClass.getClassName());
            }

            Collection<AnalyzerFilter> filters = analyzer.getFilters();
            for (AnalyzerFilter filter : filters) {
                FilterClass filterClass = filter.getFilterClass();
                Element filterElement = DocumentHelper.createElement("filter");
                analyzerElement.add(filterElement);
                filterElement.addAttribute("class", filterClass.getClassName());
                addNotNullAttribute(filterElement, "catenateAll", filter);
                addNotNullAttribute(filterElement, "catenateWords", filter);
                addNotNullAttribute(filterElement, "delimiter", filter);
                addNotNullAttribute(filterElement, "enablePositionIncrements", filter);
                addNotNullAttribute(filterElement, "encoder", filter);
                addNotNullAttribute(filterElement, "expand", filter);
                addNotNullAttribute(filterElement, "generateNumberParts", filter);
                addNotNullAttribute(filterElement, "generateWordParts", filter);
                addNotNullAttribute(filterElement, "ignoreCase", filter);
                addNotNullAttribute(filterElement, "inject", filter);
                addNotNullAttribute(filterElement, "language", filter);
                addNotNullAttribute(filterElement, "pattern", filter);
                if (filter.getProtectedText() != null) {
                    filterElement.addAttribute("protected", filter.getProtectedText());
                }
                addNotNullAttribute(filterElement, "replace", filter);
                addNotNullAttribute(filterElement, "replacement", filter);
                addNotNullAttribute(filterElement, "splitOnCaseChange", filter);
                if (filter.getSynonymsText() != null) {
                    filterElement.addAttribute("synonyms", filter.getSynonymsText());
                }
                if (filter.getWordsText() != null) {
                    filterElement.addAttribute("words", filter.getWordsText());
                }
            }
        }

        if (queryAnalyzer != null) {
            Element analyzerElement = DocumentHelper.createElement("analyzer");
            fieldTypeElement.add(analyzerElement);
            analyzerElement.addAttribute("type", "query");

            AnalyzerClass analyzerClass = queryAnalyzer.getAnalyzerClass();
            if (analyzerClass != null) {
                analyzerElement.addAttribute("class", analyzerClass.getClassName());
            }

            TokenizerClass tokenizerClass = queryAnalyzer.getTokenizerClass();
            if (tokenizerClass != null) {
                Element tokenizerElement = DocumentHelper.createElement("tokenizer");
                analyzerElement.add(tokenizerElement);
                tokenizerElement.addAttribute("class", tokenizerClass.getClassName());
            }

            Collection<AnalyzerFilter> filters = queryAnalyzer.getFilters();
            for (AnalyzerFilter filter : filters) {
                FilterClass filterClass = filter.getFilterClass();
                Element filterElement = DocumentHelper.createElement("filter");
                analyzerElement.add(filterElement);
                filterElement.addAttribute("class", filterClass.getClassName());
                addNotNullAttribute(filterElement, "catenateAll", filter);
                addNotNullAttribute(filterElement, "catenateWords", filter);
                addNotNullAttribute(filterElement, "delimiter", filter);
                addNotNullAttribute(filterElement, "enablePositionIncrements", filter);
                addNotNullAttribute(filterElement, "encoder", filter);
                addNotNullAttribute(filterElement, "expand", filter);
                addNotNullAttribute(filterElement, "generateNumberParts", filter);
                addNotNullAttribute(filterElement, "generateWordParts", filter);
                addNotNullAttribute(filterElement, "ignoreCase", filter);
                addNotNullAttribute(filterElement, "inject", filter);
                addNotNullAttribute(filterElement, "language", filter);
                addNotNullAttribute(filterElement, "pattern", filter);
                if (filter.getProtectedText() != null) {
                    filterElement.addAttribute("protected", filter.getProtectedText());
                }
                addNotNullAttribute(filterElement, "replace", filter);
                addNotNullAttribute(filterElement, "replacement", filter);
                addNotNullAttribute(filterElement, "splitOnCaseChange", filter);
                if (filter.getSynonymsText() != null) {
                    filterElement.addAttribute("synonyms", filter.getSynonymsText());
                }
                if (filter.getWordsText() != null) {
                    filterElement.addAttribute("words", filter.getWordsText());
                }
            }
        }
    }
    writeSchema(collectionName, schemaDocument);
    if (collection != null) {
        // for _default_constellio, we do not need initialize
        initCore(collection);
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* w  ww .  j a v a  2s.co  m*/
public void updateDismax(RecordCollection collection) {
    ensureCore(collection);

    Element dismaxElement = getDismaxElement(collection);
    Document solrConfigDocument = readSolrConfig(collection);
    Element root = solrConfigDocument.getRootElement();

    boolean defaultSearchFieldFound = false;
    // 1. keep only one requestHandler with name DISMAX_ATTRIBUTE_NAME
    for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) {
        Element currentRequestHandlerElement = it.next();
        String currentSearchComponentName = currentRequestHandlerElement.attribute("name").getText();
        if (currentSearchComponentName.equals(DISMAX_ATTRIBUTE_NAME)) {
            // first copy other fields that are not defaults if the
            // query was set as default
            if (!defaultSearchFieldFound) {
                Attribute defaultAttribute = currentRequestHandlerElement.attribute("default");
                if (defaultAttribute != null && defaultAttribute.getText().equals("true")) {
                    defaultSearchFieldFound = true;
                    defaultAttribute.setText("false");
                    List<Element> elements = currentRequestHandlerElement.elements();
                    for (Element element : elements) {
                        if (element.attribute("name") != null
                                && !element.attribute("name").getValue().equals("defaults")) {
                            BaseElement cloneElement = new BaseElement(element.getName());
                            cloneElement.appendAttributes(element);
                            cloneElement.appendContent(element);
                            dismaxElement.add(cloneElement);
                        }
                    }
                }
            }
            it.remove();
        }
    }
    if (!defaultSearchFieldFound) {
        // 2. add the parameters of the default RequestHandler to dismax
        // requestHandler (escape the parameter with name="defaults")
        for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) {
            Element currentRequestHandlerElement = it.next();
            Attribute defaultAttribute = currentRequestHandlerElement.attribute("default");
            if (defaultAttribute != null && defaultAttribute.getText().equals("true")) {
                defaultAttribute.setText("false");
                List<Element> elements = currentRequestHandlerElement.elements();
                for (Element element : elements) {
                    if (element.attribute("name") != null
                            && !element.attribute("name").getValue().equals("defaults")) {
                        BaseElement cloneElement = new BaseElement(element.getName());
                        cloneElement.appendAttributes(element);
                        cloneElement.appendContent(element);
                        dismaxElement.add(cloneElement);
                    }
                }
                break;
            }
        }
    }

    root.add(dismaxElement);

    writeSolrConfig(collection, solrConfigDocument);
    initCore(collection);
}

From source file:com.doculibre.constellio.utils.izpack.UsersXmlFileUtils.java

License:Open Source License

public static void addUserTo(ConstellioUser constellioUser, String fileName) {
    Document xmlDocument;//from   w  ww.j a va 2 s . com
    try {
        xmlDocument = new SAXReader().read(fileName);
        Element root = xmlDocument.getRootElement();

        Element user = toXmlElement(constellioUser);
        root.add(user);

        OutputFormat format = OutputFormat.createPrettyPrint();

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

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

}