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.haulmont.chile.core.datatypes.Datatypes.java

License:Apache License

private Datatypes() {
    SAXReader reader = new SAXReader();
    URL resource = Datatypes.class.getResource("/datatypes.xml");
    if (resource == null) {
        log.info("Can't find /datatypes.xml, using default datatypes settings");
        resource = Datatypes.class.getResource("/com/haulmont/chile/core/datatypes/datatypes.xml");
    }/*from   ww  w  . j a va  2  s. c  o m*/

    try {
        Document document = reader.read(resource);
        Element element = document.getRootElement();

        List<Element> datatypeElements = element.elements("datatype");
        for (Element datatypeElement : datatypeElements) {
            String datatypeClassName = datatypeElement.attributeValue("class");
            try {
                Datatype datatype;
                Class<Datatype> datatypeClass = ReflectionHelper.getClass(datatypeClassName);
                try {
                    final Constructor<Datatype> constructor = datatypeClass.getConstructor(Element.class);
                    datatype = constructor.newInstance(datatypeElement);
                } catch (Throwable e) {
                    datatype = datatypeClass.newInstance();
                }

                __register(datatype);
            } catch (Throwable e) {
                log.error(String.format("Fail to load datatype '%s'", datatypeClassName), e);
            }
        }
    } catch (DocumentException e) {
        log.error("Fail to load datatype settings", e);
    }
}

From source file:com.haulmont.cuba.core.app.EntitySnapshotManager.java

License:Apache License

protected String processSnapshotXml(String snapshotXml, Map<Class, Class> classMapping) {
    if (!isXml(snapshotXml)) {
        return snapshotXml;
    }//from   w w w  .j  a v  a  2 s.c  o m
    Document document;
    try {
        document = DocumentHelper.parseText(snapshotXml);
    } catch (DocumentException e) {
        throw new RuntimeException("Couldn't parse snapshot xml content", e);
    }
    replaceClasses(document.getRootElement(), classMapping);
    replaceInXmlTree(document.getRootElement(), classMapping);
    return document.asXML();
}

From source file:com.haulmont.cuba.core.entity.ScheduledTask.java

License:Apache License

public List<MethodParameterInfo> getMethodParameters() {
    ArrayList<MethodParameterInfo> result = new ArrayList<>();
    String xml = getMethodParamsXml();
    if (!StringUtils.isBlank(xml)) {
        Document doc = Dom4j.readDocument(xml);
        List<Element> elements = Dom4j.elements(doc.getRootElement(), "param");
        for (Element paramEl : elements) {
            String typeName = paramEl.attributeValue("type");
            String name = paramEl.attributeValue("name");
            Object value = paramEl.getText();
            result.add(new MethodParameterInfo(typeName, name, value));
        }//from  www .j  av a 2  s .c om
    }
    return result;
}

From source file:com.haulmont.cuba.core.sys.AbstractViewRepository.java

License:Apache License

protected void addFile(Element commonRootElem, String fileName) {
    if (readFileNames.contains(fileName))
        return;/*  w  ww . j  a va 2 s . c  o m*/

    log.debug("Deploying views config: " + fileName);
    readFileNames.add(fileName);

    InputStream stream = null;
    try {
        stream = resources.getResourceAsStream(fileName);
        if (stream == null) {
            throw new IllegalStateException("Resource is not found: " + fileName);
        }

        SAXReader reader = new SAXReader();
        Document doc;
        try {
            doc = reader.read(new InputStreamReader(stream, StandardCharsets.UTF_8));
        } catch (DocumentException e) {
            throw new RuntimeException("Unable to parse view file " + fileName, e);
        }
        Element rootElem = doc.getRootElement();

        for (Element includeElem : Dom4j.elements(rootElem, "include")) {
            String incFile = includeElem.attributeValue("file");
            if (!StringUtils.isBlank(incFile))
                addFile(commonRootElem, incFile);
        }

        for (Element viewElem : Dom4j.elements(rootElem, "view")) {
            commonRootElem.add(viewElem.createCopy());
        }
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.haulmont.cuba.core.sys.AbstractViewRepository.java

License:Apache License

public void deployViews(Reader xml) {
    lock.readLock().lock();/*from w  w w . j  a va2 s . c  o  m*/
    try {
        checkInitialized();
    } finally {
        lock.readLock().unlock();
    }

    SAXReader reader = new SAXReader();
    Document doc;
    try {
        doc = reader.read(xml);
    } catch (DocumentException e) {
        throw new RuntimeException("Unable to read views xml", e);
    }
    Element rootElem = doc.getRootElement();

    for (Element includeElem : Dom4j.elements(rootElem, "include")) {
        String file = includeElem.attributeValue("file");
        if (!StringUtils.isBlank(file))
            deployViews(file);
    }

    for (Element viewElem : Dom4j.elements(rootElem, "view")) {
        deployView(rootElem, viewElem);
    }
}

From source file:com.haulmont.cuba.core.sys.AppComponents.java

License:Apache License

private void load(AppComponent component) {
    try {/*from  w  w  w  .  j  a  v  a  2s .  com*/
        Document doc = getDescriptorDoc(component);

        String dependsOnAttr = doc.getRootElement().attributeValue("dependsOn");
        if (!StringUtils.isEmpty(dependsOnAttr)) {
            for (String depCompId : splitCommaSeparatedValue(dependsOnAttr)) {
                AppComponent depComp = get(depCompId);
                if (depComp == null) {
                    depComp = new AppComponent(depCompId);
                    load(depComp);
                    components.add(depComp);
                }
                component.addDependency(depComp);
            }
        }

        for (Element moduleEl : Dom4j.elements(doc.getRootElement(), "module")) {
            String blocksAttr = moduleEl.attributeValue("blocks");
            if (StringUtils.isEmpty(blocksAttr))
                continue;
            List<String> blocks = splitCommaSeparatedValue(blocksAttr);
            if (blocks.contains("*") || blocks.contains(block)) {
                for (Element propertyEl : Dom4j.elements(moduleEl, "property")) {
                    String name = propertyEl.attributeValue("name");
                    String value = propertyEl.attributeValue("value");
                    String existingValue = component.getProperty(name);

                    if (value.startsWith("\\+")) {
                        if (existingValue != null) {
                            log.debug("Overwrite value of property {} from {} to {}", name, existingValue,
                                    value);
                        }

                        component.setProperty(name, value.substring(1), false);
                        continue;
                    }

                    if (!value.startsWith("+")) {
                        if (existingValue != null) {
                            log.debug("Overwrite value of property {} from {} to {}", name, existingValue,
                                    value);
                        }

                        component.setProperty(name, value, false);
                        continue;
                    }

                    String cleanValue = value.substring(1);

                    if (existingValue != null) {

                        String newValue = existingValue;
                        Splitter splitter = Splitter.on(AppProperties.SEPARATOR_PATTERN).omitEmptyStrings();
                        List<String> existingParts = splitter.splitToList(existingValue);
                        for (String part : splitter.split(cleanValue)) {
                            if (!existingParts.contains(part))
                                newValue += " " + part;
                        }
                        component.setProperty(name, newValue, true);
                    } else {
                        component.setProperty(name, cleanValue, true);
                    }
                }
            }

        }
    } catch (IOException | DocumentException e) {
        throw new RuntimeException("Error loading app component '" + component + "'", e);
    }
}

From source file:com.haulmont.cuba.core.sys.DefaultPermissionValuesConfig.java

License:Apache License

protected void parseConfigFile(String fileName) {
    String fileContent = resources.getResourceAsString(fileName);
    if (!Strings.isNullOrEmpty(fileContent)) {
        Document document = Dom4j.readDocument(fileContent);
        List<Element> permissionElements = Dom4j.elements(document.getRootElement(), "permission");

        for (Element element : permissionElements) {
            String target = element.attributeValue("target");
            Integer value = Integer.valueOf(element.attributeValue("value"));
            Integer type = Integer.valueOf(element.attributeValue("type"));
            Permission permission = metadata.create(Permission.class);
            permission.setTarget(target);
            permission.setType(PermissionType.fromId(type));
            permission.setValue(value);/*from  w w  w.  j  a  va  2s . c o m*/
            permissionValues.put(target, permission);
        }
    } else {
        log.error("File {} not found", fileName);
    }
}

From source file:com.haulmont.cuba.core.sys.MetadataBuildSupport.java

License:Apache License

protected Element readXml(String path) {
    InputStream stream = resources.getResourceAsStream(path);
    try {/*from www.  ja v  a2s .co m*/
        stream = resources.getResourceAsStream(path);
        if (stream == null)
            throw new IllegalStateException("Resource not found: " + path);
        Document document = Dom4j.readDocument(stream);
        return document.getRootElement();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.haulmont.cuba.core.sys.MetadataLoader.java

License:Apache License

protected void loadDatatypesFromClasspathResource() {
    SAXReader reader = new SAXReader();
    URL resource = Datatypes.class.getResource(getGetDatatypesResourcePath());
    if (resource != null) {
        log.info("Loading datatypes from " + resource);
        try {/*from   w  w w.  j  a  v  a 2s .  c  o  m*/
            Document document = reader.read(resource);
            Element element = document.getRootElement();

            List<Element> datatypeElements = Dom4j.elements(element, "datatype");
            for (Element datatypeElement : datatypeElements) {
                String datatypeClassName = datatypeElement.attributeValue("class");
                try {
                    Datatype datatype;
                    Class<Datatype> datatypeClass = ReflectionHelper.getClass(datatypeClassName);
                    try {
                        final Constructor<Datatype> constructor = datatypeClass.getConstructor(Element.class);
                        datatype = constructor.newInstance(datatypeElement);
                    } catch (Throwable e) {
                        datatype = datatypeClass.newInstance();
                    }

                    String id = datatypeElement.attributeValue("id");
                    if (Strings.isNullOrEmpty(id))
                        id = guessDatatypeId(datatype);
                    datatypeRegistry.register(datatype, id, true);
                } catch (Throwable e) {
                    log.error(String.format("Fail to load datatype '%s'", datatypeClassName), e);
                }
            }
        } catch (DocumentException e) {
            log.error("Fail to load datatype settings", e);
        }
    }
}

From source file:com.haulmont.cuba.core.sys.persistence.PersistenceConfigProcessor.java

License:Apache License

public void create() {
    if (sourceFileNames == null || sourceFileNames.isEmpty())
        throw new IllegalStateException("Source file list not set");
    if (StringUtils.isBlank(outFileName))
        throw new IllegalStateException("Output file not set");

    Map<String, String> classes = new LinkedHashMap<>();
    Map<String, String> properties = new HashMap<>();

    properties.putAll(DbmsSpecificFactory.getDbmsFeatures(storeName).getJpaParameters());

    for (String fileName : sourceFileNames) {
        Document doc = getDocument(fileName);
        Element puElem = findPersistenceUnitElement(doc.getRootElement());
        if (puElem == null)
            throw new IllegalStateException(
                    "No persistence unit named 'cuba' found among multiple units inside " + fileName);
        addClasses(puElem, classes);//from  w ww .jav a  2  s.c  o m
        addProperties(puElem, properties);
    }

    for (String name : AppContext.getPropertyNames()) {
        if (name.startsWith("eclipselink.")) {
            properties.put(name, AppContext.getProperty(name));
        }
    }

    if (!Stores.isMain(storeName))
        properties.put(PersistenceImplSupport.PROP_NAME, storeName);

    File outFile;
    try {
        outFile = new File(outFileName).getCanonicalFile();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    outFile.getParentFile().mkdirs();

    boolean ormXmlCreated = true;
    String disableOrmGenProp = AppContext.getProperty("cuba.disableOrmXmlGeneration");
    if (!Boolean.parseBoolean(disableOrmGenProp)) {
        MappingFileCreator mappingFileCreator = new MappingFileCreator(classes.values(), properties,
                outFile.getParentFile());
        ormXmlCreated = mappingFileCreator.create();
    }

    String fileName = sourceFileNames.get(sourceFileNames.size() - 1);
    Document doc = getDocument(fileName);
    Element rootElem = doc.getRootElement();

    Element puElem = findPersistenceUnitElement(rootElem);
    if (puElem == null)
        throw new IllegalStateException(
                "No persistence unit named 'cuba' found among multiple units inside " + fileName);

    String puName = AppContext.getProperty("cuba.persistenceUnitName");
    if (!StringUtils.isEmpty(puName)) {
        if (!Stores.isMain(storeName))
            puName = puName + "_" + storeName;
        puElem.addAttribute("name", puName);
    }

    for (Element element : new ArrayList<>(Dom4j.elements(puElem, "class"))) {
        puElem.remove(element);
    }

    puElem.addElement("provider").setText("org.eclipse.persistence.jpa.PersistenceProvider");

    if (ormXmlCreated) {
        puElem.addElement("mapping-file").setText("orm.xml");
    }

    for (String className : classes.values()) {
        puElem.addElement("class").setText(className);
    }

    puElem.addElement("exclude-unlisted-classes");

    Element propertiesEl = puElem.element("properties");
    if (propertiesEl != null)
        puElem.remove(propertiesEl);

    propertiesEl = puElem.addElement("properties");
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        Element element = propertiesEl.addElement("property");
        element.addAttribute("name", entry.getKey());
        element.addAttribute("value", entry.getValue());
    }

    log.info("Creating file " + outFile);
    OutputStream os = null;
    try {
        os = new FileOutputStream(outFileName);
        Dom4j.writeDocument(doc, true, os);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}