Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

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

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.guzz.builder.GuzzConfigFileBuilder.java

License:Apache License

/**
 * ?sql?sql?ObjectMapping?<sqlMap></sqlMap>orm?sqlMap
 * ?? @link ObjectMappingManager ?sqlMapsql?
 * @return (@link Map) id~~CompiledSQL// w w  w .  j av a 2s.  c om
 */
public static Map loadSQLMap(GuzzContext gf, TemplatedSQLService templatedSQLService, ObjectMappingManager omm,
        CompiledSQLBuilder compiledSQLBuilder, Element fragment, boolean registerIdToTemplatedService)
        throws IOException, ClassNotFoundException {
    /*
    <sqlMap dbgroup="user">
       <select id="selectUser" orm="user">
    select * from @@user where @id = :id 
       </select>
            
       <update id="updateUserFavCount" orm="userObjectMap">
    update @@user set @favCount = favCount + 1
       </update>
               
       <select id="selectUsers" orm="userObjectMap">
    select @id, @name, @vip, @favCount from @@user
       </select>
               
       <orm id="userObjectMap" class="org.guzz.test.UserModel" dbgroup="user">
    <generator  class="native" >
       <param name="column" value="pk" />
    </generator>
            
    <result property="id" column="pk"/>
     <result property="name" column="userName"/>
     <result property="favCount" column="FAV_COUNT"/>
     <result property="vip" column="VIP_USER"/>
       </orm>
    </sqlMap>
     */

    if (!"sqlMap".equals(fragment.getName())) {
        throw new GuzzException("xml fragment should be insided in <sqlMap></sqlMap>");
    }

    String m_dbgroup = fragment.attributeValue("dbgroup");

    //???sqlmaporm?ormglobal orm
    List orms = fragment.selectNodes("orm");
    HashMap local_orms = new HashMap();

    for (int i = 0; i < orms.size(); i++) {
        Element e = (Element) orms.get(i);
        ResultMapBasedObjectMapping m_orm = loadORM(gf, m_dbgroup, e);

        String[] ids = m_orm.getUniqueName();

        for (int k = 0; k < ids.length; k++) {
            local_orms.put(ids[k], m_orm);
        }
    }

    HashMap css = new HashMap();

    //select?@xxxormupdate??
    List select_nodes = fragment.selectNodes("select");
    for (int i = 0; i < select_nodes.size(); i++) {
        Element s_node = (Element) select_nodes.get(i);
        String m_id = s_node.attributeValue("id");
        String m_orm = s_node.attributeValue("orm");
        String resultClass = s_node.attributeValue("result-class");
        boolean templated = "true".equalsIgnoreCase(s_node.attributeValue("templated"));
        String value = s_node.getTextTrim();
        value = StringUtil.replaceString(value, "\r\n", " ");
        value = StringUtil.replaceString(value, "\n", " ");

        if (registerIdToTemplatedService && m_id == null) {
            throw new InvalidConfigurationException("attribute id is required! xml:" + s_node.asXML());
        }

        Class beanCls = StringUtil.notEmpty(resultClass) ? ClassUtil.getClass(resultClass) : null;
        CompiledSQL cs = null;

        ObjectMapping localORM = (ObjectMapping) local_orms.get(m_orm);
        if (localORM != null) {
            if (templated) {
                if (registerIdToTemplatedService) {
                    cs = TemplatedCompiledSQL.buildAndRegisterById(templatedSQLService, localORM, m_id, value);
                } else {
                    cs = TemplatedCompiledSQL.buildBySql(templatedSQLService, localORM, value);
                }
            } else {
                cs = compiledSQLBuilder.buildCompiledSQL(localORM, value);
            }
        } else {
            if (templated) {
                if (registerIdToTemplatedService) {
                    cs = TemplatedCompiledSQL.buildAndRegisterById(templatedSQLService, m_orm, m_id, value);
                } else {
                    cs = TemplatedCompiledSQL.buildBySql(templatedSQLService, m_orm, value);
                }
            } else {
                cs = compiledSQLBuilder.buildCompiledSQL(m_orm, value);
            }
        }

        if (beanCls != null) {
            cs.setResultClass(beanCls);
        }

        //Register parameters' types.
        loadParamPropsMapping(cs, (Element) s_node.selectSingleNode("paramsMapping"));

        css.put(m_id, cs);
    }

    List update_nodes = fragment.selectNodes("update");
    for (int i = 0; i < update_nodes.size(); i++) {
        Element s_node = (Element) update_nodes.get(i);
        String m_id = s_node.attributeValue("id");
        String m_orm = s_node.attributeValue("orm");
        boolean templated = "true".equalsIgnoreCase(s_node.attributeValue("templated"));
        String value = s_node.getTextTrim();
        value = StringUtil.replaceString(value, "\r\n", " ");
        value = StringUtil.replaceString(value, "\n", " ");

        ObjectMapping localORM = (ObjectMapping) local_orms.get(m_orm);
        CompiledSQL cs = null;

        if (localORM != null) {
            if (templated) {
                cs = compiledSQLBuilder.buildTemplatedCompiledSQL(localORM, value);
            } else {
                cs = compiledSQLBuilder.buildCompiledSQL(localORM, value);
            }
        } else {
            if (templated) {
                cs = compiledSQLBuilder.buildTemplatedCompiledSQL(m_orm, value);
            } else {
                cs = compiledSQLBuilder.buildCompiledSQL(m_orm, value);
            }
        }

        //Register parameters' types.
        loadParamPropsMapping(cs, (Element) s_node.selectSingleNode("paramsMapping"));

        css.put(m_id, cs);
    }

    return css;
}

From source file:org.guzz.builder.HbmXMLBuilder.java

License:Apache License

public static POJOBasedObjectMapping parseHbmStream(final GuzzContextImpl gf, String dbGroupName,
        BusinessValidChecker checker, String businessName, Class overridedDomainClass, Class interpreterClass,
        InputStream is) throws DocumentException, IOException, SAXException, ClassNotFoundException {

    SAXReader reader = null;//w  w w .jav  a  2  s  . c om
    Document document = null;

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    document = reader.read(is);
    final Element root = document.getRootElement();

    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = getDomainClassDbGroup(root);
    }
    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = "default";
    }

    final DBGroup dbGroup = gf.getDBGroup(dbGroupName);

    final SimpleTable st = new SimpleTable(dbGroup.getDialect());
    final POJOBasedObjectMapping map = new POJOBasedObjectMapping(gf, dbGroup, st);

    if (overridedDomainClass == null) {//hbm?className
        String m_class = HbmXMLBuilder.getDomainClassName(root);

        overridedDomainClass = ClassUtil.getClass(m_class);
    }

    if (checker != null && !checker.shouldParse(overridedDomainClass)) {
        return null;
    }

    if (StringUtil.isEmpty(businessName)) {
        businessName = getDomainClassBusinessName(root);
    }

    final Business business = gf.instanceNewGhost(businessName, dbGroup.getGroupName(), interpreterClass,
            overridedDomainClass);
    if (business.getInterpret() == null) {
        throw new GuzzException("cann't create new instance of business: " + business.getName());
    }

    business.setTable(st);
    business.setMapping(map);

    //?business??
    if (business.getName() != null) {
        st.setBusinessName(business.getName());
    } else {
        st.setBusinessName(business.getDomainClass().getName());
    }

    //properties defined.
    final LinkedList props = new LinkedList();

    Visitor visitor = new VisitorSupport() {

        private String packageName;

        public void visit(Element e) {

            //package
            if ("hibernate-mapping".equalsIgnoreCase(e.getName())
                    || "guzz-mapping".equalsIgnoreCase(e.getName())) {
                this.packageName = e.attributeValue("package");

            } else if ("class".equalsIgnoreCase(e.getName())) {
                String className = e.attributeValue("name");
                String tableName = e.attributeValue("table");
                String shadow = e.attributeValue("shadow");
                boolean dynamicUpdate = StringUtil.toBoolean(e.attributeValue("dynamic-update"), false);

                if (StringUtil.notEmpty(this.packageName)) {
                    className = this.packageName + "." + className;
                }

                //business????hbml.xml?class namebusinessclass
                Class cls = business.getDomainClass();
                if (cls == null) { //?business?domainClassName
                    cls = ClassUtil.getClass(className);
                }

                Assert.assertNotNull(cls, "invalid class name");
                Assert.assertNotEmpty(tableName, "invalid table name");

                JavaBeanWrapper configBeanWrapper = BeanWrapper.createPOJOWrapper(cls);
                business.setDomainClass(cls);
                business.setConfiguredBeanWrapper(configBeanWrapper);

                map.setBusiness(business);

                //shadow?tableName?
                if (StringUtil.notEmpty(shadow)) {
                    ShadowTableView sv = (ShadowTableView) BeanCreator.newBeanInstance(shadow);
                    sv.setConfiguredTableName(tableName);

                    //CustomTableViewShadowTableView
                    if (sv instanceof CustomTableView) {
                        CustomTableView ctv = (CustomTableView) sv;
                        ctv.setConfiguredObjectMapping(map);

                        st.setCustomTableView(ctv);
                    }

                    st.setShadowTableView(sv);
                    gf.registerShadowTableView(sv);
                }

                //TODO: ???
                st.setTableName(tableName);
                st.setDynamicUpdate(dynamicUpdate);

            } else if ("id".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);

                st.addPKColumn(col);

            } else if ("version".equalsIgnoreCase(e.getName())) {
                //see: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 5.1.9. Version (optional)
                //TODO: annotation?version?

                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);
                col.setAllowInsert(insertIt);

                st.addVersionColumn(col);

            } else if ("property".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String nullValue = e.attributeValue("null");
                String lazy = e.attributeValue("lazy");
                String loader = e.attributeValue("loader");

                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                boolean updateIt = StringUtil.toBoolean(e.attributeValue("update"), true);

                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, loader);
                col.setNullValue(nullValue);
                col.setAllowInsert(insertIt);
                col.setAllowUpdate(updateIt);
                col.setLazy("true".equalsIgnoreCase(lazy));

                st.addColumn(col);
            }
        }
    };

    root.accept(visitor);

    //?generator
    //?generator?
    List generator = root.selectNodes("//class/id/generator");
    if (generator.size() != 1) {
        throw new GuzzException("id generator is not found for business: " + business);
    }

    Element ge = (Element) generator.get(0);

    String m_clsName = ge.attributeValue("class");

    if ("native".equalsIgnoreCase(m_clsName)) { //nativegeneratordialect?
        m_clsName = dbGroup.getDialect().getNativeIDGenerator();
    }

    String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(m_clsName);
    if (realClassName == null) {
        realClassName = m_clsName;
    }

    IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName);

    //?generator??      
    List m_params = ge.selectNodes("param");
    Properties p = new Properties();
    for (int i = 0; i < m_params.size(); i++) {
        Element mp = (Element) m_params.get(i);
        p.put(mp.attributeValue("name"), mp.getTextTrim());
    }

    if (ig instanceof Configurable) {
        ((Configurable) ig).configure(dbGroup.getDialect(), map, p);
    }

    //register callback for GuzzContext's full starting.
    if (ig instanceof GuzzContextAware) {
        gf.registerContextStartedAware((GuzzContextAware) ig);
    }

    st.setIdentifierGenerator(ig);

    return map;
}

From source file:org.hibernate.build.gradle.publish.auth.maven.DomHelper.java

License:Open Source License

public static String extractValue(Element element) {
    if (element == null) {
        return null;
    }/*from  w w  w.  j a v  a2  s. c o  m*/

    final String value = element.getTextTrim();
    if (value != null && value.length() == 0) {
        return null;
    }

    return value;
}

From source file:org.hibernate.build.gradle.upload.StandardMavenAuthenticationProvider.java

License:Open Source License

private String extractValue(Element element) {
    if (element == null) {
        return null;
    }/*from  w w  w. j  a  va  2 s.co m*/

    final String value = element.getTextTrim();
    if (value != null && value.length() == 0) {
        return null;
    }

    return value;
}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

/**
 * Adds a @MapKeyEnumerated annotation to the specified annotationList if the specified element
 * contains a map-key-enumerated sub-element. This should only be the case for
 * element-collection, many-to-many, or one-to-many associations.
 *//* w ww  .j a  v a2  s.  co m*/
private void getMapKeyEnumerated(List<Annotation> annotationList, Element element) {
    Element subelement = element != null ? element.element("map-key-enumerated") : null;
    if (subelement != null) {
        AnnotationDescriptor ad = new AnnotationDescriptor(MapKeyEnumerated.class);
        EnumType value = EnumType.valueOf(subelement.getTextTrim());
        ad.setValue("value", value);
        annotationList.add(AnnotationFactory.create(ad));
    }
}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

/**
 * Adds a @MapKeyTemporal annotation to the specified annotationList if the specified element
 * contains a map-key-temporal sub-element. This should only be the case for element-collection,
 * many-to-many, or one-to-many associations.
 *//*  w  w  w  .j  a  va2 s . c o  m*/
private void getMapKeyTemporal(List<Annotation> annotationList, Element element) {
    Element subelement = element != null ? element.element("map-key-temporal") : null;
    if (subelement != null) {
        AnnotationDescriptor ad = new AnnotationDescriptor(MapKeyTemporal.class);
        TemporalType value = TemporalType.valueOf(subelement.getTextTrim());
        ad.setValue("value", value);
        annotationList.add(AnnotationFactory.create(ad));
    }
}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

private void getEnumerated(List<Annotation> annotationList, Element element) {
    Element subElement = element != null ? element.element("enumerated") : null;
    if (subElement != null) {
        AnnotationDescriptor ad = new AnnotationDescriptor(Enumerated.class);
        String enumerated = subElement.getTextTrim();
        if ("ORDINAL".equalsIgnoreCase(enumerated)) {
            ad.setValue("value", EnumType.ORDINAL);
        } else if ("STRING".equalsIgnoreCase(enumerated)) {
            ad.setValue("value", EnumType.STRING);
        } else if (StringHelper.isNotEmpty(enumerated)) {
            throw new AnnotationException("Unknown EnumType: " + enumerated + ". " + SCHEMA_VALIDATION);
        }//w ww .j ava 2 s  .  com
        annotationList.add(AnnotationFactory.create(ad));
    }
}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

private void getTemporal(List<Annotation> annotationList, Element element) {
    Element subElement = element != null ? element.element("temporal") : null;
    if (subElement != null) {
        AnnotationDescriptor ad = new AnnotationDescriptor(Temporal.class);
        String temporal = subElement.getTextTrim();
        if ("DATE".equalsIgnoreCase(temporal)) {
            ad.setValue("value", TemporalType.DATE);
        } else if ("TIME".equalsIgnoreCase(temporal)) {
            ad.setValue("value", TemporalType.TIME);
        } else if ("TIMESTAMP".equalsIgnoreCase(temporal)) {
            ad.setValue("value", TemporalType.TIMESTAMP);
        } else if (StringHelper.isNotEmpty(temporal)) {
            throw new AnnotationException("Unknown TemporalType: " + temporal + ". " + SCHEMA_VALIDATION);
        }//from   w  ww .j  av a  2  s.  com
        annotationList.add(AnnotationFactory.create(ad));
    }
}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

public static List<NamedStoredProcedureQuery> buildNamedStoreProcedureQueries(Element element,
        XMLContext.Default defaults) {//from   ww  w . j a  v  a  2s  . c  o  m
    if (element == null) {
        return new ArrayList<NamedStoredProcedureQuery>();
    }
    List namedStoredProcedureElements = element.elements("named-stored-procedure-query");
    List<NamedStoredProcedureQuery> namedStoredProcedureQueries = new ArrayList<NamedStoredProcedureQuery>();
    for (Object obj : namedStoredProcedureElements) {
        Element subElement = (Element) obj;
        AnnotationDescriptor ann = new AnnotationDescriptor(NamedStoredProcedureQuery.class);
        copyStringAttribute(ann, subElement, "name", true);
        copyStringAttribute(ann, subElement, "procedure-name", true);

        List<Element> elements = subElement.elements("parameter");
        List<StoredProcedureParameter> storedProcedureParameters = new ArrayList<StoredProcedureParameter>();

        for (Element parameterElement : elements) {
            AnnotationDescriptor parameterDescriptor = new AnnotationDescriptor(StoredProcedureParameter.class);
            copyStringAttribute(parameterDescriptor, parameterElement, "name", false);
            String modeValue = parameterElement.attributeValue("mode");
            if (modeValue == null) {
                parameterDescriptor.setValue("mode", ParameterMode.IN);
            } else {
                parameterDescriptor.setValue("mode", ParameterMode.valueOf(modeValue.toUpperCase(Locale.ROOT)));
            }
            String clazzName = parameterElement.attributeValue("class");
            Class clazz;
            try {
                clazz = ReflectHelper.classForName(XMLContext.buildSafeClassName(clazzName, defaults),
                        JPAOverriddenAnnotationReader.class);
            } catch (ClassNotFoundException e) {
                throw new AnnotationException("Unable to find entity-class: " + clazzName, e);
            }
            parameterDescriptor.setValue("type", clazz);
            storedProcedureParameters
                    .add((StoredProcedureParameter) AnnotationFactory.create(parameterDescriptor));
        }

        ann.setValue("parameters", storedProcedureParameters
                .toArray(new StoredProcedureParameter[storedProcedureParameters.size()]));

        elements = subElement.elements("result-class");
        List<Class> returnClasses = new ArrayList<Class>();
        for (Element classElement : elements) {
            String clazzName = classElement.getTextTrim();
            Class clazz;
            try {
                clazz = ReflectHelper.classForName(XMLContext.buildSafeClassName(clazzName, defaults),
                        JPAOverriddenAnnotationReader.class);
            } catch (ClassNotFoundException e) {
                throw new AnnotationException("Unable to find entity-class: " + clazzName, e);
            }
            returnClasses.add(clazz);
        }
        ann.setValue("resultClasses", returnClasses.toArray(new Class[returnClasses.size()]));

        elements = subElement.elements("result-set-mapping");
        List<String> resultSetMappings = new ArrayList<String>();
        for (Element resultSetMappingElement : elements) {
            resultSetMappings.add(resultSetMappingElement.getTextTrim());
        }
        ann.setValue("resultSetMappings", resultSetMappings.toArray(new String[resultSetMappings.size()]));
        elements = subElement.elements("hint");
        buildQueryHints(elements, ann);
        namedStoredProcedureQueries.add((NamedStoredProcedureQuery) AnnotationFactory.create(ann));
    }
    return namedStoredProcedureQueries;

}

From source file:org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader.java

License:LGPL

private static void buildUniqueConstraints(AnnotationDescriptor annotation, Element element) {
    List uniqueConstraintElementList = element.elements("unique-constraint");
    UniqueConstraint[] uniqueConstraints = new UniqueConstraint[uniqueConstraintElementList.size()];
    int ucIndex = 0;
    Iterator ucIt = uniqueConstraintElementList.listIterator();
    while (ucIt.hasNext()) {
        Element subelement = (Element) ucIt.next();
        List<Element> columnNamesElements = subelement.elements("column-name");
        String[] columnNames = new String[columnNamesElements.size()];
        int columnNameIndex = 0;
        Iterator it = columnNamesElements.listIterator();
        while (it.hasNext()) {
            Element columnNameElt = (Element) it.next();
            columnNames[columnNameIndex++] = columnNameElt.getTextTrim();
        }/*w w w.j  a  va  2s  .c  o  m*/
        AnnotationDescriptor ucAnn = new AnnotationDescriptor(UniqueConstraint.class);
        copyStringAttribute(ucAnn, subelement, "name", false);
        ucAnn.setValue("columnNames", columnNames);
        uniqueConstraints[ucIndex++] = AnnotationFactory.create(ucAnn);
    }
    annotation.setValue("uniqueConstraints", uniqueConstraints);
}