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.services.SolrServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w w w . ja  v  a2  s. c o m*/
public boolean usesDisMax(RecordCollection collection) {
    ensureCore(collection);

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

    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)) {
            return true;
        }
    }
    return false;
}

From source file:com.doculibre.constellio.utils.connector.init.InitSolrConnectorHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addCopyFields(Document schemaDocument, RecordCollection collection) {
    CopyFieldServices copyFieldServices = ConstellioSpringUtils.getCopyFieldServices();

    EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
    if (!entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().begin();
    }//  ww w .  j a v  a 2s. com

    List<Element> dynamicFieldsElement = schemaDocument.getRootElement().elements("copyField");
    for (Element elem : dynamicFieldsElement) {
        List<String> currentCopyField = new ArrayList<String>();
        String source = elem.attributeValue("source");
        currentCopyField.add(source);
        String destination = elem.attributeValue("dest");
        currentCopyField.add(destination);
        String maxCharsString = elem.attributeValue("maxChars");

        Integer maxChars = null;
        if (maxCharsString != null) {
            maxChars = Integer.valueOf(maxCharsString);
        }

        List<CopyField> newCopyFields = null;
        try {
            newCopyFields = copyFieldServices.newCopyFields(collection, source, destination, maxChars);
            for (CopyField newCopyField : newCopyFields) {
                copyFieldServices.makePersistent(newCopyField);
            }
        } catch (Exception e) {
            LOG.warn("CopyField associated with " + source + ", " + destination
                    + " not added due to the following :");
            LOG.warn(e.getMessage());
        }

    }

    entityManager.getTransaction().commit();
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

License:Open Source License

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }/*from  w w  w .j a  va 2 s. co 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, "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 connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

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

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

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

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

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            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 (Exception 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.utils.ConnectorManagerRequestUtils.java

License:Open Source License

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {/*from   w  w w .ja  v  a  2 s  .c o  m*/
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "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 connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

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

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

        try {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> 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.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public static List<ConstellioUser> readUsers(String fileName) {
    List<ConstellioUser> returnList = new ArrayList<ConstellioUser>();

    File xmlFile = new File(fileName);

    Document xmlDocument;
    if (!xmlFile.exists()) {
        return returnList;
    }/*from www.  j  a  va  2  s.c  o m*/
    try {
        xmlDocument = new SAXReader().read(xmlFile);
    } catch (DocumentException e) {
        e.printStackTrace();
        return returnList;
    }

    Element root = xmlDocument.getRootElement();
    for (Iterator<Element> it = root.elementIterator(USER); it.hasNext();) {
        Element currentUser = it.next();
        returnList.add(toConstellioUser(currentUser));

    }
    return returnList;
}

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

License:Open Source License

public static void addUserTo(ConstellioUser constellioUser, String fileName) {
    Document xmlDocument;
    try {//w w w  . j  av a  2 s.com
        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();
    }

}

From source file:com.doculibre.constellio.utils.SolrSchemaUtils.java

License:Open Source License

public static IndexSchema getSchema(ConnectorType connectorType) {
    IndexSchema connectorTypeSchema;//w  w  w.j a  v a 2 s .  c  o m

    String targetSchemaName;
    if (connectorType != null) {
        targetSchemaName = connectorType.getName();
    } else {
        targetSchemaName = "constellio"; // Default
    }

    Resource[] classpathResources = ConstellioSpringUtils.getResources(SOLR_SCHEMA_PATTERN);
    if (classpathResources != null) {
        connectorTypeSchema = null;
        for (int i = 0; i < classpathResources.length; i++) {
            InputStream resourceInput = null;
            try {
                Resource resource = classpathResources[i];
                resourceInput = resource.getInputStream();
                Document schema = new SAXReader().read(resourceInput);
                Element schemaElement = schema.getRootElement();
                String schemaName = schemaElement.attributeValue("name");
                if (targetSchemaName.equals(schemaName)) {
                    resourceInput = resource.getInputStream();

                    SolrConfig dummySolrConfig;
                    URL dummySolrConfigURL = SolrSchemaUtils.class.getClassLoader()
                            .getResource("config" + File.separator + "solrdefault" + File.separator);
                    File dummySolrConfigDir = new File(dummySolrConfigURL.toURI());
                    File dummySolrConfigFile = new File(dummySolrConfigDir,
                            "conf" + File.separator + "solrconfig.xml");
                    dummySolrConfig = new SolrConfig(dummySolrConfigDir.getPath(),
                            dummySolrConfigFile.getPath(), null);

                    connectorTypeSchema = new IndexSchema(dummySolrConfig, null,
                            new InputSource(resourceInput));
                    break;
                }
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ParserConfigurationException e) {
                throw new RuntimeException(e);
            } catch (SAXException e) {
                throw new RuntimeException(e);
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else {
                    throw new RuntimeException(e);
                }
            } finally {
                IOUtils.closeQuietly(resourceInput);
            }
        }
    } else {
        connectorTypeSchema = null;
    }
    return connectorTypeSchema;
}

From source file:com.doculibre.constellio.utils.xml.SolrShemaXmlReader.java

License:Open Source License

public static String getUniqueKeyField(Document schemaDocument) throws DocumentException {
    String defaultUniqueKeyName = "id";
    String uniqueKeyFieldName = defaultUniqueKeyName;
    Element uniqueKeyElement = schemaDocument.getRootElement().element("uniqueKey");
    if (uniqueKeyElement != null) {
        uniqueKeyFieldName = uniqueKeyElement.getText();
    }/*from   ww w  . j a v  a2  s.co m*/

    return uniqueKeyFieldName;

}

From source file:com.doculibre.constellio.utils.xml.SolrShemaXmlReader.java

License:Open Source License

public static String getDefaultSearchField(Document schemaDocument) throws DocumentException {
    String defaultSearchFieldName;
    Element defaultSearchFieldElement = schemaDocument.getRootElement().element("defaultSearchField");
    if (defaultSearchFieldElement != null) {
        defaultSearchFieldName = defaultSearchFieldElement.getText();
    } else {//w w  w . ja v  a  2 s.  co  m
        defaultSearchFieldName = null;
    }
    return defaultSearchFieldName;

}

From source file:com.doculibre.constellio.utils.xml.SolrShemaXmlReader.java

License:Open Source License

private static Map<String, Map<String, String>> readFields(Document schemaDocument, Boolean readDynamicFields,
        Boolean checkTypes) {/*from   w  w w . ja  v a 2 s .c o  m*/
    Map<String, Map<String, String>> returnList = new HashMap<String, Map<String, String>>();
    //AnalyzerClassServices analyzerClassServices = ConstellioSpringUtils.getAnalyzerClassServices();
    FieldTypeServices fieldTypeServices = ConstellioSpringUtils.getFieldTypeServices();
    if (schemaDocument != null) {

        Element fieldsElement = schemaDocument.getRootElement().element("fields");

        List<Element> fieldElements;
        if (readDynamicFields) {
            fieldElements = fieldsElement.elements("dynamicField");
        } else {
            fieldElements = fieldsElement.elements("field");
        }
        for (Iterator<Element> it = fieldElements.iterator(); it.hasNext();) {
            Element fieldElement = it.next();

            if (checkTypes) {
                /*String analyzerClassName = fieldElement.attributeValue("analyzer");
                if (analyzerClassName != null) {
                AnalyzerClass analyzerClass = analyzerClassServices.get(analyzerClassName);
                    if (analyzerClass == null) {
                       throw new RuntimeException("New Analyzers must be defined throught Constellio Interface");
                    }
                }*/
                String typeName = fieldElement.attributeValue("type");
                if (typeName == null) {
                    throw new RuntimeException("A Field must have a type");
                }
                FieldType fieldType = fieldTypeServices.get(typeName);
                if (fieldType == null) {
                    throw new RuntimeException(
                            "New Field type " + typeName + " must be defined throught Constellio Interface");
                }
            }
            String fieldName = fieldElement.attributeValue("name");
            if (fieldName == null) {
                throw new RuntimeException("A Field must have a name");
            }

            List<Attribute> attributes = fieldElement.attributes();
            Map<String, String> attributesToMap = new HashMap<String, String>();
            for (Attribute att : attributes) {
                if (!att.getQualifiedName().equals("name")) {
                    attributesToMap.put(att.getQualifiedName(), att.getValue());
                }
            }

            returnList.put(fieldName, attributesToMap);
        }
    }
    return returnList;
}