Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

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

Prototype

List<Element> elements(QName qName);

Source Link

Document

Returns the elements contained in this element with the given fully qualified name.

Usage

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

License:Open Source License

private Map _readLiferayDisplayXML(String servletContextName, String xml)
        throws DocumentException, IOException {

    Map categories = new LinkedHashMap();

    if (xml == null) {
        return categories;
    }//from   w  w  w.java  2s.  c  om

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(null);

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

    Set portletIds = new HashSet();

    Iterator itr1 = doc.getRootElement().elements("category").iterator();

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

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

        List portlets = new ArrayList();

        Iterator itr2 = category.elements("portlet").iterator();

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

            String portletId = portlet.attributeValue("id");
            if (servletContextName != null) {
                portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
            }

            portletIds.add(portletId);

            String status = portlet.attributeValue("status");

            portlets.add(new KeyValuePair(portletId, status));
        }

        if (portlets.size() > 0) {
            categories.put(name, portlets);
        }
    }

    // Portlets that do not belong to any categories should default to the
    // Undefined category

    List undefinedPortlets = new ArrayList();

    itr1 = _getPortletsPool().values().iterator();

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

        String portletId = portlet.getPortletId();

        if ((servletContextName != null) && (portlet.isWARFile())
                && (portletId.startsWith(servletContextName) && (!portletIds.contains(portletId)))) {

            undefinedPortlets.add(new KeyValuePair(portletId, null));
        } else if ((servletContextName == null) && (!portlet.isWARFile())
                && (!portletIds.contains(portletId))) {

            undefinedPortlets.add(new KeyValuePair(portletId, null));
        }
    }

    if (undefinedPortlets.size() > 0) {
        categories.put("category.undefined", undefinedPortlets);
    }

    return categories;
}

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

License:Open Source License

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

    Set liferayPortletIds = new HashSet();

    if (xml == null) {
        return liferayPortletIds;
    }//ww w  .j ava 2  s  .co  m

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(null);

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

    Element root = doc.getRootElement();

    Map customUserAttributes = new HashMap();

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

    while (itr.hasNext()) {
        Element customUserAttribute = (Element) itr.next();

        String name = customUserAttribute.attributeValue("name");
        String customClass = customUserAttribute.attributeValue("custom-class");

        customUserAttributes.put(name, customClass);
    }

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

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

        String portletId = portlet.attributeValue("id");
        if (servletContextName != null) {
            portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
        }

        liferayPortletIds.add(portletId);

        Portlet portletModel = (Portlet) portletsPool.get(portletId);

        if (portletModel != null) {
            portletModel.setStrutsPath(
                    GetterUtil.get(portlet.attributeValue("struts-path"), portletModel.getStrutsPath()));
            portletModel.setIndexerClass(
                    GetterUtil.get(portlet.attributeValue("indexer-class"), portletModel.getIndexerClass()));
            portletModel.setSchedulerClass(GetterUtil.get(portlet.attributeValue("scheduler-class"),
                    portletModel.getSchedulerClass()));
            portletModel.setPreferencesSharingType(
                    GetterUtil.get(portlet.attributeValue("preferences-sharing-type"),
                            portletModel.getPreferencesSharingType()));
            portletModel.setUseDefaultTemplate(GetterUtil.get(portlet.attributeValue("use-default-template"),
                    portletModel.isUseDefaultTemplate()));
            portletModel.setShowPortletAccessDenied(
                    GetterUtil.get(portlet.attributeValue("show-portlet-access-denied"),
                            portletModel.isShowPortletAccessDenied()));
            portletModel.setShowPortletInactive(GetterUtil.get(portlet.attributeValue("show-portlet-inactive"),
                    portletModel.isShowPortletInactive()));
            portletModel.setRestoreCurrentView(GetterUtil.get(portlet.attributeValue("restore-current-view"),
                    portletModel.isRestoreCurrentView()));
            portletModel.setNs4Compatible(
                    GetterUtil.get(portlet.attributeValue("ns-4-compatible"), portletModel.isNs4Compatible()));
            portletModel.setNarrow(GetterUtil.get(portlet.attributeValue("narrow"), portletModel.isNarrow()));
            portletModel.setActive(GetterUtil.get(portlet.attributeValue("active"), portletModel.isActive()));
            portletModel
                    .setInclude(GetterUtil.get(portlet.attributeValue("include"), portletModel.isInclude()));

            portletModel.getCustomUserAttributes().putAll(customUserAttributes);
        }
    }

    return liferayPortletIds;
}

From source file:com.liferay.portal.events.InitAction.java

License:Open Source License

public void run(String[] ids) throws ActionException {

    // Set default locale

    String userLanguage = SystemProperties.get("user.language");
    String userCountry = SystemProperties.get("user.country");
    String userVariant = SystemProperties.get("user.variant");

    if (Validator.isNull(userVariant)) {
        Locale.setDefault(new Locale(userLanguage, userCountry));
    } else {/*from   w  w  w  .j a  v  a2 s . c  om*/
        Locale.setDefault(new Locale(userLanguage, userCountry, userVariant));
    }

    // Log4J

    if (GetterUtil.get(PropsUtil.get(PropsUtil.LOG_CONFIGURE_LOG4J), true) && !ServerDetector.isSun()) {

        URL portalLog4jUrl = getClass().getClassLoader().getResource("META-INF/portal-log4j.xml");

        if (Logger.getRootLogger().getAllAppenders() instanceof NullEnumeration) {

            DOMConfigurator.configure(portalLog4jUrl);
        } else {
            Set currentLoggerNames = new HashSet();

            Enumeration enu = LogManager.getCurrentLoggers();

            while (enu.hasMoreElements()) {
                Logger logger = (Logger) enu.nextElement();

                currentLoggerNames.add(logger.getName());
            }

            try {
                SAXReader reader = new SAXReader();

                Document doc = reader.read(portalLog4jUrl);

                Element root = doc.getRootElement();

                Iterator itr = root.elements("category").iterator();

                while (itr.hasNext()) {
                    Element category = (Element) itr.next();

                    String name = category.attributeValue("name");
                    String priority = category.element("priority").attributeValue("value");

                    Logger logger = Logger.getLogger(name);

                    logger.setLevel(Level.toLevel(priority));
                }
            } catch (Exception e) {
                com.dotmarketing.util.Logger.error(this, e.getMessage(), e);
            }
        }
    }
}

From source file:com.liferay.portal.tools.EJBXMLBuilder.java

License:Open Source License

private String _buildPramatiXMLRefs(Element entity) {
    StringBuffer sb = new StringBuffer();

    Iterator itr = entity.elements("ejb-local-ref").iterator();

    while (itr.hasNext()) {
        Element ejbRef = (Element) itr.next();

        sb.append("\t\t\t<ejb-local-ref>\n");
        sb.append("\t\t\t\t<ejb-ref-name>").append(ejbRef.elementText("ejb-ref-name"))
                .append("</ejb-ref-name>\n");
        sb.append("\t\t\t\t<ejb-link>").append(ejbRef.elementText("ejb-ref-name")).append("__PRAMATI_LOCAL")
                .append("</ejb-link>\n");
        sb.append("\t\t\t</ejb-local-ref>\n");
    }//w w  w .  j  a va  2  s. co m

    return sb.toString();
}

From source file:com.liferay.portal.tools.EJBXMLBuilder.java

License:Open Source License

private void _buildWebSphereXML() throws Exception {
    StringBuffer sb = new StringBuffer();

    sb.append("<?xml version=\"1.0\"?>\n");

    sb.append(// ww w.j  a  va  2  s  .c  o  m
            "\n<com.ibm.ejs.models.base.bindings.ejbbnd:EJBJarBinding xmlns:com.ibm.ejs.models.base.bindings.ejbbnd=\"ejbbnd.xmi\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:com.ibm.ejs.models.base.bindings.commonbnd=\"commonbnd.xmi\" xmlns:com.ibm.etools.ejb=\"ejb.xmi\" xmlns:com.ibm.etools.j2ee.common=\"common.xmi\" xmi:version=\"2.0\" xmi:id=\"ejb-jar_ID_Bnd\" currentBackendId=\"CLOUDSCAPE_V50_1\">\n");
    sb.append("\t<ejbJar href=\"META-INF/ejb-jar.xml#ejb-jar_ID\" />\n");

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new EntityResolver());

    Document doc = reader.read(new File("classes/META-INF/ejb-jar.xml"));

    int sessionCount = 0;
    int ejbLocalRefCount = 0;

    Iterator itr1 = doc.getRootElement().element("enterprise-beans").elements("session").iterator();

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

        sb.append("\t<ejbBindings xmi:id=\"Session_").append(++sessionCount).append("_Bnd\" jndiName=\"");

        if (sessionEl.elementText("display-name").endsWith("LocalManagerEJB")) {
            sb.append("ejb/liferay/").append(sessionEl.elementText("display-name")).append("Home");
        } else {
            sb.append(sessionEl.elementText("ejb-name"));
        }

        sb.append("\">\n");

        sb.append(
                "\t\t<enterpriseBean xmi:type=\"com.ibm.etools.ejb:Session\" href=\"META-INF/ejb-jar.xml#Session_")
                .append(sessionCount).append("\" />\n");

        Iterator itr2 = sessionEl.elements("ejb-local-ref").iterator();

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

            sb.append("\t\t<ejbRefBindings xmi:id=\"EjbRefBinding_").append(++ejbLocalRefCount)
                    .append("\" jndiName=\"").append(ejbLocalRefEl.elementText("ejb-ref-name")).append("\">\n");
            sb.append(
                    "\t\t\t<bindingEjbRef xmi:type=\"com.ibm.etools.j2ee.common:EJBLocalRef\" href=\"META-INF/ejb-jar.xml#EjbRef_")
                    .append(ejbLocalRefCount).append("\" />\n");
            sb.append("\t\t</ejbRefBindings>\n");
        }

        sb.append("\t</ejbBindings>\n");
    }

    sb.append("</com.ibm.ejs.models.base.bindings.ejbbnd:EJBJarBinding>");

    File outputFile = new File("classes/META-INF/ibm-ejb-jar-bnd.xmi");

    if (!outputFile.exists() || !FileUtil.read(outputFile).equals(sb.toString())) {

        FileUtil.write(outputFile, sb.toString());

        Logger.info(EJBXMLBuilder.class, outputFile.toString());
    }
}

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   ww w . jav  a 2  s .  c o 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  a2s  .  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 _createRemotingXml() throws Exception {
    StringBundler sb = new StringBundler();

    SAXReader saxReader = _getSAXReader();

    Document document = saxReader.read(new File(_springFileName));

    Element rootElement = document.getRootElement();

    List<Element> beanElements = rootElement.elements("bean");

    for (Element beanElement : beanElements) {
        String beanId = beanElement.attributeValue("id");

        if (beanId.endsWith("Service") && !beanId.endsWith("LocalService")) {

            String entityName = beanId;

            entityName = StringUtil.replaceLast(entityName, ".service.", ".");

            int pos = entityName.lastIndexOf("Service");

            entityName = entityName.substring(0, pos);

            Entity entity = getEntity(entityName);

            String serviceName = beanId;

            String serviceMapping = serviceName;

            serviceMapping = StringUtil.replaceLast(serviceMapping, ".service.", ".service.spring.");
            serviceMapping = StringUtil.replace(serviceMapping, StringPool.PERIOD, StringPool.UNDERLINE);

            Map<String, Object> context = _getContext();

            context.put("entity", entity);
            context.put("serviceName", serviceName);
            context.put("serviceMapping", serviceMapping);

            sb.append(_processTemplate(_tplRemotingXml, context));
        }//from w  w  w .  ja v  a2  s.  com
    }

    File outputFile = new File(_remotingFileName);

    if (!outputFile.exists()) {
        return;
    }

    String content = FileUtils.readFileToString(outputFile);
    String newContent = content;

    int x = content.indexOf("<bean ");
    int y = content.lastIndexOf("</bean>") + 8;

    if (x != -1) {
        newContent = content.substring(0, x - 1) + sb.toString() + content.substring(y);
    } else {
        x = content.indexOf("</beans>");

        if (x != -1) {
            newContent = content.substring(0, x) + sb.toString() + content.substring(x);
        } else {
            x = content.indexOf("<beans/>");
            y = x + 8;

            newContent = content.substring(0, x) + "<beans>" + sb.toString() + "</beans>"
                    + content.substring(y);
        }
    }

    writeFileRaw(outputFile, _formatXml(newContent), _modifiedFileNames);
}

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 .  j a v  a2s. com

        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.portal.tools.WebSiteBuilder.java

License:Open Source License

public static List getWebSites() throws Exception {
    File file = new File("../web-sites/web-sites.xml");

    SAXReader reader = new SAXReader();

    Document doc = null;/* w  w  w . ja v  a 2  s  .c om*/

    try {
        doc = reader.read(file);
    } catch (DocumentException de) {
        Logger.error(WebSiteBuilder.class, de.getMessage(), de);
    }

    Element root = doc.getRootElement();

    List webSites = new ArrayList();

    Iterator itr = root.elements("web-site").iterator();

    while (itr.hasNext()) {
        Element webSite = (Element) itr.next();

        String id = webSite.attributeValue("id");
        boolean httpEnabled = GetterUtil.getBoolean(webSite.attributeValue("http-enabled"), true);
        String keystore = GetterUtil.getString(webSite.attributeValue("keystore"));
        String keystorePassword = GetterUtil.getString(webSite.attributeValue("keystore-password"));
        String virtualHosts = GetterUtil.getString(webSite.attributeValue("virtual-hosts"));
        String forwardURL = GetterUtil.getString(webSite.attributeValue("forward-url"), "/c");

        webSites.add(new WebSite(id, httpEnabled, keystore, keystorePassword, virtualHosts, forwardURL));
    }

    return webSites;
}