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.cuba.restapi.XMLConverter2.java

License:Apache License

@Override
public ServiceRequest parseServiceRequest(String content) throws Exception {
    Document document = Dom4j.readDocument(content);
    Element rootElement = document.getRootElement();
    Element serviceEl = rootElement.element("service");
    if (serviceEl == null) {
        throw new IllegalArgumentException("Service name not specified in request");
    }//from   w  ww. ja v a2 s .c o m
    String serviceName = serviceEl.getTextTrim();
    Element methodEl = rootElement.element("method");
    if (methodEl == null) {
        throw new IllegalArgumentException("Method name not specified in request");
    }
    String methodName = methodEl.getTextTrim();
    String viewName = null;
    Element viewEl = rootElement.element("view");
    if (viewEl != null)
        viewName = viewEl.getTextTrim();

    ServiceRequest serviceRequest = new ServiceRequest(serviceName, methodName, this);

    Element paramsEl = rootElement.element("params");
    if (paramsEl != null) {
        int idx = 0;
        while (true) {
            String paramName = "param" + idx;
            Element paramEl = findParamByName(paramsEl, paramName);
            if (paramEl == null)
                break;
            serviceRequest.getParamValuesString().add(paramElementContentAsString(paramEl));

            Element paramTypeEl = findParamByName(paramsEl, paramName + "_type");
            if (paramTypeEl != null) {
                String type = paramTypeEl.getText();
                serviceRequest.getParamTypes().add(ClassUtils.forName(type, null));
            } else {
                if (!serviceRequest.getParamTypes().isEmpty()) {
                    //types should be defined for all parameters or for none of them
                    throw new RestServiceException("Parameter type for param" + idx + " is not defined");
                }
            }
            idx++;
        }
    }

    return serviceRequest;
}

From source file:com.haulmont.cuba.restapi.XMLConverter2.java

License:Apache License

@Override
public Entity parseEntity(String content) {
    Document document = Dom4j.readDocument(content);
    Element instanceEl = document.getRootElement();
    return parseEntity(instanceEl, null, null);
}

From source file:com.haulmont.cuba.restapi.XMLConverter2.java

License:Apache License

@Override
public QueryRequest parseQueryRequest(String content)
        throws IllegalArgumentException, ClassNotFoundException, ParseException {
    Document document = Dom4j.readDocument(content);
    Element rootElement = document.getRootElement();
    QueryRequest queryRequest = new QueryRequest();

    Element entityElem = rootElement.element("entity");
    String entity = entityElem.getTextTrim();
    queryRequest.setEntity(entity);/*from   w w  w  .  ja va  2 s . c  om*/

    Element queryElem = rootElement.element("query");
    String query = queryElem.getTextTrim();
    queryRequest.setQuery(query);

    if (rootElement.element("view") != null) {
        Element viewElem = rootElement.element("view");
        String view = viewElem.getTextTrim();
        queryRequest.setViewName(view);
    }

    if (rootElement.element("max") != null) {
        Element maxElem = rootElement.element("max");
        String maxString = maxElem.getTextTrim();
        int max = Integer.parseInt(maxString);
        queryRequest.setMax(max);
    }

    if (rootElement.element("first") != null) {
        Element firstElem = rootElement.element("first");
        String firstString = firstElem.getTextTrim();
        int first = Integer.parseInt(firstString);
        queryRequest.setFirst(first);
    }

    if (rootElement.element("dynamicAttributes") != null) {
        Element dynamicAttributesElem = rootElement.element("dynamicAttributes");
        String dynamicAttributesString = dynamicAttributesElem.getTextTrim();
        Boolean dynamicAttributes = Boolean.valueOf(dynamicAttributesString);
        queryRequest.setDynamicAttributes(dynamicAttributes);
    }

    if (rootElement.element("params") != null) {
        Element paramsElem = rootElement.element("params");
        List paramList = paramsElem.elements("param");
        for (Object obj : paramList) {
            if (obj instanceof Element) {
                Element paramElem = (Element) obj;

                Element nameElem = paramElem.element("name");
                String paramName = nameElem.getStringValue();

                Element valueElem = paramElem.element("value");
                String paramValue = valueElem.getStringValue();

                Object value = null;
                if (paramElem.element("type") != null) {
                    Element typeElem = paramElem.element("type");
                    String typeString = typeElem.getStringValue();
                    Class type = ClassUtils.forName(typeString, null);
                    value = ParseUtils.toObject(type, paramValue, this);
                } else {
                    value = ParseUtils.tryParse(paramValue);
                }

                queryRequest.getParams().put(paramName, value != null ? value : paramValue);
            }
        }
    }

    return queryRequest;
}

From source file:com.haulmont.cuba.restapi.XMLConverter2.java

License:Apache License

@Override
public Collection<? extends Entity> parseEntitiesCollection(String content,
        Class<? extends Collection> collectionClass) {
    try {//from   ww w. j  a v a 2 s .c o m
        Collection collection = newCollectionInstance(collectionClass);
        Document document = Dom4j.readDocument(content);
        List instances = document.getRootElement().elements("instance");
        for (Object instance : instances) {
            Entity entity = parseEntity((Element) instance, null, null);
            collection.add(entity);
        }
        return collection;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.haulmont.cuba.security.app.UserSettingServiceBean.java

License:Apache License

@Override
public void copySettings(User fromUser, User toUser) {
    MetaClass metaClass = metadata.getClassNN(UserSetting.class);

    Security security = AppBeans.get(Security.NAME);
    if (!security.isEntityOpPermitted(metaClass, EntityOp.CREATE)) {
        throw new AccessDeniedException(PermissionType.ENTITY_OP, metaClass.getName());
    }//from   ww  w.j a  va  2s .c om

    Map<UUID, Presentation> presentationsMap = copyPresentations(fromUser, toUser);
    copyUserFolders(fromUser, toUser, presentationsMap);
    Map<UUID, FilterEntity> filtersMap = copyFilters(fromUser, toUser);

    try (Transaction tx = persistence.createTransaction()) {
        EntityManager em = persistence.getEntityManager();

        Query deleteSettingsQuery = em.createQuery("delete from sec$UserSetting s where s.user.id = ?1");
        deleteSettingsQuery.setParameter(1, toUser);
        deleteSettingsQuery.executeUpdate();
        tx.commitRetaining();
        em = persistence.getEntityManager();

        TypedQuery<UserSetting> q = em.createQuery("select s from sec$UserSetting s where s.user.id = ?1",
                UserSetting.class);
        q.setParameter(1, fromUser);
        List<UserSetting> fromUserSettings = q.getResultList();

        for (UserSetting currSetting : fromUserSettings) {
            UserSetting newSetting = metadata.create(UserSetting.class);
            newSetting.setUser(toUser);
            newSetting.setClientType(currSetting.getClientType());
            newSetting.setName(currSetting.getName());

            try {
                Document doc = Dom4j.readDocument(currSetting.getValue());

                List<Element> components = doc.getRootElement().element("components").elements("component");
                for (Element component : components) {
                    Attribute presentationAttr = component.attribute("presentation");
                    if (presentationAttr != null) {
                        UUID presentationId = UuidProvider.fromString(presentationAttr.getValue());
                        Presentation newPresentation = presentationsMap.get(presentationId);
                        if (newPresentation != null) {
                            presentationAttr.setValue(newPresentation.getId().toString());
                        }
                    }
                    Element defaultFilterEl = component.element("defaultFilter");
                    if (defaultFilterEl != null) {
                        Attribute idAttr = defaultFilterEl.attribute("id");
                        if (idAttr != null) {
                            UUID filterId = UuidProvider.fromString(idAttr.getValue());
                            FilterEntity newFilter = filtersMap.get(filterId);
                            if (newFilter != null) {
                                idAttr.setValue(newFilter.getId().toString());
                            }
                        }
                    }
                }

                newSetting.setValue(Dom4j.writeDocument(doc, true));
            } catch (Exception e) {
                newSetting.setValue(currSetting.getValue());
            }
            em.persist(newSetting);
        }

        tx.commit();
    }
}

From source file:com.haulmont.cuba.web.gui.components.presentations.PresentationEditor.java

License:Apache License

protected void commit() {
    Presentations presentations = component.getPresentations();

    Document doc = DocumentHelper.createDocument();
    doc.setRootElement(doc.addElement("presentation"));

    component.saveSettings(doc.getRootElement());

    String xml = Dom4j.writeDocument(doc, false);
    presentation.setXml(xml);//from w  w  w.j a  v a 2  s  . co  m

    presentation.setName(nameField.getValue());
    presentation.setAutoSave(autoSaveField.getValue());
    presentation.setDefault(defaultField.getValue());

    User user = sessionSource.getUserSession().getCurrentOrSubstitutedUser();

    boolean userOnly = !allowGlobalPresentations || !BooleanUtils.isTrue(globalField.getValue());
    presentation.setUser(userOnly ? user : null);

    if (log.isTraceEnabled()) {
        log.trace(String.format("XML: %s", Dom4j.writeDocument(doc, true)));
    }

    if (isNew) {
        presentations.add(presentation);
    } else {
        presentations.modify(presentation);
    }
    presentations.commit();

    addCloseListener(e -> {
        if (isNew) {
            component.applyPresentation(presentation.getId());
        }
    });
}

From source file:com.haulmont.cuba.web.sys.ExternalUIComponentsManager.java

License:Apache License

protected void _registerComponents(String componentDescriptorPath) throws IOException, ClassNotFoundException {
    Enumeration<URL> resources = ExternalUIComponentsManager.class.getClassLoader()
            .getResources(componentDescriptorPath);
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        try (InputStream is = url.openStream()) {
            Document document = Dom4j.readDocument(is);
            List<Element> components = document.getRootElement().elements("component");
            for (Element component : components) {
                String name = component.elementText("name");
                String componentLoaderClassName = component.elementText("componentLoader");
                String componentClassName = component.elementText("class");

                Class<?> componentLoaderClass = Class.forName(componentLoaderClassName);
                Class<?> componentClass = Class.forName(componentClassName);

                if (Component.class.isAssignableFrom(componentClass)) {
                    WebComponentsFactory.registerComponent(name, (Class<? extends Component>) componentClass);
                } else {
                    log.warn("Component {} is not a subclass of com.haulmont.cuba.gui.components.Component",
                            componentClassName);
                }//from  w w  w .j  av  a  2 s . co m

                if (ComponentLoader.class.isAssignableFrom(componentLoaderClass)) {
                    LayoutLoaderConfig.registerLoader(name,
                            (Class<? extends ComponentLoader>) componentLoaderClass);
                } else {
                    log.warn(
                            "Component loader {} is not a subclass of com.haulmont.cuba.gui.xml.layout.ComponentLoader",
                            componentLoaderClassName);
                }
            }
        }
    }
}

From source file:com.haulmont.yarg.structure.xml.impl.DefaultXmlReader.java

License:Apache License

@Override
public Report parseXml(String xml) throws IOException {
    try {/*from  ww w.  j av a  2s .c o m*/
        SAXReader reader = null;
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();

            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

            factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("reporting.xsd")) }));

            SAXParser parser = factory.newSAXParser();

            reader = new SAXReader(parser.getXMLReader());
        } catch (SAXException e) {
            throw new ReportingXmlException(
                    String.format("An error occurred during loading reporting xsd. \\n[%s]", xml), e);
        } catch (ParserConfigurationException e) {
            throw new ReportingXmlException(
                    String.format("An error occurred during loading reporting xsd. \\n[%s]", xml), e);
        }

        Document document = reader.read(new StringReader(xml));
        Element rootElement = document.getRootElement();
        Map<String, ReportTemplate> templateMap = parseTemplates(rootElement);
        List<ReportParameter> reportParameters = parseInputParameters(rootElement);
        List<ReportFieldFormat> reportFieldFormats = parseValueFormats(rootElement);
        BandBuilder rootBandDefinitionBuilder = new BandBuilder().name(BandData.ROOT_BAND_NAME);
        parseQueries(rootElement.element("rootBand"), rootBandDefinitionBuilder);
        parseChildBandDefinitions(rootElement.element("rootBand"), rootBandDefinitionBuilder);
        ReportBand rootBandDefinition = rootBandDefinitionBuilder.build();
        String reportName = rootElement.attribute("name").getText();
        ReportImpl report = new ReportImpl(reportName, templateMap, rootBandDefinition, reportParameters,
                reportFieldFormats);
        return report;
    } catch (DocumentException e) {
        throw new ReportingXmlException(
                String.format("An error occurred while parsing report xml. \\n[%s]", xml), e);
    } catch (FileNotFoundException e) {
        throw new ReportingXmlException(String.format("Could not find report template. \\n[%s]", xml), e);
    } catch (ClassNotFoundException e) {
        throw new ReportingXmlException(String.format("Report parameter class not found. \\n[%s]", xml), e);
    }
}

From source file:com.hazzard.gui.PiNet.java

public void parse(String text) throws DocumentException {
    Document document = DocumentHelper.parseText(text.trim());

    System.out.println(text);//from  ww w.jav  a2s.  co m

    if (document.getRootElement().getName().equals("syncData")) {
        List data;
        data = document.selectNodes("/syncData/*");
        Iterator<Element> iterator = data.iterator();
        while (iterator.hasNext()) {
            Element current = iterator.next();
            if (current.getName().equals("RaceInfo")) {
                raceInfo.time = Integer
                        .parseInt(document.selectSingleNode("/syncData/RaceInfo/Time").getText());
                raceInfo.laps = Integer
                        .parseInt(document.selectSingleNode("/syncData/RaceInfo/Laps").getText());
                raceInfo.joinedPlayers = Integer
                        .parseInt(document.selectSingleNode("/syncData/RaceInfo/JoinedPlayers").getText());
            } else if (current.getName().equals("PlayerInfo1")) {
                playerInfo1.currentLap = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/CurrentLap").getText());
                playerInfo1.relativeTime = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/RelativeTime").getText());
                playerInfo1.speed = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/Speed").getText());
                playerInfo1.turn = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/Turn").getText());
                playerInfo1.position = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/Position").getText());
                playerInfo1.finished = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo1/Finished").getText());
            } else if (current.getName().equals("PlayerInfo2")) {
                playerInfo2.currentLap = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/CurrentLap").getText());
                playerInfo2.relativeTime = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/RelativeTime").getText());
                playerInfo2.speed = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/speed").getText());
                playerInfo2.turn = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/Turn").getText());
                playerInfo2.position = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/Position").getText());
                playerInfo2.finished = Integer
                        .parseInt(document.selectSingleNode("/syncData/PlayerInfo2/Finished").getText());
            }
        }
    }
}

From source file:com.heren.turtle.entry.command.AbstractCommand.java

License:Open Source License

@Override
public void startAll(String args) throws Exception {
    Document document = DocumentHelper.parseText(args);
    Element root = document.getRootElement();
    List elements = root.elements();
    List<Map<String, String>> eachElement = XmlUtils.getEachElement(elements);
    for (Map<String, String> map : eachElement) {
        String eleName = map.get("eleName");
        String name = map.get("name");
        String ip = map.get("ip");
        String port = map.get("port");
        String nameSuffix = map.get("nameSuffix");
        String status = map.get("status");
        String needToFilter = map.get("needToFilter");
        String method = map.get("method");
        String methodType = map.get("methodType");
        Class<?> aClass = Class.forName(name);
        if (Boolean.valueOf(status) && eleName.equals("Soap")) {
            Command command = new SoapCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port), ip,
                    nameSuffix);//www. ja  v a2s  . c o  m
            command.start();
        } else if (Boolean.valueOf(status) && eleName.equals("Rest")) {
            Command command = new RestCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port), ip,
                    nameSuffix);
            command.start();
        } else if (Boolean.valueOf(status) && eleName.equals("Netty")) {
            Command command = new NettyCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port),
                    method, methodType);
            command.start();
        }
    }
}