javabeanwriter.java

来自「开源的axis2框架的源码。用于开发WEBSERVER」· Java 代码 · 共 1,368 行 · 第 1/4 页

JAVA
1,368
字号

    private boolean minOccursChanged(QName qname, ArrayList missingQNames, BeanWriterMetaInfoHolder metainf) throws SchemaCompilationException {

        boolean minChanged = false;
        QName[] pQNames;

        BeanWriterMetaInfoHolder parentMetainf = metainf.getParent();

        if (parentMetainf != null && !missingQNames.contains(qname)) {

            if (parentMetainf.isOrdered()) {
                pQNames = parentMetainf.getOrderedQNameArray();
            } else {
                pQNames = parentMetainf.getQNameArray();
            }

            for (int j = 0; j < pQNames.length; j++) {
                if (qname.getLocalPart().equals(pQNames[j].getLocalPart())) {

                    if (metainf.getMinOccurs(qname) > parentMetainf.getMinOccurs(pQNames[j])) {
                        minChanged = true;
                    } else if (metainf.getMinOccurs(qname) < parentMetainf.getMinOccurs(pQNames[j])) {
                        throw new SchemaCompilationException(SchemaCompilerMessages.getMessage("minOccurs Wrong!"));
                    }

                }
            }
        }
        return minChanged;
    }

    private boolean maxOccursChanged(QName qname, ArrayList missingQNames, BeanWriterMetaInfoHolder metainf) throws SchemaCompilationException {

        boolean maxChanged = false;
        QName[] pQNames;

        BeanWriterMetaInfoHolder parentMetainf = metainf.getParent();

        if (parentMetainf != null && !missingQNames.contains(qname)) {
            if (parentMetainf.isOrdered()) {
                pQNames = parentMetainf.getOrderedQNameArray();
            } else {
                pQNames = parentMetainf.getQNameArray();
            }

            for (int j = 0; j < pQNames.length; j++) {
                if (qname.getLocalPart().equals(pQNames[j].getLocalPart())) {

                    if (metainf.getMaxOccurs(qname) < parentMetainf.getMaxOccurs(pQNames[j])) {
                        maxChanged = true;
                    } else if (metainf.getMaxOccurs(qname) > parentMetainf.getMaxOccurs(pQNames[j])) {
                        throw new SchemaCompilationException(SchemaCompilerMessages.getMessage("maxOccurs Wrong!"));
                    }
                }
            }
        }
        return maxChanged;
    }

    /**
     * Test whether the given class name matches the default
     *
     * @param javaClassNameForElement
     */
    private boolean isDefault(String javaClassNameForElement) {
        return getDefaultClassName()
                .equals(javaClassNameForElement)
                || getDefaultClassArrayName()
                .equals(javaClassNameForElement);
    }

    /**
     * Given the xml name, make a unique class name taking into account that
     * some file systems are case sensitive and some are not. -Consider the
     * Jax-WS spec for this
     *
     * @param listOfNames
     * @param xmlName
     * @return Returns String.
     */
    private String makeUniqueJavaClassName(List listOfNames, String xmlName) {
        String javaName;
        if (JavaUtils.isJavaKeyword(xmlName)) {
            javaName = JavaUtils.makeNonJavaKeyword(xmlName);
        } else {
            javaName = JavaUtils.capitalizeFirstChar(JavaUtils
                    .xmlNameToJava(xmlName));
        }

        while (listOfNames.contains(javaName.toLowerCase())) {
            javaName = javaName + count++;
        }

        listOfNames.add(javaName.toLowerCase());
        return javaName;
    }

    /**
     * A bit of code from the old code generator. We are better off using the
     * template engines and such stuff that's already there. But the class
     * writers are hard to be reused so some code needs to be repeated (atleast
     * a bit)
     */
    private void loadTemplate() throws SchemaCompilationException {

        // first get the language specific property map
        Class clazz = this.getClass();
        InputStream xslStream;
        String templateName = javaBeanTemplateName;
        if (templateName != null) {
            try {
                xslStream = clazz.getResourceAsStream(templateName);
                templateCache = TransformerFactory.newInstance().newTemplates(
                        new StreamSource(xslStream));
                templateLoaded = true;
            } catch (TransformerConfigurationException e) {
                throw new SchemaCompilationException(SchemaCompilerMessages
                        .getMessage("schema.templateLoadException"), e);
            }
        } else {
            throw new SchemaCompilationException(SchemaCompilerMessages
                    .getMessage("schema.templateNotFoundException"));
        }
    }

    /**
     * Creates the output file
     *
     * @param packageName
     * @param fileName
     * @throws Exception
     */
    private File createOutFile(String packageName, String fileName)
            throws Exception {
        return org.apache.axis2.util.FileWriter.createClassFile(this.rootDir,
                packageName, fileName, ".java");
    }

    /**
     * Writes the output file
     *
     * @param doc
     * @param outputFile
     * @throws Exception
     */
    private void parse(Document doc, File outputFile) throws Exception {
        OutputStream outStream = new FileOutputStream(outputFile);
        XSLTTemplateProcessor.parse(outStream, doc, getTransformer());
        outStream.flush();
        outStream.close();

        PrettyPrinter.prettify(outputFile);
    }

    private Transformer getTransformer() throws TransformerConfigurationException, SchemaCompilationException {
        try {
            return this.templateCache
                    .newTransformer();
        } catch (Exception e){
            // Under some peculiar conditions (classloader issues), just scrap the old templateCache,
            // create a new one and try again.
            loadTemplate();
            return this.templateCache
                    .newTransformer();
        }
    }

    /**
     * Get a prefix for a namespace URI. This method will ALWAYS return a valid
     * prefix - if the given URI is already mapped in this serialization, we
     * return the previous prefix. If it is not mapped, we will add a new
     * mapping and return a generated prefix of the form "ns<num>".
     *
     * @param uri is the namespace uri
     * @return Returns prefix.
     */
    public String getPrefixForURI(String uri) {
        return getPrefixForURI(uri, null);
    }

    /**
     * Last used index suffix for "ns"
     */
    private int lastPrefixIndex = 1;

    /**
     * Map of namespaces URI to prefix(es)
     */
    HashMap mapURItoPrefix = new HashMap();

    HashMap mapPrefixtoURI = new HashMap();

    /**
     * Get a prefix for the given namespace URI. If one has already been defined
     * in this serialization, use that. Otherwise, map the passed default prefix
     * to the URI, and return that. If a null default prefix is passed, use one
     * of the form "ns<num>"
     */
    public String getPrefixForURI(String uri, String defaultPrefix) {
        if ((uri == null) || (uri.length() == 0))
            return null;
        String prefix = (String) mapURItoPrefix.get(uri);
        if (prefix == null) {
            if (defaultPrefix == null || defaultPrefix.length() == 0) {
                prefix = "ns" + lastPrefixIndex++;
                while (mapPrefixtoURI.get(prefix) != null) {
                    prefix = "ns" + lastPrefixIndex++;
                }
            } else {
                prefix = defaultPrefix;
            }
            mapPrefixtoURI.put(prefix, uri);
            mapURItoPrefix.put(uri, prefix);
        }
        return prefix;
    }

    private String getShortTypeName(String typeClassName) {
        if (typeClassName.endsWith("[]")) {
            typeClassName = typeClassName.substring(0, typeClassName
                    .lastIndexOf("["));
        }

        return typeClassName.substring(typeClassName.lastIndexOf(".") + 1,
                typeClassName.length());

    }

    /**
     * Get the mapper class name - there is going to be only one
     * mapper class for the whole
     */
    private String getFullyQualifiedMapperClassName() {
        if (wrapClasses || !writeClasses) {
            return EXTENSION_MAPPER_CLASSNAME;
        } else {
            return mappingClassPackage + "." + EXTENSION_MAPPER_CLASSNAME;
        }
    }

    /**
     * get the mapper class package name
     * May be ignored by the implementer
     */
    public String getExtensionMapperPackageName() {
        return mappingClassPackage;
    }

    /**
     * Sets the mapping class name of this writer. A mapping class
     * package set by the options may be overridden at the this point
     *
     * @param mapperPackageName
     */
    public void registerExtensionMapperPackageName(String mapperPackageName) {
        this.mappingClassPackage = mapperPackageName;
    }

    /**
     * Write the extension classes - this is needed to process
     * the hierarchy of classes
     *
     * @param metainfArray
     */
    public void writeExtensionMapper(BeanWriterMetaInfoHolder[] metainfArray) throws SchemaCompilationException {
        //generate the element
        try {


            String mapperClassName = getFullyQualifiedMapperClassName();

            Document model = XSLTUtils.getDocument();
            Element rootElt = XSLTUtils.getElement(model, "mapper");
            String mapperName = mapperClassName.substring(mapperClassName.lastIndexOf(".") + 1);
            XSLTUtils.addAttribute(model, "name", mapperName, rootElt);
            String basePackageName = "";
            if (mapperClassName.indexOf(".") != -1) {
                basePackageName = mapperClassName.substring(0, mapperClassName.lastIndexOf("."));
                XSLTUtils.addAttribute(model, "package", basePackageName, rootElt);
            } else {
                XSLTUtils.addAttribute(model, "package", "", rootElt);
            }

            if (!wrapClasses) {
                XSLTUtils.addAttribute(model, "unwrapped", "yes", rootElt);
            }

            if (!writeClasses) {
                XSLTUtils.addAttribute(model, "skip-write", "yes", rootElt);
            }

            if (isHelperMode) {
                XSLTUtils.addAttribute(model, "helpermode", "yes", rootElt);
            }

            for (int i = 0; i < metainfArray.length; i++) {
                QName ownQname = metainfArray[i].getOwnQname();
                String className = metainfArray[i].getOwnClassName();
                //do  not add when the qname is not availble
                if (ownQname != null) {
                    Element typeChild = XSLTUtils.addChildElement(model, "type", rootElt);
                    XSLTUtils.addAttribute(model, "nsuri", ownQname.getNamespaceURI(), typeChild);
                    XSLTUtils.addAttribute(model, "classname", className == null ? "" : className, typeChild);
                    XSLTUtils.addAttribute(model, "shortname", ownQname == null ? "" :
                            ownQname.getLocalPart(), typeChild);
                }
            }

            model.appendChild(rootElt);

            if (!templateLoaded) {
                loadTemplate();
            }

            if (wrapClasses) {
                rootElt = (Element) globalWrappedDocument.importNode(rootElt, true);
                //add to the global wrapped document
                globalWrappedDocument.getDocumentElement().appendChild(rootElt);
            } else {
                if (writeClasses) {
                    // create the file
                    File out = createOutFile(basePackageName, mapperName);
                    // parse with the template and create the files
                    parse(model, out);

                }

                // add the model to the model map
                modelMap.put(new QName(mapperName), model);
            }

        } catch (ParserConfigurationException e) {
            throw new SchemaCompilationException(SchemaCompilerMessages.getMessage("schema.docuement.error"), e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SchemaCompilationException(e);
        }


    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?