Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

License:Open Source License

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }/*  w  ww  .j  a  va 2  s.  c o m*/

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private synchronized void readCache(String collectionName) {
    Map<String, List<String>> solrCoreElevationCache = elevationCache.get(collectionName);
    if (solrCoreElevationCache == null) {
        solrCoreElevationCache = new HashMap<String, List<String>>();
        elevationCache.put(collectionName, solrCoreElevationCache);

        Map<String, List<String>> solrCoreExclusionCache = new HashMap<String, List<String>>();
        exclusionCache.put(collectionName, solrCoreExclusionCache);

        Document document = SolrServicesImpl.readXMLConfigInCloud(collectionName, "elevate.xml");

        Element rootElement = document.getRootElement();
        for (Element queryElement : (List<Element>) rootElement.elements("query")) {
            String queryText = queryElement.attributeValue("text");
            String queryDisplayText = queryElement.attributeValue("displayText");
            if (queryDisplayText != null && displayQueriesCache.get(queryText) == null) {
                displayQueriesCache.put(queryText, queryDisplayText);
            }/*from   w  w w .  j a  v a  2  s. c  om*/

            List<String> elevatedDocIds = new ArrayList<String>();
            List<String> excludedDocIds = new ArrayList<String>();

            for (Element docElement : (List<Element>) queryElement.elements("doc")) {
                String docId = docElement.attributeValue("id");
                if ("true".equals(docElement.attributeValue("exclude"))) {
                    excludedDocIds.add(docId);
                } else {
                    elevatedDocIds.add(docId);
                }
            }
            if (!elevatedDocIds.isEmpty()) {
                solrCoreElevationCache.put(queryText, elevatedDocIds);
            }
            if (!excludedDocIds.isEmpty()) {
                solrCoreExclusionCache.put(queryText, excludedDocIds);
            }
        }
    }
}

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) {/* ww  w.j  a v  a 2 s  . c  om*/
    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

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 a v a  2 s  .c  o  m*/
    }
    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

@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.  j a v a2 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  . jav a2 s .c om
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//from  w  w w. ja  v  a 2  s  . c  o m
public synchronized void initConnectorTypeFields() {
    ConnectorTypeServices connectorTypeServices = ConstellioSpringUtils.getConnectorTypeServices();
    FieldTypeServices fieldTypeServices = ConstellioSpringUtils.getFieldTypeServices();
    AnalyzerClassServices analyzerClassServices = ConstellioSpringUtils.getAnalyzerClassServices();

    for (ConnectorType connectorType : connectorTypeServices.list()) {
        Collection<ConnectorTypeMetaMapping> connectorTypeMetaMappings = connectorType.getMetaMappings();
        if (connectorTypeMetaMappings.isEmpty()) {
            File connectorsDir = ConstellioSpringUtils.getGoogleConnectorsDir();
            File connectorTypeDir = new File(connectorsDir, connectorType.getName());
            File schemaFile = new File(connectorTypeDir, "schema.xml");

            // // we must ensure that collection with the name of
            // connectorType
            // // exists in solrcloud
            // Document schemaDocument =
            // readSchema(connectorType.getName());
            if (schemaFile.exists()) {
                Document schemaDocument = readSchema(schemaFile);
                if (schemaDocument != null) {
                    String defaultUniqueKeyName = "id";
                    String uniqueKeyFieldName = defaultUniqueKeyName;
                    Element uniqueKeyElement = schemaDocument.getRootElement().element("uniqueKey");
                    if (uniqueKeyElement != null) {
                        uniqueKeyFieldName = uniqueKeyElement.getText();
                    }

                    String defaultSearchFieldName;
                    Element defaultSearchFieldElement = schemaDocument.getRootElement()
                            .element("defaultSearchField");
                    if (defaultSearchFieldElement != null) {
                        defaultSearchFieldName = defaultSearchFieldElement.getText();
                    } else {
                        defaultSearchFieldName = null;
                    }

                    Element fieldsElement = schemaDocument.getRootElement().element("fields");
                    List<Element> fieldElements = fieldsElement.elements("field");
                    for (Iterator<Element> it = fieldElements.iterator(); it.hasNext();) {
                        Element fieldElement = it.next();

                        ConnectorTypeMetaMapping connectorTypeMetaMapping = new ConnectorTypeMetaMapping();
                        connectorType.addMetaMapping(connectorTypeMetaMapping);

                        String metaName = fieldElement.attributeValue("name");
                        connectorTypeMetaMapping.setMetaName(metaName);
                        if (metaName.equals(uniqueKeyFieldName)) {
                            connectorTypeMetaMapping.setUniqueKey(true);
                        }

                        if (defaultSearchFieldName != null && metaName.equals(defaultSearchFieldName)) {
                            connectorTypeMetaMapping.setDefaultSearchField(true);
                        }

                        String indexFieldName = IndexField.normalize(metaName);
                        connectorTypeMetaMapping.setIndexFieldName(indexFieldName);

                        setProperty(fieldElement, "indexed", connectorTypeMetaMapping);
                        // Defaults to true
                        // setProperty(fieldElement, "stored",
                        // connectorTypeMetaMapping);
                        setProperty(fieldElement, "multiValued", connectorTypeMetaMapping);

                        String analyzerClassName = fieldElement.attributeValue("analyzer");
                        if (analyzerClassName != null) {
                            AnalyzerClass analyzerClass = analyzerClassServices.get(analyzerClassName);
                            if (analyzerClass == null) {
                                analyzerClass = new AnalyzerClass();
                                analyzerClass.setClassName(analyzerClassName);
                                analyzerClassServices.makePersistent(analyzerClass, false);
                            }
                            Analyzer analyzer = new Analyzer();
                            analyzer.setAnalyzerClass(analyzerClass);
                            connectorTypeMetaMapping.setAnalyzer(analyzer);
                        }

                        String typeName = fieldElement.attributeValue("type");
                        FieldType fieldType = fieldTypeServices.get(typeName);
                        if (fieldType != null) {
                            connectorTypeMetaMapping.setFieldType(fieldType);
                            if (fieldType.getIndexed() != null) {
                                connectorTypeMetaMapping.setIndexed(fieldType.getIndexed());
                            }
                            if (fieldType.getMultiValued() != null) {
                                connectorTypeMetaMapping.setMultiValued(fieldType.getMultiValued());
                            }
                        }
                    }
                }
            }
        }
    }
}

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

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Boolean createMissingFieldTypes(Document schemaDocument) {
    Boolean newFielTypes = false;
    FieldTypeServices fieldTypeServices = ConstellioSpringUtils.getFieldTypeServices();
    ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils.getConnectorManagerServices();
    FieldTypeClassServices fieldTypeClassServices = ConstellioSpringUtils.getFieldTypeClassServices();
    FilterClassServices filterClassServices = ConstellioSpringUtils.getFilterClassServices();
    TokenizerClassServices tokenizerClassServices = ConstellioSpringUtils.getTokenizerClassServices();
    AnalyzerClassServices analyzerClassServices = ConstellioSpringUtils.getAnalyzerClassServices();

    ConnectorManager connectorManager = connectorManagerServices.getDefaultConnectorManager();

    Element typesElement = schemaDocument.getRootElement().element("types");
    if (typesElement != null) {
        List<Element> fieldTypeElements = typesElement.elements("fieldType");
        for (Element fieldTypeElement : fieldTypeElements) {
            String name = fieldTypeElement.attributeValue("name");
            FieldType fieldType = fieldTypeServices.get(name);
            if (fieldType == null) {
                newFielTypes = true;/*  w  w  w . ja  va2  s  .  c  o m*/
                fieldType = new FieldType();
                fieldType.setName(name);

                String fieldTypeClassName = fieldTypeElement.attributeValue("class");
                FieldTypeClass fieldTypeClass = fieldTypeClassServices.get(fieldTypeClassName);
                if (fieldTypeClass == null) {
                    fieldTypeClass = new FieldTypeClass();
                    fieldTypeClass.setClassName(fieldTypeClassName);
                    fieldTypeClass.setConnectorManager(connectorManager);
                    fieldTypeClassServices.makePersistent(fieldTypeClass);
                }
                fieldType.setFieldTypeClass(fieldTypeClass);
                fieldType.setConnectorManager(connectorManager);

                setProperty(fieldTypeElement, "indexed", fieldType);
                // Always true
                // setProperty(fieldTypeElement, "stored", fieldType);
                setProperty(fieldTypeElement, "multiValued", fieldType);
                setProperty(fieldTypeElement, "omitNorms", fieldType);
                setProperty(fieldTypeElement, "precisionStep", fieldType);
                setProperty(fieldTypeElement, "positionIncrementGap", fieldType);
                setProperty(fieldTypeElement, "sortMissingLast", fieldType);

                List<Element> analyzerElements = fieldTypeElement.elements("analyzer");
                Element analyzerElement = null;
                Element queryAnalyzerElement = null;
                for (Element element : analyzerElements) {
                    String type = element.attributeValue("type");
                    if (type == null || type.equals("index")) {
                        analyzerElement = element;
                    } else if (type.equals("query")) {
                        queryAnalyzerElement = element;
                    }
                }

                if (analyzerElement != null) {
                    Analyzer analyzer = new Analyzer();
                    fieldType.setAnalyzer(analyzer);

                    String analyzerClassName = analyzerElement.attributeValue("class");
                    if (analyzerClassName != null) {
                        AnalyzerClass analyzerClass = analyzerClassServices.get(analyzerClassName);
                        if (analyzerClass == null) {
                            analyzerClass = new AnalyzerClass();
                            analyzerClass.setClassName(analyzerClassName);
                            analyzerClass.setConnectorManager(connectorManager);
                            analyzerClassServices.makePersistent(analyzerClass, false);
                        }
                        analyzer.setAnalyzerClass(analyzerClass);
                    }

                    Element tokenizerElement = analyzerElement.element("tokenizer");
                    if (tokenizerElement != null) {
                        String tokenizerClassName = tokenizerElement.attributeValue("class");
                        TokenizerClass tokenizerClass = tokenizerClassServices.get(tokenizerClassName);
                        if (tokenizerClass == null) {
                            tokenizerClass = new TokenizerClass();
                            tokenizerClass.setClassName(tokenizerClassName);
                            tokenizerClass.setConnectorManager(connectorManager);
                            tokenizerClassServices.makePersistent(tokenizerClass, false);
                        }
                        analyzer.setTokenizerClass(tokenizerClass);
                    }

                    for (Element filterElement : (List<Element>) analyzerElement.elements("filter")) {
                        AnalyzerFilter filter = new AnalyzerFilter();
                        filter.setAnalyzer(analyzer);
                        analyzer.getFilters().add(filter);

                        String filterClassName = filterElement.attributeValue("class");
                        FilterClass filterClass = filterClassServices.get(filterClassName);
                        if (filterClass == null) {
                            filterClass = new FilterClass();
                            filterClass.setClassName(filterClassName);
                            filterClass.setConnectorManager(connectorManager);
                            filterClassServices.makePersistent(filterClass);
                        }
                        filter.setFilterClass(filterClass);

                        setProperty(filterElement, "catenateAll", filter);
                        setProperty(filterElement, "catenateWords", filter);
                        setProperty(filterElement, "delimiter", filter);
                        setProperty(filterElement, "enablePositionIncrements", filter);
                        setProperty(filterElement, "encoder", filter);
                        setProperty(filterElement, "expand", filter);
                        setProperty(filterElement, "generateNumberParts", filter);
                        setProperty(filterElement, "generateWordParts", filter);
                        setProperty(filterElement, "ignoreCase", filter);
                        setProperty(filterElement, "inject", filter);
                        setProperty(filterElement, "language", filter);
                        setProperty(filterElement, "pattern", filter);
                        if (filterElement.attribute("protected") != null) {
                            filter.setProtectedText(filterElement.attributeValue("protected"));
                        }
                        setProperty(filterElement, "replace", filter);
                        setProperty(filterElement, "replacement", filter);
                        setProperty(filterElement, "splitOnCaseChange", filter);
                        if (filterElement.attribute("synonyms") != null) {
                            filter.setSynonymsText(filterElement.attributeValue("synonyms"));
                        }
                        if (filterElement.attribute("words") != null) {
                            filter.setWordsText(filterElement.attributeValue("words"));
                        }
                    }
                }

                if (queryAnalyzerElement != null) {
                    Analyzer queryAnalyzer = new Analyzer();
                    fieldType.setQueryAnalyzer(queryAnalyzer);

                    String analyzerClassName = queryAnalyzerElement.attributeValue("class");
                    if (analyzerClassName != null) {
                        AnalyzerClass analyzerClass = analyzerClassServices.get(analyzerClassName);
                        if (analyzerClass == null) {
                            analyzerClass = new AnalyzerClass();
                            analyzerClass.setClassName(analyzerClassName);
                            analyzerClass.setConnectorManager(connectorManager);
                            analyzerClassServices.makePersistent(analyzerClass, false);
                        }
                        queryAnalyzer.setAnalyzerClass(analyzerClass);
                    }

                    Element tokenizerElement = queryAnalyzerElement.element("tokenizer");
                    if (tokenizerElement != null) {
                        String tokenizerClassName = tokenizerElement.attributeValue("class");
                        TokenizerClass tokenizerClass = tokenizerClassServices.get(tokenizerClassName);
                        if (tokenizerClass == null) {
                            tokenizerClass = new TokenizerClass();
                            tokenizerClass.setClassName(tokenizerClassName);
                            tokenizerClass.setConnectorManager(connectorManager);
                            tokenizerClassServices.makePersistent(tokenizerClass, false);
                        }
                        queryAnalyzer.setTokenizerClass(tokenizerClass);
                    }

                    for (Element filterElement : (List<Element>) queryAnalyzerElement.elements("filter")) {
                        AnalyzerFilter filter = new AnalyzerFilter();
                        filter.setAnalyzer(queryAnalyzer);
                        queryAnalyzer.getFilters().add(filter);

                        String filterClassName = filterElement.attributeValue("class");
                        FilterClass filterClass = filterClassServices.get(filterClassName);
                        if (filterClass == null) {
                            filterClass = new FilterClass();
                            filterClass.setClassName(filterClassName);
                            filterClass.setConnectorManager(connectorManager);
                            filterClassServices.makePersistent(filterClass);
                        }
                        filter.setFilterClass(filterClass);

                        setProperty(filterElement, "catenateAll", filter);
                        setProperty(filterElement, "catenateWords", filter);
                        setProperty(filterElement, "delimiter", filter);
                        setProperty(filterElement, "enablePositionIncrements", filter);
                        setProperty(filterElement, "encoder", filter);
                        setProperty(filterElement, "expand", filter);
                        setProperty(filterElement, "generateNumberParts", filter);
                        setProperty(filterElement, "generateWordParts", filter);
                        setProperty(filterElement, "ignoreCase", filter);
                        setProperty(filterElement, "inject", filter);
                        setProperty(filterElement, "language", filter);
                        setProperty(filterElement, "pattern", filter);
                        if (filterElement.attribute("protected") != null) {
                            filter.setProtectedText(filterElement.attributeValue("protected"));
                        }
                        setProperty(filterElement, "replace", filter);
                        setProperty(filterElement, "replacement", filter);
                        setProperty(filterElement, "splitOnCaseChange", filter);
                        if (filterElement.attribute("synonyms") != null) {
                            filter.setSynonymsText(filterElement.attributeValue("synonyms"));
                        }
                        if (filterElement.attribute("words") != null) {
                            filter.setWordsText(filterElement.attributeValue("words"));
                        }
                    }
                }

                fieldTypeServices.makePersistent(fieldType);
            }
        }
    }
    return newFielTypes;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w w  w . j a v  a 2s . c om*/
public void resetDefaultDistance(RecordCollection collection) {
    ensureCore(collection);

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

    // 1. remove all 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)) {
            it.remove();
        }
    }
    // 2. set requestHandler with name DEFAULT_DISTANCE_NAME as the
    // default distance
    for (Iterator<Element> it = root.elementIterator("requestHandler"); it.hasNext();) {
        Element currentRequestHandlerElement = it.next();
        String currentSearchComponentName = currentRequestHandlerElement.attribute("name").getText();
        if (currentSearchComponentName.equals(DEFAULT_DISTANCE_NAME)) {
            Attribute defaultAttribute = currentRequestHandlerElement.attribute("default");
            if (defaultAttribute != null) {
                defaultAttribute.setText("true");
            } else {
                currentRequestHandlerElement.addAttribute("default", "true");
            }
            break;
        }
    }

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

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  www. j  ava 2s  .  c  o 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);
}