Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:com.kingmed.yuyt.util.XMLHandler.java

public static Map<String, Object> transXmltoMapForReport(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, Object> map = new HashMap<String, Object>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }/*from www . ja  va2s  .  com*/
    /*
    Element e = (Element) (rootElt.element("Data"));
    String data = "";
    if (e != null) {
    data = ((Element) e.elements().get(0)).asXML();
    map.put("Data", "<Data>" + data + "</Data>");
    } else {
    data = xmlInfo;
    map.put("Data", data);
    }
    */
    return map;
}

From source file:com.kingmed.yuyt.util.XMLHandler.java

public static Map<String, String> transSimpleXmltoMap(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, String> map = new HashMap<String, String>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }/*w  w  w. ja v  a  2 s. c o m*/
    return map;
}

From source file:com.liferay.alloy.tools.model.Component.java

License:Open Source License

public void initialize(Element componentElement, String defaultPackage) {
    String name = componentElement.attributeValue("name");
    setName(name);//from w  w  w .java  2s.  c  om

    Element descriptionElement = componentElement.element("description");

    String description = StringPool.EMPTY;

    if (descriptionElement != null) {
        description = Convert.toString(descriptionElement.getText());
    }

    setDescription(description);

    Element authorsElement = componentElement.element("authors");

    if (authorsElement != null) {
        List<String> authors = new ArrayList<String>();
        List<Element> authorElementsList = authorsElement.elements("author");

        for (Element authorElement : authorElementsList) {
            authors.add(authorElement.getText());
        }

        _authors = authors.toArray(new String[authors.size()]);
    }

    if (_authors == null) {
        _authors = _DEFAULT_AUTHORS;
    }

    _alloyComponent = Convert.toBoolean(componentElement.attributeValue("alloyComponent"), true);
    _bodyContent = Convert.toBoolean(componentElement.attributeValue("bodyContent"), false);
    _componentInterface = Convert.toString(componentElement.attributeValue("componentInterface"), null);
    String extendsTagsString = Convert.toString(componentElement.attributeValue("extendsTags"), null);

    if (extendsTagsString == null) {
        _extendsTags = null;
    } else {
        _extendsTags = extendsTagsString.split(StringPool.SPACE);
    }

    _module = Convert.toString(componentElement.attributeValue("module"), null);
    _package = Convert.toString(componentElement.attributeValue("package"), defaultPackage);
    _parentClass = Convert.toString(componentElement.attributeValue("parentClass"), null);
    boolean generateJava = Convert.toBoolean(componentElement.attributeValue("generateJava"), true);
    setGenerateJava(generateJava);

    Element attributesElement = componentElement.element("attributes");
    _attributes = new ArrayList<Attribute>();

    if (attributesElement != null) {
        List<Element> attributeElementsList = attributesElement.elements("attribute");
        _attributes.addAll(getAttributesFromElements(attributeElementsList));
    }

    Element eventsElement = componentElement.element("events");
    _events = new ArrayList<Event>();

    if (eventsElement != null) {
        List<Element> eventElementsList = eventsElement.elements("event");
        _events.addAll(getEventsFromElements(eventElementsList));
    }
}

From source file:com.liferay.portal.ejb.PortletManagerImpl.java

License:Open Source License

private Set _readPortletXML(String servletContextName, String xml, Map portletsPool)
        throws DocumentException, IOException {

    Set portletIds = new HashSet();

    if (xml == null) {
        return portletIds;
    }//from  w  ww  .j  ava  2  s  .  com

    /*EntityResolver resolver = new EntityResolver() {
       public InputSource resolveEntity(String publicId, String systemId) {
    InputStream is =
       getClass().getClassLoader().getResourceAsStream(
          "com/liferay/portal/resources/portlet-app_1_0.xsd");
            
    return new InputSource(is);
       }
    };*/

    SAXReader reader = new SAXReader();
    //reader.setEntityResolver(resolver);

    Document doc = reader.read(new StringReader(xml));

    Element root = doc.getRootElement();

    Set userAttributes = new HashSet();

    Iterator itr1 = root.elements("user-attribute").iterator();

    while (itr1.hasNext()) {
        Element userAttribute = (Element) itr1.next();

        String name = userAttribute.elementText("name");

        userAttributes.add(name);
    }

    itr1 = root.elements("portlet").iterator();

    while (itr1.hasNext()) {
        Element portlet = (Element) itr1.next();

        String portletId = portlet.elementText("portlet-name");
        if (servletContextName != null) {
            portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
        }

        portletIds.add(portletId);

        Portlet portletModel = (Portlet) portletsPool.get(portletId);
        if (portletModel == null) {
            portletModel = new Portlet(new PortletPK(portletId, _SHARED_KEY, _SHARED_KEY));

            portletsPool.put(portletId, portletModel);
        }

        if (servletContextName != null) {
            portletModel.setWARFile(true);
        }

        portletModel.setPortletClass(portlet.elementText("portlet-class"));

        Iterator itr2 = portlet.elements("init-param").iterator();

        while (itr2.hasNext()) {
            Element initParam = (Element) itr2.next();

            portletModel.getInitParams().put(initParam.elementText("name"), initParam.elementText("value"));
        }

        Element expirationCache = portlet.element("expiration-cache");
        if (expirationCache != null) {
            portletModel.setExpCache(new Integer(GetterUtil.getInteger(expirationCache.getText())));
        }

        itr2 = portlet.elements("supports").iterator();

        while (itr2.hasNext()) {
            Element supports = (Element) itr2.next();

            String mimeType = supports.elementText("mime-type");

            Iterator itr3 = supports.elements("portlet-mode").iterator();

            while (itr3.hasNext()) {
                Element portletMode = (Element) itr3.next();

                Set mimeTypeModes = (Set) portletModel.getPortletModes().get(mimeType);

                if (mimeTypeModes == null) {
                    mimeTypeModes = new HashSet();

                    portletModel.getPortletModes().put(mimeType, mimeTypeModes);
                }

                mimeTypeModes.add(portletMode.getTextTrim().toLowerCase());
            }
        }

        Set supportedLocales = portletModel.getSupportedLocales();

        supportedLocales.add(Locale.getDefault().getLanguage());

        itr2 = portlet.elements("supported-locale").iterator();

        while (itr2.hasNext()) {
            Element supportedLocaleEl = (Element) itr2.next();

            String supportedLocale = supportedLocaleEl.getText();

            supportedLocales.add(supportedLocale);
        }

        portletModel.setResourceBundle(portlet.elementText("resource-bundle"));

        Element portletInfo = portlet.element("portlet-info");

        String portletInfoTitle = null;
        String portletInfoShortTitle = null;
        String portletInfoKeyWords = null;

        if (portletInfo != null) {
            portletInfoTitle = portletInfo.elementText("title");
            portletInfoShortTitle = portletInfo.elementText("short-title");
            portletInfoKeyWords = portletInfo.elementText("keywords");
        }

        portletModel
                .setPortletInfo(new PortletInfo(portletInfoTitle, portletInfoShortTitle, portletInfoKeyWords));

        Element portletPreferences = portlet.element("portlet-preferences");

        String defaultPreferences = null;
        String prefsValidator = null;

        if (portletPreferences != null) {
            Element prefsValidatorEl = portletPreferences.element("preferences-validator");

            String prefsValidatorName = null;

            if (prefsValidatorEl != null) {
                prefsValidator = prefsValidatorEl.getText();

                portletPreferences.remove(prefsValidatorEl);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat());

            writer.write(portletPreferences);

            defaultPreferences = baos.toString();
        }

        portletModel.setDefaultPreferences(defaultPreferences);
        portletModel.setPreferencesValidator(prefsValidator);

        if (!portletModel.isWARFile() && Validator.isNotNull(prefsValidator)
                && GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

            try {
                PreferencesValidator prefsValidatorObj = PortalUtil.getPreferencesValidator(portletModel);

                prefsValidatorObj.validate(PortletPreferencesSerializer.fromDefaultXML(defaultPreferences));
            } catch (Exception e) {
                _log.warn("Portlet with the name " + portletId + " does not have valid default preferences");
            }
        }

        List roles = new ArrayList();

        itr2 = portlet.elements("security-role-ref").iterator();

        while (itr2.hasNext()) {
            Element role = (Element) itr2.next();

            roles.add(role.elementText("role-name"));
        }

        portletModel.setRolesArray((String[]) roles.toArray(new String[0]));

        portletModel.getUserAttributes().addAll(userAttributes);
    }

    return portletIds;
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

License:Open Source License

public static String getContent(String fileName) throws Exception {
    Document document = _getContentDocument(fileName);

    Element rootElement = document.getRootElement();

    Element authorElement = null;
    Element namespaceElement = null;
    Map<String, Element> entityElements = new TreeMap<>();
    Map<String, Element> exceptionElements = new TreeMap<>();

    List<Element> elements = rootElement.elements();

    for (Element element : elements) {
        String elementName = element.getName();

        if (elementName.equals("author")) {
            element.detach();/*w ww.j a  va 2  s  .  c o m*/

            if (authorElement != null) {
                throw new IllegalArgumentException("There can only be one author element");
            }

            authorElement = element;
        } else if (elementName.equals("namespace")) {
            element.detach();

            if (namespaceElement != null) {
                throw new IllegalArgumentException("There can only be one namespace element");
            }

            namespaceElement = element;
        } else if (elementName.equals("entity")) {
            element.detach();

            String name = element.attributeValue("name");

            entityElements.put(StringUtil.toLowerCase(name), element);
        } else if (elementName.equals("exceptions")) {
            element.detach();

            List<Element> exceptionElementsList = element.elements("exception");

            for (Element exceptionElement : exceptionElementsList) {
                exceptionElement.detach();

                exceptionElements.put(exceptionElement.getText(), exceptionElement);
            }
        }
    }

    if (authorElement != null) {
        rootElement.add(authorElement);
    }

    if (namespaceElement == null) {
        throw new IllegalArgumentException("The namespace element is required");
    } else {
        rootElement.add(namespaceElement);
    }

    _addElements(rootElement, entityElements);

    if (!exceptionElements.isEmpty()) {
        Element exceptionsElement = rootElement.addElement("exceptions");

        _addElements(exceptionsElement, exceptionElements);
    }

    return document.asXML();
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

License:Open Source License

public ServiceBuilder(String apiDirName, boolean autoImportDefaultReferences, boolean autoNamespaceTables,
        String beanLocatorUtil, long buildNumber, boolean buildNumberIncrement, String hbmFileName,
        String implDirName, String inputFileName, String modelHintsFileName, boolean osgiModule,
        String pluginName, String propsUtil, String[] readOnlyPrefixes, String remotingFileName,
        Set<String> resourceActionModels, String resourcesDirName, String springFileName,
        String[] springNamespaces, String sqlDirName, String sqlFileName, String sqlIndexesFileName,
        String sqlSequencesFileName, String targetEntityName, String testDirName, boolean build)
        throws Exception {

    _tplBadAliasNames = _getTplProperty("bad_alias_names", _tplBadAliasNames);
    _tplBadColumnNames = _getTplProperty("bad_column_names", _tplBadColumnNames);
    _tplBadTableNames = _getTplProperty("bad_table_names", _tplBadTableNames);
    _tplBlobModel = _getTplProperty("blob_model", _tplBlobModel);
    _tplEjbPk = _getTplProperty("ejb_pk", _tplEjbPk);
    _tplException = _getTplProperty("exception", _tplException);
    _tplExtendedModel = _getTplProperty("extended_model", _tplExtendedModel);
    _tplExtendedModelBaseImpl = _getTplProperty("extended_model_base_impl", _tplExtendedModelBaseImpl);
    _tplExtendedModelImpl = _getTplProperty("extended_model_impl", _tplExtendedModelImpl);
    _tplFinder = _getTplProperty("finder", _tplFinder);
    _tplFinderUtil = _getTplProperty("finder_util", _tplFinderUtil);
    _tplHbmXml = _getTplProperty("hbm_xml", _tplHbmXml);
    _tplJsonJs = _getTplProperty("json_js", _tplJsonJs);
    _tplJsonJsMethod = _getTplProperty("json_js_method", _tplJsonJsMethod);
    _tplModel = _getTplProperty("model", _tplModel);
    _tplModelCache = _getTplProperty("model_cache", _tplModelCache);
    _tplModelClp = _getTplProperty("model", _tplModelClp);
    _tplModelHintsXml = _getTplProperty("model_hints_xml", _tplModelHintsXml);
    _tplModelImpl = _getTplProperty("model_impl", _tplModelImpl);
    _tplModelSoap = _getTplProperty("model_soap", _tplModelSoap);
    _tplModelWrapper = _getTplProperty("model_wrapper", _tplModelWrapper);
    _tplPersistence = _getTplProperty("persistence", _tplPersistence);
    _tplPersistenceImpl = _getTplProperty("persistence_impl", _tplPersistenceImpl);
    _tplPersistenceUtil = _getTplProperty("persistence_util", _tplPersistenceUtil);
    _tplProps = _getTplProperty("props", _tplProps);
    _tplRemotingXml = _getTplProperty("remoting_xml", _tplRemotingXml);
    _tplService = _getTplProperty("service", _tplService);
    _tplServiceBaseImpl = _getTplProperty("service_base_impl", _tplServiceBaseImpl);
    _tplServiceClp = _getTplProperty("service_clp", _tplServiceClp);
    _tplServiceClpInvoker = _getTplProperty("service_clp_invoker", _tplServiceClpInvoker);
    _tplServiceClpMessageListener = _getTplProperty("service_clp_message_listener",
            _tplServiceClpMessageListener);
    _tplServiceClpSerializer = _getTplProperty("service_clp_serializer", _tplServiceClpSerializer);
    _tplServiceHttp = _getTplProperty("service_http", _tplServiceHttp);
    _tplServiceImpl = _getTplProperty("service_impl", _tplServiceImpl);
    _tplServicePropsUtil = _getTplProperty("service_props_util", _tplServicePropsUtil);
    _tplServiceSoap = _getTplProperty("service_soap", _tplServiceSoap);
    _tplServiceUtil = _getTplProperty("service_util", _tplServiceUtil);
    _tplServiceWrapper = _getTplProperty("service_wrapper", _tplServiceWrapper);
    _tplSpringXml = _getTplProperty("spring_xml", _tplSpringXml);

    try {//from   w  w  w.jav a 2 s .  co  m
        _apiDirName = apiDirName;
        _autoImportDefaultReferences = autoImportDefaultReferences;
        _autoNamespaceTables = autoNamespaceTables;
        _beanLocatorUtil = beanLocatorUtil;
        _buildNumber = buildNumber;
        _buildNumberIncrement = buildNumberIncrement;
        _hbmFileName = hbmFileName;
        _implDirName = implDirName;
        _modelHintsFileName = modelHintsFileName;
        _osgiModule = osgiModule;
        _pluginName = GetterUtil.getString(pluginName);
        _propsUtil = propsUtil;
        _readOnlyPrefixes = readOnlyPrefixes;
        _remotingFileName = remotingFileName;
        _resourceActionModels = resourceActionModels;
        _resourcesDirName = resourcesDirName;
        _springFileName = springFileName;

        _springNamespaces = springNamespaces;

        if (!ArrayUtil.contains(_springNamespaces, _SPRING_NAMESPACE_BEANS)) {

            _springNamespaces = ArrayUtil.append(_springNamespaces, _SPRING_NAMESPACE_BEANS);
        }

        _sqlDirName = sqlDirName;
        _sqlFileName = sqlFileName;
        _sqlIndexesFileName = sqlIndexesFileName;
        _sqlSequencesFileName = sqlSequencesFileName;
        _targetEntityName = targetEntityName;
        _testDirName = testDirName;
        _build = build;

        _badTableNames = _readLines(_tplBadTableNames);
        _badAliasNames = _readLines(_tplBadAliasNames);
        _badColumnNames = _readLines(_tplBadColumnNames);

        _beanLocatorUtilShortName = _beanLocatorUtil.substring(_beanLocatorUtil.lastIndexOf(".") + 1);

        SAXReader saxReader = _getSAXReader();

        Document document = saxReader.read(new XMLSafeReader(getContent(inputFileName)));

        Element rootElement = document.getRootElement();

        String packagePath = rootElement.attributeValue("package-path");

        if (Validator.isNull(packagePath)) {
            throw new IllegalArgumentException("The package-path attribute is required");
        }

        _outputPath = _implDirName + "/" + StringUtil.replace(packagePath, ".", "/");

        _serviceOutputPath = _apiDirName + "/" + StringUtil.replace(packagePath, ".", "/");

        if (Validator.isNotNull(_testDirName)) {
            _testOutputPath = _testDirName + "/" + StringUtil.replace(packagePath, ".", "/");
        }

        _packagePath = packagePath;

        _autoImportDefaultReferences = GetterUtil.getBoolean(
                rootElement.attributeValue("auto-import-default-references"), _autoImportDefaultReferences);
        _autoNamespaceTables = GetterUtil.getBoolean(rootElement.attributeValue("auto-namespace-tables"),
                _autoNamespaceTables);
        _mvccEnabled = GetterUtil.getBoolean(rootElement.attributeValue("mvcc-enabled"));

        Element authorElement = rootElement.element("author");

        if (authorElement != null) {
            _author = authorElement.getText();
        } else {
            _author = AUTHOR;
        }

        Element portletElement = rootElement.element("portlet");
        Element namespaceElement = rootElement.element("namespace");

        if (portletElement != null) {
            _portletName = portletElement.attributeValue("name");

            _portletShortName = portletElement.attributeValue("short-name");

            _portletPackageName = TextFormatter.format(_portletName, TextFormatter.B);

            _outputPath += "/" + _portletPackageName;

            _serviceOutputPath += "/" + _portletPackageName;

            _testOutputPath += "/" + _portletPackageName;

            _packagePath += "." + _portletPackageName;
        } else {
            _portletShortName = namespaceElement.getText();
        }

        _portletShortName = _portletShortName.trim();

        for (char c : _portletShortName.toCharArray()) {
            if (!Validator.isChar(c) && (c != CharPool.UNDERLINE)) {
                throw new RuntimeException("The namespace element must be a valid keyword");
            }
        }

        _ejbList = new ArrayList<>();
        _entityMappings = new HashMap<>();

        List<Element> entityElements = rootElement.elements("entity");

        for (Element entityElement : entityElements) {
            _parseEntity(entityElement);
        }

        List<String> exceptionList = new ArrayList<>();

        Element exceptionsElement = rootElement.element("exceptions");

        if (exceptionsElement != null) {
            List<Element> exceptionElements = exceptionsElement.elements("exception");

            for (Element exceptionElement : exceptionElements) {
                exceptionList.add(exceptionElement.getText());
            }
        }

        if (build) {
            for (int x = 0; x < _ejbList.size(); x++) {
                Entity entity = _ejbList.get(x);

                if (_isTargetEntity(entity)) {
                    System.out.println("Building " + entity.getName());

                    _resolveEntity(entity);

                    if (entity.hasActionableDynamicQuery()) {
                        _createActionableDynamicQuery(entity);

                        if (entity.isStagedModel()) {
                            _createExportActionableDynamicQuery(entity);
                        } else {
                            _removeExportActionableDynamicQuery(entity);
                        }
                    } else {
                        _removeActionableDynamicQuery(entity);
                        _removeExportActionableDynamicQuery(entity);
                    }

                    if (entity.hasColumns()) {
                        _createHbm(entity);
                        _createHbmUtil(entity);

                        _createPersistenceImpl(entity);
                        _createPersistence(entity);
                        _createPersistenceUtil(entity);

                        if (Validator.isNotNull(_testDirName)) {
                            _createPersistenceTest(entity);
                        }

                        _createModelImpl(entity);
                        _createExtendedModelBaseImpl(entity);
                        _createExtendedModelImpl(entity);

                        entity.setTransients(_getTransients(entity, false));
                        entity.setParentTransients(_getTransients(entity, true));

                        _createModel(entity);
                        _createExtendedModel(entity);

                        _createModelCache(entity);
                        _createModelClp(entity);
                        _createModelWrapper(entity);

                        _createModelSoap(entity);

                        _createBlobModels(entity);

                        _createPool(entity);

                        if (entity.getPKList().size() > 1) {
                            _createEJBPK(entity);
                        }
                    }

                    _createFinder(entity);
                    _createFinderUtil(entity);

                    if (entity.hasLocalService()) {
                        _createServiceImpl(entity, _SESSION_TYPE_LOCAL);
                        _createServiceBaseImpl(entity, _SESSION_TYPE_LOCAL);
                        _createService(entity, _SESSION_TYPE_LOCAL);
                        _createServiceFactory(entity, _SESSION_TYPE_LOCAL);
                        _createServiceUtil(entity, _SESSION_TYPE_LOCAL);

                        _createServiceClp(entity, _SESSION_TYPE_LOCAL);
                        _createServiceClpInvoker(entity, _SESSION_TYPE_LOCAL);
                        _createServiceWrapper(entity, _SESSION_TYPE_LOCAL);
                    } else {
                        _removeServiceImpl(entity, _SESSION_TYPE_LOCAL);
                        _removeServiceBaseImpl(entity, _SESSION_TYPE_LOCAL);
                        _removeService(entity, _SESSION_TYPE_LOCAL);
                        _removeServiceUtil(entity, _SESSION_TYPE_LOCAL);

                        _removeServiceClp(entity, _SESSION_TYPE_LOCAL);
                        _removeServiceClpInvoker(entity, _SESSION_TYPE_LOCAL);
                        _removeServiceWrapper(entity, _SESSION_TYPE_LOCAL);
                    }

                    if (entity.hasRemoteService()) {
                        _createServiceImpl(entity, _SESSION_TYPE_REMOTE);
                        _createServiceBaseImpl(entity, _SESSION_TYPE_REMOTE);
                        _createService(entity, _SESSION_TYPE_REMOTE);
                        _createServiceFactory(entity, _SESSION_TYPE_REMOTE);
                        _createServiceUtil(entity, _SESSION_TYPE_REMOTE);

                        _createServiceClp(entity, _SESSION_TYPE_REMOTE);
                        _createServiceClpInvoker(entity, _SESSION_TYPE_REMOTE);
                        _createServiceWrapper(entity, _SESSION_TYPE_REMOTE);

                        if (Validator.isNotNull(_remotingFileName)) {
                            _createServiceHttp(entity);
                        }

                        _createServiceJson(entity);

                        if (entity.hasColumns()) {
                            _createServiceJsonSerializer(entity);
                        }

                        _createServiceSoap(entity);
                    } else {
                        _removeServiceImpl(entity, _SESSION_TYPE_REMOTE);
                        _removeServiceBaseImpl(entity, _SESSION_TYPE_REMOTE);
                        _removeService(entity, _SESSION_TYPE_REMOTE);
                        _removeServiceUtil(entity, _SESSION_TYPE_REMOTE);

                        _removeServiceClp(entity, _SESSION_TYPE_REMOTE);
                        _removeServiceClpInvoker(entity, _SESSION_TYPE_REMOTE);
                        _removeServiceWrapper(entity, _SESSION_TYPE_REMOTE);

                        if (Validator.isNotNull(_remotingFileName)) {
                            _removeServiceHttp(entity);
                        }

                        _removeServiceSoap(entity);
                    }
                } else {
                    if (entity.hasColumns()) {
                        entity.setTransients(_getTransients(entity, false));
                        entity.setParentTransients(_getTransients(entity, true));
                    }
                }
            }

            _createHbmXml();
            _createModelHintsXml();
            _createSpringXml();

            _createExceptions(exceptionList);

            _createServiceClpMessageListener();
            _createServiceClpSerializer(exceptionList);
            _createServicePropsUtil();

            if (Validator.isNotNull(_remotingFileName)) {
                _createRemotingXml();
            }

            _createSQLIndexes();
            _createSQLTables();
            _createSQLSequences();

            _createProps();

            _deleteOrmXml();
            _deleteSpringLegacyXml();
        }
    } catch (FileNotFoundException fnfe) {
        System.out.println(fnfe.getMessage());
    }
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

License:Open Source License

private static void _readResourceActionModels(String implDir, InputStream inputStream,
        Set<String> resourceActionModels) throws Exception {

    SAXReader saxReader = _getSAXReader();

    Document document = saxReader.read(inputStream);

    Element rootElement = document.getRootElement();

    List<Element> resourceElements = rootElement.elements("resource");

    for (Element resourceElement : resourceElements) {
        resourceActionModels.addAll(/*from  w w w .  jav a  2s .  c om*/
                readResourceActionModels(implDir, new String[] { resourceElement.attributeValue("file") }));
    }

    XPath xPath = document.createXPath("//model-resource/model-name");

    List<Element> elements = xPath.selectNodes(rootElement);

    for (Element element : elements) {
        resourceActionModels.add(element.getText().trim());
    }
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

License:Open Source License

private void _parseEntity(Element entityElement) throws Exception {
    String ejbName = entityElement.attributeValue("name");
    String humanName = entityElement.attributeValue("human-name");

    String table = entityElement.attributeValue("table");

    if (Validator.isNull(table)) {
        table = ejbName;//from  w w w. ja va  2s.  c o m

        if (_badTableNames.contains(ejbName)) {
            table += StringPool.UNDERLINE;
        }

        if (_autoNamespaceTables) {
            table = _portletShortName + StringPool.UNDERLINE + ejbName;
        }
    }

    boolean uuid = GetterUtil.getBoolean(entityElement.attributeValue("uuid"));
    boolean uuidAccessor = GetterUtil.getBoolean(entityElement.attributeValue("uuid-accessor"));
    boolean localService = GetterUtil.getBoolean(entityElement.attributeValue("local-service"));
    boolean remoteService = GetterUtil.getBoolean(entityElement.attributeValue("remote-service"), true);
    String persistenceClass = GetterUtil.getString(entityElement.attributeValue("persistence-class"),
            _packagePath + ".service.persistence.impl." + ejbName + "PersistenceImpl");

    String finderClass = "";

    File originalFinderImpl = new File(_outputPath + "/service/persistence/" + ejbName + "FinderImpl.java");
    File newFinderImpl = new File(_outputPath + "/service/persistence/impl/" + ejbName + "FinderImpl.java");

    if (originalFinderImpl.exists()) {
        FileUtils.moveFile(originalFinderImpl, newFinderImpl);

        String content = FileUtils.readFileToString(newFinderImpl);

        StringBundler sb = new StringBundler();

        sb.append("package " + _packagePath + ".service.persistence.impl;\n\n");
        sb.append("import " + _packagePath + ".service.persistence." + ejbName + "Finder;\n");
        sb.append("import " + _packagePath + ".service.persistence." + ejbName + "Util;");

        content = StringUtil.replace(content, "package " + _packagePath + ".service.persistence;",
                sb.toString());

        writeFileRaw(newFinderImpl, content, _modifiedFileNames);
    }

    if (newFinderImpl.exists()) {
        finderClass = _packagePath + ".service.persistence.impl." + ejbName + "FinderImpl";
    }

    String dataSource = entityElement.attributeValue("data-source");
    String sessionFactory = entityElement.attributeValue("session-factory");
    String txManager = entityElement.attributeValue("tx-manager");
    boolean cacheEnabled = GetterUtil.getBoolean(entityElement.attributeValue("cache-enabled"), true);
    boolean jsonEnabled = GetterUtil.getBoolean(entityElement.attributeValue("json-enabled"), remoteService);
    boolean mvccEnabled = GetterUtil.getBoolean(entityElement.attributeValue("mvcc-enabled"), _mvccEnabled);
    boolean trashEnabled = GetterUtil.getBoolean(entityElement.attributeValue("trash-enabled"));
    boolean deprecated = GetterUtil.getBoolean(entityElement.attributeValue("deprecated"));

    boolean dynamicUpdateEnabled = GetterUtil.getBoolean(entityElement.attributeValue("dynamic-update-enabled"),
            mvccEnabled);

    List<EntityColumn> pkList = new ArrayList<>();
    List<EntityColumn> regularColList = new ArrayList<>();
    List<EntityColumn> blobList = new ArrayList<>();
    List<EntityColumn> collectionList = new ArrayList<>();
    List<EntityColumn> columnList = new ArrayList<>();

    boolean permissionedModel = false;

    List<Element> columnElements = entityElement.elements("column");

    if (uuid) {
        Element columnElement = DocumentHelper.createElement("column");

        columnElement.addAttribute("name", "uuid");
        columnElement.addAttribute("type", "String");

        columnElements.add(0, columnElement);
    }

    if (mvccEnabled && !columnElements.isEmpty()) {
        Element columnElement = DocumentHelper.createElement("column");

        columnElement.addAttribute("name", "mvccVersion");
        columnElement.addAttribute("type", "long");

        columnElements.add(0, columnElement);
    }

    for (Element columnElement : columnElements) {
        String columnName = columnElement.attributeValue("name");

        if (columnName.equals("resourceBlockId") && !ejbName.equals("ResourceBlock")) {

            permissionedModel = true;
        }

        String columnDBName = columnElement.attributeValue("db-name");

        if (Validator.isNull(columnDBName)) {
            columnDBName = columnName;

            if (_badColumnNames.contains(columnName)) {
                columnDBName += StringPool.UNDERLINE;
            }
        }

        String columnType = columnElement.attributeValue("type");
        boolean primary = GetterUtil.getBoolean(columnElement.attributeValue("primary"));
        boolean accessor = GetterUtil.getBoolean(columnElement.attributeValue("accessor"));
        boolean filterPrimary = GetterUtil.getBoolean(columnElement.attributeValue("filter-primary"));
        String collectionEntity = columnElement.attributeValue("entity");

        String mappingTable = columnElement.attributeValue("mapping-table");

        if (Validator.isNotNull(mappingTable)) {
            if (_badTableNames.contains(mappingTable)) {
                mappingTable += StringPool.UNDERLINE;
            }

            if (_autoNamespaceTables) {
                mappingTable = _portletShortName + StringPool.UNDERLINE + mappingTable;
            }
        }

        String idType = columnElement.attributeValue("id-type");
        String idParam = columnElement.attributeValue("id-param");
        boolean convertNull = GetterUtil.getBoolean(columnElement.attributeValue("convert-null"), true);
        boolean lazy = GetterUtil.getBoolean(columnElement.attributeValue("lazy"), true);
        boolean localized = GetterUtil.getBoolean(columnElement.attributeValue("localized"));
        boolean colJsonEnabled = GetterUtil.getBoolean(columnElement.attributeValue("json-enabled"),
                jsonEnabled);
        boolean containerModel = GetterUtil.getBoolean(columnElement.attributeValue("container-model"));
        boolean parentContainerModel = GetterUtil
                .getBoolean(columnElement.attributeValue("parent-container-model"));

        EntityColumn col = new EntityColumn(columnName, columnDBName, columnType, primary, accessor,
                filterPrimary, collectionEntity, mappingTable, idType, idParam, convertNull, lazy, localized,
                colJsonEnabled, containerModel, parentContainerModel);

        if (primary) {
            pkList.add(col);
        }

        if (columnType.equals("Collection")) {
            collectionList.add(col);
        } else {
            regularColList.add(col);

            if (columnType.equals("Blob")) {
                blobList.add(col);
            }
        }

        columnList.add(col);

        if (Validator.isNotNull(collectionEntity) && Validator.isNotNull(mappingTable)) {

            EntityMapping entityMapping = new EntityMapping(mappingTable, ejbName, collectionEntity);

            if (!_entityMappings.containsKey(mappingTable)) {
                _entityMappings.put(mappingTable, entityMapping);
            }
        }
    }

    EntityOrder order = null;

    Element orderElement = entityElement.element("order");

    if (orderElement != null) {
        boolean asc = true;

        if ((orderElement.attribute("by") != null) && orderElement.attributeValue("by").equals("desc")) {

            asc = false;
        }

        List<EntityColumn> orderColsList = new ArrayList<>();

        order = new EntityOrder(asc, orderColsList);

        List<Element> orderColumnElements = orderElement.elements("order-column");

        for (Element orderColElement : orderColumnElements) {
            String orderColName = orderColElement.attributeValue("name");
            boolean orderColCaseSensitive = GetterUtil
                    .getBoolean(orderColElement.attributeValue("case-sensitive"), true);

            boolean orderColByAscending = asc;

            String orderColBy = GetterUtil.getString(orderColElement.attributeValue("order-by"));

            if (orderColBy.equals("asc")) {
                orderColByAscending = true;
            } else if (orderColBy.equals("desc")) {
                orderColByAscending = false;
            }

            EntityColumn col = Entity.getColumn(orderColName, columnList);

            col.setOrderColumn(true);

            col = (EntityColumn) col.clone();

            col.setCaseSensitive(orderColCaseSensitive);
            col.setOrderByAscending(orderColByAscending);

            orderColsList.add(col);
        }
    }

    List<EntityFinder> finderList = new ArrayList<>();

    List<Element> finderElements = entityElement.elements("finder");

    if (uuid) {
        if (columnList.contains(new EntityColumn("companyId"))) {
            Element finderElement = DocumentHelper.createElement("finder");

            finderElement.addAttribute("name", "Uuid_C");
            finderElement.addAttribute("return-type", "Collection");

            Element finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "uuid");

            finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "companyId");

            finderElements.add(0, finderElement);
        }

        if (columnList.contains(new EntityColumn("groupId"))) {
            Element finderElement = DocumentHelper.createElement("finder");

            if (ejbName.equals("Layout")) {
                finderElement.addAttribute("name", "UUID_G_P");
            } else {
                finderElement.addAttribute("name", "UUID_G");
            }

            finderElement.addAttribute("return-type", ejbName);
            finderElement.addAttribute("unique", "true");

            Element finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "uuid");

            finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "groupId");

            if (ejbName.equals("Layout")) {
                finderColumnElement = finderElement.addElement("finder-column");

                finderColumnElement.addAttribute("name", "privateLayout");
            }

            finderElements.add(0, finderElement);
        }

        Element finderElement = DocumentHelper.createElement("finder");

        finderElement.addAttribute("name", "Uuid");
        finderElement.addAttribute("return-type", "Collection");

        Element finderColumnElement = finderElement.addElement("finder-column");

        finderColumnElement.addAttribute("name", "uuid");

        finderElements.add(0, finderElement);
    }

    if (permissionedModel) {
        Element finderElement = DocumentHelper.createElement("finder");

        finderElement.addAttribute("name", "ResourceBlockId");
        finderElement.addAttribute("return-type", "Collection");

        Element finderColumnElement = finderElement.addElement("finder-column");

        finderColumnElement.addAttribute("name", "resourceBlockId");

        finderElements.add(0, finderElement);
    }

    String alias = TextFormatter.format(ejbName, TextFormatter.I);

    if (_badAliasNames.contains(StringUtil.toLowerCase(alias))) {
        alias += StringPool.UNDERLINE;
    }

    for (Element finderElement : finderElements) {
        String finderName = finderElement.attributeValue("name");
        String finderReturn = finderElement.attributeValue("return-type");
        boolean finderUnique = GetterUtil.getBoolean(finderElement.attributeValue("unique"));

        String finderWhere = finderElement.attributeValue("where");

        if (Validator.isNotNull(finderWhere)) {
            for (EntityColumn column : columnList) {
                String name = column.getName();

                finderWhere = StringUtil.replace(finderWhere, name, alias + "." + name);
            }
        }

        boolean finderDBIndex = GetterUtil.getBoolean(finderElement.attributeValue("db-index"), true);

        List<EntityColumn> finderColsList = new ArrayList<>();

        List<Element> finderColumnElements = finderElement.elements("finder-column");

        for (Element finderColumnElement : finderColumnElements) {
            String finderColName = finderColumnElement.attributeValue("name");
            boolean finderColCaseSensitive = GetterUtil
                    .getBoolean(finderColumnElement.attributeValue("case-sensitive"), true);
            String finderColComparator = GetterUtil.getString(finderColumnElement.attributeValue("comparator"),
                    "=");
            String finderColArrayableOperator = GetterUtil
                    .getString(finderColumnElement.attributeValue("arrayable-operator"));

            EntityColumn col = Entity.getColumn(finderColName, columnList);

            if (!col.isFinderPath()) {
                col.setFinderPath(true);
            }

            col = (EntityColumn) col.clone();

            col.setCaseSensitive(finderColCaseSensitive);
            col.setComparator(finderColComparator);
            col.setArrayableOperator(finderColArrayableOperator);

            col.validate();

            finderColsList.add(col);
        }

        finderList.add(new EntityFinder(finderName, finderReturn, finderUnique, finderWhere, finderDBIndex,
                finderColsList));
    }

    List<Entity> referenceList = new ArrayList<>();
    List<String> unresolvedReferenceList = new ArrayList<>();

    if (_build) {
        List<Element> referenceElements = entityElement.elements("reference");

        Set<String> referenceSet = new TreeSet<>();

        for (Element referenceElement : referenceElements) {
            String referencePackage = referenceElement.attributeValue("package-path");
            String referenceEntity = referenceElement.attributeValue("entity");

            referenceSet.add(referencePackage + "." + referenceEntity);
        }

        if (!_packagePath.equals("com.liferay.counter")) {
            referenceSet.add("com.liferay.counter.Counter");
        }

        if (_autoImportDefaultReferences) {
            referenceSet.add("com.liferay.portal.ClassName");
            referenceSet.add("com.liferay.portal.Resource");
            referenceSet.add("com.liferay.portal.User");
        }

        for (String referenceName : referenceSet) {
            try {
                referenceList.add(getEntity(referenceName));
            } catch (RuntimeException re) {
                unresolvedReferenceList.add(referenceName);
            }
        }
    }

    List<String> txRequiredList = new ArrayList<>();

    List<Element> txRequiredElements = entityElement.elements("tx-required");

    for (Element txRequiredEl : txRequiredElements) {
        String txRequired = txRequiredEl.getText();

        txRequiredList.add(txRequired);
    }

    boolean resourceActionModel = _resourceActionModels.contains(_packagePath + ".model." + ejbName);

    _ejbList.add(new Entity(_packagePath, _portletName, _portletShortName, ejbName, humanName, table, alias,
            uuid, uuidAccessor, localService, remoteService, persistenceClass, finderClass, dataSource,
            sessionFactory, txManager, cacheEnabled, dynamicUpdateEnabled, jsonEnabled, mvccEnabled,
            trashEnabled, deprecated, pkList, regularColList, blobList, collectionList, columnList, order,
            finderList, referenceList, unresolvedReferenceList, txRequiredList, resourceActionModel));
}

From source file:com.liferay.util.xml.descriptor.SimpleXMLDescriptor.java

License:Open Source License

private int _compareChildText(Element el1, Element el2, String childName) {
    Element child1 = _getChild(el1, childName);
    Element child2 = _getChild(el2, childName);

    if ((child1 == null) || (child2 == null)) {
        return -1;
    }/*from  www  . j  av  a  2  s  .  c o m*/

    String name1 = child1.getText();
    String name2 = child2.getText();

    if ((name1 == null) || (name2 == null)) {
        return -1;
    }

    return name1.compareTo(name2);
}

From source file:com.love320.templateparser.label.impl.XMLToLabelImpl.java

License:Apache License

@Override
public List<Label> get(String xmlstr) {
    List<Label> labeList = new ArrayList<Label>();
    try {// w ww .jav  a 2  s. co m
        Document document = DocumentHelper.parseText(xmlstr);//string ?xml
        Element docroot = document.getRootElement();//?Element
        List ls = docroot.selectNodes("/root/content/item");//?item
        for (int i = 0; i < ls.size(); i++) {//??
            Element element = (Element) ls.get(i);//?
            String type = element.attributeValue("type");//?
            Label label = new Label();//
            label.setType(type);//
            label.setTemplate(element.getText());//
            labeList.add(label);//
            /*
            if(type.equals("label")){//
               logger.info("label:"+element.getText());
            }else if(type.equals("symbols")){//?
               logger.info("symbols:"+element.getText());
            }else{//
               logger.info(element.getText());
            }
            */
        }
    } catch (DocumentException e) {
        logger.error("DocumentException", e);
    }
    return labeList;
}