text:
package org.apache.axis2.description.java2wsdl;

import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.jaxrs.JAXRSUtils;
import org.apache.axis2.jaxrs.JAXRSModel;
import org.apache.axis2.util.JavaUtils;
import org.apache.axis2.deployment.util.BeanExcludeInfo;
import org.apache.axis2.deployment.util.Utils;
import org.apache.axis2.description.*;
import org.apache.axis2.description.java2wsdl.bytecode.MethodTable;
import org.apache.axis2.jsr181.JSR181Helper;
import org.apache.axis2.jsr181.WebMethodAnnotation;
import org.apache.axis2.jsr181.WebParamAnnotation;
import org.apache.axis2.jsr181.WebResultAnnotation;
import org.apache.axis2.jsr181.WebServiceAnnotation;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.commons.schema.*;
import org.apache.ws.commons.schema.utils.NamespaceMap;
import org.apache.ws.commons.schema.utils.NamespacePrefixList;
import org.w3c.dom.Document;

import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import java.beans.PropertyDescriptor;
import java.beans.BeanInfo;
import java.beans.Introspector;

public class DefaultSchemaGenerator implements Java2WSDLConstants, SchemaGenerator {

    private static final Log log = LogFactory.getLog(DefaultSchemaGenerator.class);

    public static final String NAME_SPACE_PREFIX = "ax2";// axis2 name space

    private static int prefixCount = 1;

    private JAXRSModel classModel;

    protected Map<String,String> targetNamespacePrefixMap = new Hashtable<String,String>();

    protected Map<String,XmlSchema> schemaMap = new Hashtable<String,XmlSchema>();

    protected XmlSchemaCollection xmlSchemaCollection = new XmlSchemaCollection();

    protected ClassLoader classLoader;

    protected String className;

    protected TypeTable typeTable = new TypeTable();

    // to keep loadded method using JAM
    protected Method methods[];

    //to store byte code method using Axis 1.x codes
    protected MethodTable methodTable;

    protected String schemaTargetNameSpace;

    protected String schema_namespace_prefix;

    protected String attrFormDefault = null;

    protected String elementFormDefault = null;

    protected ArrayList<String> excludeMethods = new ArrayList<String>();

    protected ArrayList<String> extraClasses = null;

    protected boolean useWSDLTypesNamespace = false;

    protected Map<String,String> pkg2nsmap = null;

    protected NamespaceGenerator nsGen = null;

    protected String targetNamespace = null;
    //to keep the list of operations which use other MR not RPC MR
    protected ArrayList<String> nonRpcMethods = new ArrayList<String>();

    protected Class<?> serviceClass = null;
    protected AxisService service;
    // location of the custom schema , if any
    protected String customSchemaLocation;
    // location of the class name to package mapping file
    // File is simple file with qualifiedClassName:SchemaQName
    protected String mappingFileLocation;

    //To check whether we need to generate Schema element for Exception
    protected boolean generateBaseException;

    protected boolean sortAttributes = true;

    protected boolean isGenerateWrappedArrayTypes = false;

    public NamespaceGenerator getNsGen() throws Exception {
        if (nsGen == null) {
            nsGen = new DefaultNamespaceGenerator();
        }
        return nsGen;
    }

    public void setNsGen(NamespaceGenerator nsGen) {
        this.nsGen = nsGen;
    }

    public DefaultSchemaGenerator(ClassLoader loader, String className,
                                  String schematargetNamespace,
                                  String schematargetNamespacePrefix,
                                  AxisService service)
            throws Exception {
        this.classLoader = loader;
        this.className = className;
        this.service = service;

        serviceClass = Class.forName(className, true, loader);
        methodTable = new MethodTable(serviceClass);

        this.targetNamespace = Java2WSDLUtils.targetNamespaceFromClassName(
                className, loader, getNsGen()).toString();

        if (schematargetNamespace != null
                && schematargetNamespace.trim().length() != 0) {
            this.schemaTargetNameSpace = schematargetNamespace;
        } else {
            this.schemaTargetNameSpace =
                    Java2WSDLUtils.schemaNamespaceFromClassName(className, loader, getNsGen())
                            .toString();
        }

        if (schematargetNamespacePrefix != null
                && schematargetNamespacePrefix.trim().length() != 0) {
            this.schema_namespace_prefix = schematargetNamespacePrefix;
        } else {
            this.schema_namespace_prefix = SCHEMA_NAMESPACE_PRFIX;
        }
        if (service !=null ) {
            Parameter sortAtt = service.getParameter("SortAttributes");
            if (sortAtt !=null && "false".equals(sortAtt.getValue())){
                sortAttributes = false;
            }

            Parameter generateWrappedArrayTypes = service.getParameter("generateWrappedArrayTypes");
            if ((generateWrappedArrayTypes != null) && JavaUtils.isTrue(generateWrappedArrayTypes.getValue())){
               isGenerateWrappedArrayTypes = true;
            }

            Parameter extraClassesParam = service.getParameter("extraClass");
            if (extraClassesParam != null){
                String extraClassesString = (String) extraClassesParam.getValue();
                String[] extraClassesArray = extraClassesString.split(",");
                if (this.extraClasses == null){
                    this.extraClasses = new ArrayList<String>();
                }

                for (String extraClass : extraClassesArray){
                    this.extraClasses.add(extraClass);
                }
            }
        }

    }

    //This will locad the custom schema file and add that into the schema map
    private void loadCustomSchemaFile() {
        if (customSchemaLocation != null) {
            try {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                Document doc = documentBuilderFactory.newDocumentBuilder().parse(new File(customSchemaLocation));
                XmlSchema schema = xmlSchemaCollection.read(doc, null);
                schemaMap.put(schema.getTargetNamespace(), schema);
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
    }

    /**
     * This will load the mapping file and update the Typetable with the Class name and the Qname
     * Mapping file look like
     * org.foo.bar.FooException|http://www.abc.com/soaframework/common/types|ErrorMessage
     */
    private void loadMappingFile() {
        if (mappingFileLocation != null) {
            File file = new File(mappingFileLocation);
            BufferedReader input = null;
            try {
                input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String line;
                while ((line = input.readLine()) != null) {
                    line = line.trim();
                    if (line.length() > 0 && line.charAt(0) != '#') {
                        String values[] = line.split("\\|");
                        if (values != null && values.length > 2) {
                            typeTable.addComplexSchema(values[0], new QName(values[1], values[2]));
                        }
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * Generates schema for all the parameters in method. First generates schema for all different
     * parameter type and later refers to them.
     *
     * @return Returns XmlSchema.
     * @throws Exception
     */
    public Collection<XmlSchema> generateSchema() throws Exception {
        loadCustomSchemaFile();
        loadMappingFile();
        //all most all the time the ittr will have only one class in it
        /**
         * Schema genertaion done in two stage 1. Load all the methods and
         * create type for methods parameters (if the parameters are Bean
         * then it will create Complex types foer those , and if the
         * parameters are simple type which decribe in SimpleTypeTable
         * nothing will happen) 2. In the next stage for all the methods
         * messages and port types will be creteated
         */
        WebServiceAnnotation webservice =
                JSR181Helper.INSTANCE.getWebServiceAnnotation(serviceClass);
        if (webservice != null) {
            String tns = webservice.getTargetNamespace();
            if (tns != null && !"".equals(tns)) {
                targetNamespace = tns;
                schemaTargetNameSpace = tns;
            }
            service.setName(Utils.getAnnotatedServiceName(serviceClass, webservice));
        }
        classModel= JAXRSUtils.getClassModel(serviceClass);
        methods = processMethods(serviceClass.getDeclaredMethods());

        for (String extraClassName : getExtraClasses()) {
            Class<?> extraClass = Class.forName(extraClassName, true, classLoader);
            if (typeTable.getSimpleSchemaTypeName(extraClassName) == null) {
                generateSchema(extraClass);
            }
        }

        return schemaMap.values();
    }

    protected Method[] processMethods(Method[] declaredMethods) throws Exception {
        ArrayList<Method> list = new ArrayList<Method>();
        //short the elements in the array
        Arrays.sort(declaredMethods, new MathodComparator());

        // since we do not support overload
        HashMap<String,Method> uniqueMethods = new LinkedHashMap<String,Method>();
        XmlSchemaComplexType methodSchemaType;
        XmlSchemaSequence sequence = null;

        for (Method jMethod : declaredMethods) {
            if (jMethod.isBridge()) {
                continue;
            }

            WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod);
            String methodName = jMethod.getName();
            if (methodAnnon != null) {
                if (methodAnnon.isExclude()) {
                    continue;
                }
                if (methodAnnon.getOperationName() != null){
                    methodName = methodAnnon.getOperationName();
                }
            }

            // no need to think abt this method , since that is system
            // config method
            if (excludeMethods.contains(methodName)) {
                continue;
            }

            if (!Modifier.isPublic(jMethod.getModifiers())) {
                // no need to generate Schema for non public methods
                continue;
            }

            if (uniqueMethods.get(methodName) != null) {
                log.warn("We don't support method overloading. Ignoring [" +
                        methodName + "]");
                continue;
            }
            boolean addToService = false;
            AxisOperation axisOperation = service.getOperation(new QName(methodName));
            if (axisOperation == null) {
                if (service.getAxisConfiguration() != null &&
                        service.getAxisConfiguration()
                                .getParameter(Constants.Configuration.GET_HTTP_SC_OK_FOR_VOID_SERVICE_METHODS) != null
                        && service.getAxisConfiguration()
                        .getParameter(Constants.Configuration.GET_HTTP_SC_OK_FOR_VOID_SERVICE_METHODS).getValue()
                        .equals(Constants.VALUE_TRUE)) {
                    axisOperation = Utils.getAxisOperationForJmethod(jMethod, true);
                } else {
                    axisOperation = Utils.getAxisOperationForJmethod(jMethod, false);
                }
//                if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(
//                        axisOperation.getMessageExchangePattern())) {
//                    AxisMessage outMessage = axisOperation.getMessage(
//                            WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
//                    if (outMessage != null) {
//                        outMessage.setName(methodName + RESPONSE);
//                    }
//                }
                addToService = true;
            }
// by now axis operation should be assigned but we better recheck & add the paramether
            if(axisOperation != null){
             axisOperation.addParameter("JAXRSAnnotaion", JAXRSUtils.getMethodModel(this.classModel,jMethod));
            }
            // Maintain a list of methods we actually work with
            list.add(jMethod);

            processException(jMethod, axisOperation);
            uniqueMethods.put(methodName, jMethod);
            Class<?>[] parameters = jMethod.getParameterTypes();
            String parameterNames[] = null;
            AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessage != null) {
                inMessage.setName(methodName + Java2WSDLConstants.MESSAGE_SUFFIX);
            }
            if (parameters.length > 0) {
                parameterNames = methodTable.getParameterNames(methodName);
                // put the parameter names to use it for parsing
                service.addParameter(methodName, parameterNames);
            }

            // we need to add the method opration wrapper part even to
            // empty parameter operations
            sequence = new XmlSchemaSequence();

            String requestElementSuffix = getRequestElementSuffix();
            String requestLocalPart = methodName;
            if (requestElementSuffix != null) {
                requestLocalPart += requestElementSuffix;
            }

            methodSchemaType = createSchemaTypeForMethodPart(requestLocalPart);
            methodSchemaType.setParticle(sequence);
            inMessage.setElementQName(typeTable.getQNamefortheType(requestLocalPart));

            Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
            if (param != null) {
                inMessage.setPartName((String) param.getValue());
            }

            service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(),
                    axisOperation);

            Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations();

            Type[] genericParameterTypes = jMethod.getGenericParameterTypes();
            for (int j = 0; j < parameters.length; j++) {
                Class<?> methodParameter = parameters[j];
                String parameterName = getParameterName(parameterAnnotation, j, parameterNames);
                if (nonRpcMethods.contains(jMethod.getName())) {
                    generateSchemaForType(sequence, null, jMethod.getName());
                    break;
                } else {
                    Type genericParameterType = genericParameterTypes[j];
                    Type genericType = null;
                    if(genericParameterType instanceof ParameterizedType){
                        ParameterizedType aType = (ParameterizedType) genericParameterType;
                        Type[] parameterArgTypes = aType.getActualTypeArguments();
                        genericType = parameterArgTypes[0];
                        generateSchemaForType(sequence, genericType, parameterName, true);
                    }else{
                        generateSchemaForType(sequence, methodParameter, parameterName);
                    }
                }
            }
            // for its return type
            Class<?> returnType = jMethod.getReturnType();
            if (!"void".equals(jMethod.getReturnType().getName())) {
                String partQname = methodName + RESPONSE;
                methodSchemaType =
                        createSchemaTypeForMethodPart(partQname);
                sequence = new XmlSchemaSequence();
                methodSchemaType.setParticle(sequence);
                WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod);
                String returnName = "return";
                if (returnAnnon != null) {
                    returnName = returnAnnon.getName();
                    if (returnName == null || "".equals(returnName)) {
                        returnName = "return";
                    }
                }
                Type genericParameterType = jMethod.getGenericReturnType();
                if (nonRpcMethods.contains(jMethod.getName())) {
                    generateSchemaForType(sequence, null, returnName);
                } else if(genericParameterType instanceof ParameterizedType){
                        ParameterizedType aType = (ParameterizedType) genericParameterType;
                        Type[] parameterArgTypes = aType.getActualTypeArguments();
                        generateSchemaForType(sequence, parameterArgTypes[0], returnName, true);
                    } else {
                    generateSchemaForType(sequence, returnType, returnName);
                }

                AxisMessage outMessage = axisOperation.getMessage(
                        WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                outMessage.setElementQName(typeTable.getQNamefortheType(partQname));
                outMessage.setName(partQname);

                Parameter outparam = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
                if (outparam != null) {
                    outMessage.setPartName((String) outparam.getValue());
                }

                service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(),
                        axisOperation);
            }
            if (addToService) {
                service.addOperation(axisOperation);
            }
        }
        return list.toArray(new Method[list.size()]);
    }

    /**
     * This method will generate Schema element for all the excetion types in a given JMethod
     * - No matter what it will generate Schema element for java.lang.Exception so that for other
     * exception which extend java.lang.Excetion can use as the base class type
     */
    protected void processException(Method jMethod,
                                    AxisOperation axisOperation) throws Exception {
        XmlSchemaComplexType methodSchemaType;
        XmlSchemaSequence sequence;
        if (jMethod.getExceptionTypes().length > 0) {
            for (Class<?> extype : jMethod.getExceptionTypes()) {
                if (AxisFault.class.getName().equals(extype.getName())) {
                    continue;
                }
                String partQname = this.service.getName() + getSimpleClassName(extype);
                methodSchemaType = createSchemaTypeForFault(partQname);
                QName elementName =
                        new QName(this.schemaTargetNameSpace, partQname, this.schema_namespace_prefix);
                sequence = new XmlSchemaSequence();
                if (Exception.class.getName().equals(extype.getName())) {
                    if (typeTable.getComplexSchemaType(Exception.class.getName()) == null) {
                        generateComplexTypeforException();
                    }
                    QName schemaTypeName = typeTable.getComplexSchemaType(Exception.class.getName());
                    addContentToMethodSchemaType(sequence,
                            schemaTypeName,
                            partQname,
                            false);
                    methodSchemaType.setParticle(sequence);
                    typeTable.addComplexSchema(Exception.class.getPackage().getName(),
                            methodSchemaType.getQName());
                    resolveSchemaNamespace(Exception.class.getPackage().getName());
                    addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
                } else {
                    generateSchemaForType(sequence, extype, getSimpleClassName(extype));
                    methodSchemaType.setParticle(sequence);
                }

                typeTable.addComplexSchema(partQname, elementName);

                if (AxisFault.class.getName().equals(extype.getName())) {
                    continue;
                }
                AxisMessage faultMessage = new AxisMessage();
                faultMessage.setName(this.service.getName() + getSimpleClassName(extype));
                faultMessage.setElementQName(typeTable.getQNamefortheType(partQname));

                Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
                if (param != null) {
                    faultMessage.setPartName((String) param.getValue());
                }

                axisOperation.setFaultMessages(faultMessage);
            }
        }
    }

    private void generateComplexTypeforException() {
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);
        QName elementName = new QName(schemaTargetNameSpace, "Exception", schema_namespace_prefix);
        XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
        complexType.setName("Exception");
        xmlSchema.getItems().add(complexType);
        xmlSchema.getElements().add(elementName, complexType);
        typeTable.addComplexSchema(Exception.class.getName(), elementName);
        QName schemaTypeName = new QName(Java2WSDLConstants.URI_2001_SCHEMA_XSD, "string");
        addContentToMethodSchemaType(sequence, schemaTypeName, "Message", false);
        complexType.setParticle(sequence);
    }

    /**
     * Generate schema construct for given type
     *
     * @param javaType : Class to whcih need to generate Schema
     * @return : Generated QName
     */
    protected QName generateSchema(Class<?> javaType) throws Exception {
        String name = getClassName(javaType);
        QName schemaTypeName = typeTable.getComplexSchemaType(name);
        if (schemaTypeName == null) {
            String simpleName = getSimpleClassName(javaType);

            String packageName = getQualifiedName(javaType.getPackage());
            String targetNameSpace = resolveSchemaNamespace(packageName);

            XmlSchema xmlSchema = getXmlSchema(targetNameSpace);
            String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace);
            if (targetNamespacePrefix == null) {
                targetNamespacePrefix = generatePrefix();
                targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix);
            }

            XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
            XmlSchemaSequence sequence = new XmlSchemaSequence();
            XmlSchemaComplexContentExtension complexExtension =
                    new XmlSchemaComplexContentExtension();

            XmlSchemaElement eltOuter = new XmlSchemaElement();
            schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix);
            eltOuter.setName(simpleName);
            eltOuter.setQName(schemaTypeName);

            Class<?> sup = javaType.getSuperclass();
            if ((sup != null)
                    && (!"java.lang.Object".equals(sup.getName()))
                    && (!"java.lang.Exception".equals(sup.getName()))
                    && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2")
                    && !getQualifiedName(sup.getPackage()).startsWith("java.util")){
                String superClassName = sup.getName();
                String superclassname = getSimpleClassName(sup);
                String tgtNamespace;
                String tgtNamespacepfx;
                QName qName = typeTable.getSimpleSchemaTypeName(superClassName);
                if (qName != null) {
                    tgtNamespace = qName.getNamespaceURI();
                    tgtNamespacepfx = qName.getPrefix();
                } else {
                    tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage()));
                    tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace);
                    QName superClassQname = generateSchema(sup);
                    if (superClassQname != null) {
                        tgtNamespacepfx = superClassQname.getPrefix();
                        tgtNamespace = superClassQname.getNamespaceURI();
                    }
                }
                if (tgtNamespacepfx == null) {
                    tgtNamespacepfx = generatePrefix();
                    targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx);
                }
                //if the parent class package name is differ from the child
                if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().
                        contains(tgtNamespace)) {
                    XmlSchemaImport importElement = new XmlSchemaImport();
                    importElement.setNamespace(tgtNamespace);
                    xmlSchema.getItems().add(importElement);
                    ((NamespaceMap) xmlSchema.getNamespaceContext()).
                            put(generatePrefix(), tgtNamespace);
                }

                QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx);
                complexExtension.setBaseTypeName(basetype);
                complexExtension.setParticle(sequence);
                XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent();
                contentModel.setContent(complexExtension);
                complexType.setContentModel(contentModel);

            } else {
                complexType.setParticle(sequence);
            }

            complexType.setName(simpleName);

            if (Modifier.isAbstract(javaType.getModifiers())) {
                complexType.setAbstract(true);
            }

//            xmlSchema.getItems().add(eltOuter);
            xmlSchema.getElements().add(schemaTypeName, eltOuter);
            eltOuter.setSchemaTypeName(complexType.getQName());

            xmlSchema.getItems().add(complexType);
            xmlSchema.getSchemaTypes().add(schemaTypeName, complexType);

            // adding this type to the table
            typeTable.addComplexSchema(name, eltOuter.getQName());
            // adding this type's package to the table, to support inheritance.
            typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName());

            typeTable.addClassNameForQName(eltOuter.getQName(), name);

            BeanExcludeInfo beanExcludeInfo = null;
            if (service.getExcludeInfo() != null) {
                beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType));
            }

            // we need to get properties only for this bean. hence ignore the super
            // class properties
            BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass());

            for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                String propertyName = property.getName();
                if (!property.getName().equals("class") && (property.getPropertyType() != null)) {
                    if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) {
                        Type genericFieldType = null;
                        try {
                            Field field = javaType.getDeclaredField(propertyName);
                            genericFieldType = field.getGenericType();
                        } catch (Exception e) {
                            //log.info(e.getMessage());
                        }

                        if(genericFieldType instanceof ParameterizedType){
                            ParameterizedType aType = (ParameterizedType) genericFieldType;
                            Type[] fieldArgTypes = aType.getActualTypeArguments();
                            try {
                                generateSchemaforGenericFields(xmlSchema,
                                    sequence,
                                    fieldArgTypes[0],
                                    propertyName);
                            } catch (Exception e) {
                                generateSchemaforFieldsandProperties(xmlSchema,
                                    sequence,
                                    property.getPropertyType(),
                                    propertyName,
                                    property.getPropertyType().isArray());
                            }
                        } else {
                            generateSchemaforFieldsandProperties(xmlSchema,
                                    sequence,
                                    property.getPropertyType(),
                                    propertyName,
                                    property.getPropertyType().isArray());
                        }
                    }
                }
            }
        }
        return schemaTypeName;
    }

    // moved code common to Fields & properties out of above method
    protected void generateSchemaforFieldsandProperties(XmlSchema xmlSchema,
                                                        XmlSchemaSequence sequence, Class<?> type,
                                                        String name, boolean isArrayType)
            throws Exception {
        String propertyName;
        if (isArrayType) {
            propertyName = getClassName(type.getComponentType());
            if (type.getComponentType().isArray()) {
                // this is a double array element
                Class<?> simpleType = type.getComponentType();
                String simpleTypeName = "";
                while (simpleType.isArray()) {
                    simpleTypeName += "ArrayOf";
                    simpleType = simpleType.getComponentType();
                }
                simpleTypeName += getSimpleClassName(simpleType);

                if (xmlSchema.getTypeByName(simpleTypeName) == null) {
                    XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                    XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                    xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                    generateSchemaforFieldsandProperties(xmlSchema,
                            xmlSchemaSequence, type.getComponentType(), "array", true);

                    xmlSchemaComplexType.setName(simpleTypeName);
                    xmlSchema.getItems().add(xmlSchemaComplexType);
                    xmlSchema.getSchemaTypes().add(
                            new QName(xmlSchema.getTargetNamespace(), simpleTypeName), xmlSchemaComplexType);
                }

                if (isGenerateWrappedArrayTypes) {
                    XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
                    xmlSchemaElement.setName( name + "Wrapper");
                    xmlSchemaElement.setNillable(true);
                    sequence.getItems().add(xmlSchemaElement);

                    String complexTypeName = simpleTypeName + "Wrapper";

                    XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                    XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                    xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                    xmlSchemaComplexType.setName(complexTypeName);

                    xmlSchema.getItems().add(xmlSchemaComplexType);
                    xmlSchema.getSchemaTypes().add(
                            new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                            xmlSchemaComplexType);
                    addContentToMethodSchemaType(xmlSchemaSequence,
                            new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                            "array",
                            true);

                    xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
                    xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace,
                            xmlSchemaComplexType.getName()));

                } else {
                    addContentToMethodSchemaType(sequence,
                            new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                            name,
                            true);

                }
                return;
            }
        } else {
            propertyName = getClassName(type);
        }
        if (isArrayType && "byte".equals(propertyName)) {
            propertyName = "base64Binary";
        }
        if (isDataHandler(type)) {
            propertyName = "base64Binary";
        }
        if (typeTable.isSimpleType(propertyName)) {

            if (isGenerateWrappedArrayTypes && isArrayType) {

                processGenerateWrappedArrayTypes(xmlSchema, sequence, type, name, isArrayType, propertyName);

            } else {
                addElementToSequence(name,
                        typeTable.getSimpleSchemaTypeName(propertyName),
                        sequence,
                        propertyName.equals("base64Binary"),
                        isArrayType,
                        type.isPrimitive());
            }

        } else {
            if (isArrayType) {
                generateSchema(type.getComponentType());
            } else {
                generateSchema(type);
            }

            if (isGenerateWrappedArrayTypes && isArrayType) {

                processGenerateWrappedArrayTypes(xmlSchema, sequence, type, name, isArrayType, propertyName);

            } else {
                addElementToSequence(name,
                        typeTable.getComplexSchemaType(propertyName),
                        sequence,
                        false,
                        isArrayType,
                        type.isPrimitive());
            }

            if (typeTable.getComplexSchemaType(propertyName) != null && !((NamespaceMap) xmlSchema.getNamespaceContext()).values().
                    contains(typeTable.getComplexSchemaType(propertyName).getNamespaceURI())) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(
                        typeTable.getComplexSchemaType(propertyName).getNamespaceURI());
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).
                        put(generatePrefix(),
                                typeTable.getComplexSchemaType(propertyName).getNamespaceURI());
            }
        }

    }

    protected void generateSchemaforGenericFields(XmlSchema xmlSchema,
                                                  XmlSchemaSequence sequence, Type genericType,
                                                  String name)
            throws Exception {
        String propertyName;
        Class<?> type;
        boolean isArrayType = true;
        // This fix is for java7 onwards, refer CARBON-15182
        if ((genericType instanceof Class<?>) && (((Class<?>) genericType).isArray())) {
            Class<?> simpleType = ((Class<?>) genericType).getComponentType();
            propertyName = simpleType.getName();
            // this is a doble array element
            String simpleTypeName = "";
            while (simpleType.isArray()) {
                simpleTypeName += "ArrayOf";
                simpleType = simpleType.getComponentType();
            }
            simpleTypeName += simpleType.getSimpleName();

            if (xmlSchema.getTypeByName(simpleTypeName) == null) {
                XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                generateSchemaforGenericFields(xmlSchema,
                        xmlSchemaSequence, simpleType, "array");

                xmlSchemaComplexType.setName(simpleTypeName);
                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName), xmlSchemaComplexType);
            }

            if (isGenerateWrappedArrayTypes) {
                XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
                xmlSchemaElement.setName( name + "Wrapper");
                xmlSchemaElement.setNillable(true);
                sequence.getItems().add(xmlSchemaElement);

                String complexTypeName = simpleTypeName + "Wrapper";

                XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                xmlSchemaComplexType.setName(complexTypeName);

                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(
                        new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                        xmlSchemaComplexType);
                addContentToMethodSchemaType(xmlSchemaSequence,
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                        "array",
                        true);

                xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
                xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace,
                        xmlSchemaComplexType.getName()));

            } else {
                addContentToMethodSchemaType(sequence,
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                        name,
                        true);

            }
            return;
        } else {
//            isArrayType = false;
            type = (Class<?>) genericType;
            propertyName = type.getName();
        }

        if (isArrayType && "byte".equals(propertyName)) {
            propertyName = "base64Binary";
        }
        if (isDataHandler(type)) {
            propertyName = "base64Binary";
        }
        if (typeTable.isSimpleType(propertyName)) {

            if (isGenerateWrappedArrayTypes && isArrayType) {

                processGenerateWrappedArrayTypes(xmlSchema, sequence, type, name, isArrayType, propertyName);

            } else {
                addElementToSequence(name,
                        typeTable.getSimpleSchemaTypeName(propertyName),
                        sequence,
                        propertyName.equals("base64Binary"),
                        isArrayType,
                        type.isPrimitive());
            }

        } else {
            if (isArrayType) {
                generateSchema(type.getComponentType());
            } else {
                generateSchema(type);
            }

            if (isGenerateWrappedArrayTypes && isArrayType) {

                processGenerateWrappedArrayTypes(xmlSchema, sequence, type, name, isArrayType, propertyName);

            } else {
                addElementToSequence(name,
                        typeTable.getComplexSchemaType(propertyName),
                        sequence,
                        false,
                        isArrayType,
                        type.isPrimitive());
            }

            if (typeTable.getComplexSchemaType(propertyName) != null && !((NamespaceMap) xmlSchema.getNamespaceContext()).values().
                    contains(typeTable.getComplexSchemaType(propertyName).getNamespaceURI())) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(
                        typeTable.getComplexSchemaType(propertyName).getNamespaceURI());
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).
                        put(generatePrefix(),
                                typeTable.getComplexSchemaType(propertyName).getNamespaceURI());
            }
        }

    }

    private void processGenerateWrappedArrayTypes(XmlSchema xmlSchema,
                                                  XmlSchemaSequence sequence,
                                                  Class<?> type,
                                                  String name,
                                                  boolean isArrayType,
                                                  String propertyName) {
        XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
        xmlSchemaElement.setName( name + "Wrapper");
        xmlSchemaElement.setNillable(true);
        sequence.getItems().add(xmlSchemaElement);

        String complexTypeName =
                typeTable.getSimpleSchemaTypeName(propertyName).getLocalPart() + "Wrapper";

        XmlSchemaComplexType xmlSchemaComplexType ;
        if (xmlSchema.getTypeByName(complexTypeName) == null) {
            xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
            XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
            xmlSchemaComplexType.setParticle(xmlSchemaSequence);
            xmlSchemaComplexType.setName(complexTypeName);

            xmlSchema.getItems().add(xmlSchemaComplexType);
            xmlSchema.getSchemaTypes().add(
                    new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                    xmlSchemaComplexType);
            addElementToSequence("array",
                typeTable.getSimpleSchemaTypeName(propertyName),
                xmlSchemaSequence,
                propertyName.equals("base64Binary"),
                isArrayType,
                type.isPrimitive());
        } else {
           xmlSchemaComplexType = (XmlSchemaComplexType) xmlSchema.getTypeByName(complexTypeName);
        }

        xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
        xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));
    }

    private void addElementToSequence(String name,
                                      QName propertyQName,
                                      XmlSchemaSequence sequence,
                                      boolean isBase64Binary,
                                      boolean isArryType,
                                      boolean isPrimitive) {
        XmlSchemaElement elt1 = new XmlSchemaElement();
        elt1.setName(name);
        elt1.setSchemaTypeName(propertyQName);
        sequence.getItems().add(elt1);
        if (isArryType && !isBase64Binary) {
            elt1.setMaxOccurs(Long.MAX_VALUE);
        }
        elt1.setMinOccurs(0);

        boolean disallowNillables = false;
        Parameter param = service.getParameter(Java2WSDLConstants.DISALLOW_NILLABLE_ELEMENTS_OPTION_LONG);
        if (param != null) {
            disallowNillables = JavaUtils.isTrueExplicitly(param.getValue());
        }

        if (!isPrimitive && !disallowNillables) {
            elt1.setNillable(true);
        }
    }

    private QName generateSchemaForType(XmlSchemaSequence sequence, Class<?> type, String partName)
            throws Exception {

        boolean isArrayType = false;
        if (type != null) {
            isArrayType = type.isArray();
        }
        if (isArrayType) {
            if (type.getComponentType().isArray()) {
                // this is a double array element
                Class<?> simpleType = type.getComponentType();
                String simpleTypeName = "";
                while (simpleType.isArray()) {
                    simpleTypeName += "ArrayOf";
                    simpleType = simpleType.getComponentType();
                }
                simpleTypeName += getSimpleClassName(simpleType);

                return processParameterArrayTypes(sequence, type, partName, simpleTypeName);

            } else {
                type = type.getComponentType();
            }
        }
        if (AxisFault.class.getName().equals(type)) {
            return null;
        }
        String classTypeName;
        if (type == null) {
            classTypeName = "java.lang.Object";
        } else {
            classTypeName = type.getName();
        }
        if (isArrayType && "byte".equals(classTypeName)) {
            classTypeName = "base64Binary";
            isArrayType = false;
        }

        if (isDataHandler(type)) {
            classTypeName = "base64Binary";
        }

        return generateSchemaTypeforNameCommon(sequence, partName, isArrayType, type, classTypeName);
    }

    private QName generateSchemaForType(XmlSchemaSequence sequence, Type genericType, String partName, boolean isArrayType)
            throws Exception {

        Class<?> type;
        // This fix is for java7 onwards, refer CARBON-15182
        if ((genericType instanceof Class<?>) && (((Class<?>) genericType).isArray())) {
            // this is a double array element
            Class<?> simpleType = ((Class<?>) genericType).getComponentType();
            String simpleTypeName = "";
            while (simpleType.isArray()) {
                simpleTypeName += "ArrayOf";
                simpleType = simpleType.getComponentType();
            }
            simpleTypeName += simpleType.getSimpleName();

            XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);
            if (xmlSchema.getTypeByName(simpleTypeName) == null) {
                XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                generateSchemaForType(xmlSchemaSequence, simpleType, "array",true);
                xmlSchemaComplexType.setName(simpleTypeName);
                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName), xmlSchemaComplexType);
            }

            if (isGenerateWrappedArrayTypes) {
                XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
                xmlSchemaElement.setName(partName + "Wrapper");
                xmlSchemaElement.setNillable(true);
                sequence.getItems().add(xmlSchemaElement);

                String complexTypeName = simpleTypeName + "Wrapper";

                XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                xmlSchemaComplexType.setName(complexTypeName);

                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(
                        new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                        xmlSchemaComplexType);
                addContentToMethodSchemaType(xmlSchemaSequence,
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                        "array",
                        true);

                xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
                xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));
                return new QName(xmlSchema.getTargetNamespace(), complexTypeName);
            } else {
                addContentToMethodSchemaType(sequence,
                        new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                        partName,
                        true);
                return new QName(xmlSchema.getTargetNamespace(), simpleTypeName);
            }

        } else{
            type = (Class<?>) genericType;
        }
        if (AxisFault.class.getName().equals(type)) {
            return null;
        }
        String classTypeName;
        if (type == null) {
            classTypeName = "java.lang.Object";
        } else {
            classTypeName = type.getName();
        }
        if (isArrayType && "byte".equals(classTypeName)) {
            classTypeName = "base64Binary";
            isArrayType = false;
        }

        if (isDataHandler(type)) {
            classTypeName = "base64Binary";
        }

        return generateSchemaTypeforNameCommon(sequence, partName, isArrayType, type, classTypeName);
    }

    private QName generateSchemaTypeforNameCommon(XmlSchemaSequence sequence,
                                                  String partName,
                                                  boolean isArrayType,
                                                  Class<?> type,
                                                  String classTypeName) throws Exception {
        QName schemaTypeName = typeTable.getSimpleSchemaTypeName(classTypeName);
        if (schemaTypeName == null) {
            schemaTypeName = generateSchema(type);
            if (isGenerateWrappedArrayTypes && isArrayType) {

                XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
                xmlSchemaElement.setName(partName + "Wrapper");
                xmlSchemaElement.setNillable(true);
                sequence.getItems().add(xmlSchemaElement);

                String complexTypeName = schemaTypeName.getLocalPart() + "Wrapper";
                XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);

                XmlSchemaComplexType xmlSchemaComplexType = null;
                if (xmlSchema.getTypeByName(complexTypeName) == null) {
                    xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                    XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                    xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                    xmlSchemaComplexType.setName(complexTypeName);

                    xmlSchema.getItems().add(xmlSchemaComplexType);
                    xmlSchema.getSchemaTypes().add(
                            new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                            xmlSchemaComplexType);
                    addContentToMethodSchemaType(xmlSchemaSequence,
                        schemaTypeName,
                        "array",
                        isArrayType);
                } else {
                   xmlSchemaComplexType = (XmlSchemaComplexType) xmlSchema.getTypeByName(complexTypeName);
                }

                xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
                xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));

            } else {
                addContentToMethodSchemaType(sequence,
                    schemaTypeName,
                    partName,
                    isArrayType);
            }

            String schemaNamespace;
            schemaNamespace = resolveSchemaNamespace(getQualifiedName(type.getPackage()));
            addImport(getXmlSchema(schemaNamespace), schemaTypeName);

        } else {
            if (isGenerateWrappedArrayTypes && isArrayType) {

                XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
                xmlSchemaElement.setName(partName +"Wrapper");
                xmlSchemaElement.setNillable(true);
                sequence.getItems().add(xmlSchemaElement);

                String complexTypeName = schemaTypeName.getLocalPart() + "Wrapper";
                XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);

                XmlSchemaComplexType xmlSchemaComplexType = null;
                if (xmlSchema.getTypeByName(complexTypeName) == null) {
                    xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                    XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                    xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                    xmlSchemaComplexType.setName(complexTypeName);

                    xmlSchema.getItems().add(xmlSchemaComplexType);
                    xmlSchema.getSchemaTypes().add(
                            new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                            xmlSchemaComplexType);
                    addContentToMethodSchemaType(xmlSchemaSequence,
                        schemaTypeName,
                        "array",
                        isArrayType);
                } else {
                   xmlSchemaComplexType = (XmlSchemaComplexType) xmlSchema.getTypeByName(complexTypeName);
                }

                xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
                xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));

            } else {
                addContentToMethodSchemaType(sequence,
                        schemaTypeName,
                        partName,
                        isArrayType);
            }

        }
        addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
        return schemaTypeName;
    }

    private QName processParameterArrayTypes(XmlSchemaSequence sequence, Class<?> type, String partName, String simpleTypeName) throws Exception {
        XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);
        if (xmlSchema.getTypeByName(simpleTypeName) == null) {
            XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
            XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
            xmlSchemaComplexType.setParticle(xmlSchemaSequence);
            generateSchemaForType(xmlSchemaSequence, type.getComponentType(), "array");
            xmlSchemaComplexType.setName(simpleTypeName);
            xmlSchema.getItems().add(xmlSchemaComplexType);
            xmlSchema.getSchemaTypes().add(
                    new QName(xmlSchema.getTargetNamespace(), simpleTypeName), xmlSchemaComplexType);
        }

        if (isGenerateWrappedArrayTypes) {
            XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
            xmlSchemaElement.setName(partName + "Wrapper");
            xmlSchemaElement.setNillable(true);
            sequence.getItems().add(xmlSchemaElement);

            String complexTypeName = simpleTypeName + "Wrapper";

            XmlSchemaComplexType xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
            XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
            xmlSchemaComplexType.setParticle(xmlSchemaSequence);
            xmlSchemaComplexType.setName(complexTypeName);

            xmlSchema.getItems().add(xmlSchemaComplexType);
            xmlSchema.getSchemaTypes().add(
                    new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                    xmlSchemaComplexType);
            addContentToMethodSchemaType(xmlSchemaSequence,
                    new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                    "array",
                    true);

            xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
            xmlSchemaElement.setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));
            return new QName(xmlSchema.getTargetNamespace(), complexTypeName);
        } else {
            addContentToMethodSchemaType(sequence,
                    new QName(xmlSchema.getTargetNamespace(), simpleTypeName),
                    partName,
                    true);
            return new QName(xmlSchema.getTargetNamespace(), simpleTypeName);
        }
    }

    protected boolean isDataHandler(Class<?> clazz) {
        return clazz != null && DataHandler.class.isAssignableFrom(clazz);
    }

    protected void addContentToMethodSchemaType(XmlSchemaSequence sequence,
                                                QName schemaTypeName,
                                                String paraName,
                                                boolean isArray) {
        XmlSchemaElement elt1 = new XmlSchemaElement();
        elt1.setName(paraName);

        elt1.setSchemaTypeName(schemaTypeName);
        if (sequence != null) {
            sequence.getItems().add(elt1);
        }

        if (isArray) {
            elt1.setMaxOccurs(Long.MAX_VALUE);
        }
        elt1.setMinOccurs(0);

        boolean disallowNillables = false;
        Parameter param = service.getParameter(Java2WSDLConstants.DISALLOW_NILLABLE_ELEMENTS_OPTION_LONG);
        if (param != null) {
            disallowNillables = JavaUtils.isTrueExplicitly(param.getValue());
        }

        if (!("int".equals(schemaTypeName.getLocalPart()) ||
                "double".equals(schemaTypeName.getLocalPart()) ||
                "long".equals(schemaTypeName.getLocalPart()) ||
                "boolean".equals(schemaTypeName.getLocalPart()) ||
                "short".equals(schemaTypeName.getLocalPart()) ||
                "float".equals(schemaTypeName.getLocalPart())) && !disallowNillables) {
            elt1.setNillable(true);
        }
    }

    private XmlSchemaComplexType createSchemaTypeForMethodPart(String localPartName) {
        XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);
        QName elementName =
                new QName(this.schemaTargetNameSpace, localPartName, this.schema_namespace_prefix);

        XmlSchemaComplexType complexType = getComplexTypeForElement(xmlSchema, elementName);
        if (complexType == null) {
            complexType = new XmlSchemaComplexType(xmlSchema);

            XmlSchemaElement globalElement = new XmlSchemaElement();
            globalElement.setName(localPartName);
            globalElement.setQName(elementName);

            boolean disallowAnonTypes = isAnonymousTypesDisallowed();
            if (disallowAnonTypes) {
                String complexTypeName = localPartName.substring(0, 1).toUpperCase()
                        + localPartName.substring(1);
                complexType.setName(complexTypeName);
                globalElement.setSchemaTypeName(complexType.getQName());
                xmlSchema.getItems().add(complexType);
                xmlSchema.getSchemaTypes().add(complexType.getQName(), complexType);
            } else {
                globalElement.setSchemaType(complexType);
            }

            xmlSchema.getItems().add(globalElement);
            xmlSchema.getElements().add(elementName, globalElement);
        }
        typeTable.addComplexSchema(localPartName, elementName);

        return complexType;
    }

    private XmlSchemaComplexType createSchemaTypeForFault(String localPartName) {
        XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);
        QName elementName =
                new QName(this.schemaTargetNameSpace, localPartName, this.schema_namespace_prefix);

        XmlSchemaComplexType complexType = getComplexTypeForElement(xmlSchema, elementName);
        if (complexType == null) {
            complexType = new XmlSchemaComplexType(xmlSchema);

            XmlSchemaElement globalElement = new XmlSchemaElement();
            globalElement.setName(localPartName);
            globalElement.setQName(elementName);

            boolean disallowAnonTypes = isAnonymousTypesDisallowed();
            if (disallowAnonTypes) {
                complexType.setName(localPartName);
                globalElement.setSchemaTypeName(complexType.getQName());
                xmlSchema.getItems().add(complexType);
                xmlSchema.getSchemaTypes().add(complexType.getQName(), complexType);
            } else {
                globalElement.setSchemaType(complexType);
            }

            xmlSchema.getItems().add(globalElement);
            xmlSchema.getElements().add(elementName, globalElement);

        }
        return complexType;
    }

     private boolean isAnonymousTypesDisallowed() {
        boolean disallowAnonTypes = false;
        Parameter param = service.getParameter(Java2WSDLConstants.DISALLOW_ANON_TYPES_OPTION_LONG);
        if (param != null) {
            disallowAnonTypes = JavaUtils.isTrueExplicitly(param.getValue());
        }
        return disallowAnonTypes;
    }

    private String getRequestElementSuffix() {
        String requestElementSuffix = null;
        Parameter param = service.getParameter(Java2WSDLConstants.REQUEST_ELEMENT_SUFFIX_OPTION_LONG);
        if (param != null) {
            requestElementSuffix = (String) param.getValue();
        }
        return requestElementSuffix;
    }

    protected XmlSchemaComplexType getComplexTypeForElement(XmlSchema xmlSchema, QName name) {

        Iterator<?> iterator = xmlSchema.getItems().getIterator();
        while (iterator.hasNext()) {
            XmlSchemaObject object = (XmlSchemaObject) iterator.next();
            if (object instanceof XmlSchemaElement && ((XmlSchemaElement) object).getQName().equals(name)) {
                XmlSchemaComplexType xmlSchemaComplexType = (XmlSchemaComplexType) ((XmlSchemaElement) object).getSchemaType();
                if ((xmlSchemaComplexType == null) && (((XmlSchemaElement) object).getSchemaTypeName() != null)){
                    xmlSchemaComplexType =
                            (XmlSchemaComplexType) xmlSchema.getTypeByName(((XmlSchemaElement) object).getSchemaTypeName());
                }
                return xmlSchemaComplexType;
            }
        }
        return null;
    }

    protected XmlSchema getXmlSchema(String targetNamespace) {
        XmlSchema xmlSchema;

        if ((xmlSchema = schemaMap.get(targetNamespace)) == null) {
            String targetNamespacePrefix;

            if (targetNamespace.equals(schemaTargetNameSpace) &&
                    schema_namespace_prefix != null) {
                targetNamespacePrefix = schema_namespace_prefix;
            } else {
                targetNamespacePrefix = generatePrefix();
            }

            xmlSchema = new XmlSchema(targetNamespace, xmlSchemaCollection);
            xmlSchema.setAttributeFormDefault(getAttrFormDefaultSetting());
            xmlSchema.setElementFormDefault(getElementFormDefaultSetting());

            targetNamespacePrefixMap.put(targetNamespace, targetNamespacePrefix);
            schemaMap.put(targetNamespace, xmlSchema);

            NamespaceMap prefixmap = new NamespaceMap();
            prefixmap.put(DEFAULT_SCHEMA_NAMESPACE_PREFIX, URI_2001_SCHEMA_XSD);
            prefixmap.put(targetNamespacePrefix, targetNamespace);
            xmlSchema.setNamespaceContext(prefixmap);
        }
        return xmlSchema;
    }

    public TypeTable getTypeTable() {
        return typeTable;
    }

    public Method[] getMethods() {
        return methods;
    }

    protected String generatePrefix() {
        return NAME_SPACE_PREFIX + prefixCount++;
    }

    public void setExcludeMethods(ArrayList<String> excludeMethods) {
        if (excludeMethods == null) excludeMethods = new ArrayList<String>();
        this.excludeMethods = excludeMethods;
    }

    public String getSchemaTargetNameSpace() {
        return schemaTargetNameSpace;
    }

    protected void addImport(XmlSchema xmlSchema, QName schemaTypeName) {
        NamespacePrefixList map = xmlSchema.getNamespaceContext();
        if (map == null ||
                ((map instanceof NamespaceMap) && ((NamespaceMap) map).values() == null) ||
                schemaTypeName == null) {
            return;
        }
        if (map instanceof NamespaceMap && !((NamespaceMap) map).values().
                contains(schemaTypeName.getNamespaceURI())) {
            XmlSchemaImport importElement = new XmlSchemaImport();
            importElement.setNamespace(schemaTypeName.getNamespaceURI());
            xmlSchema.getItems().add(importElement);
            ((NamespaceMap) xmlSchema.getNamespaceContext()).
                    put(generatePrefix(), schemaTypeName.getNamespaceURI());
        }
    }

    public String getAttrFormDefault() {
        return attrFormDefault;
    }

    public void setAttrFormDefault(String attrFormDefault) {
        this.attrFormDefault = attrFormDefault;
    }

    public String getElementFormDefault() {
        return elementFormDefault;
    }

    public void setElementFormDefault(String elementFormDefault) {
        this.elementFormDefault = elementFormDefault;
    }

    protected XmlSchemaForm getAttrFormDefaultSetting() {
        if (FORM_DEFAULT_UNQUALIFIED.equals(getAttrFormDefault())) {
            return new XmlSchemaForm(XmlSchemaForm.UNQUALIFIED);
        } else {
            return new XmlSchemaForm(XmlSchemaForm.QUALIFIED);
        }
    }

    protected XmlSchemaForm getElementFormDefaultSetting() {
        if (FORM_DEFAULT_UNQUALIFIED.equals(getElementFormDefault())) {
            return new XmlSchemaForm(XmlSchemaForm.UNQUALIFIED);
        } else {
            return new XmlSchemaForm(XmlSchemaForm.QUALIFIED);
        }
    }

    public ArrayList<String> getExtraClasses() {
        if (extraClasses == null) {
            extraClasses = new ArrayList<String>();
        }
        return extraClasses;
    }

    public void setExtraClasses(ArrayList<String> extraClasses) {
        this.extraClasses = extraClasses;
    }

    protected String resolveSchemaNamespace(String packageName) throws Exception {
        //if all types must go into the wsdl types schema namespace
        if (useWSDLTypesNamespace) {
            //return schemaTargetNameSpace;
            return pkg2nsmap.get("all");
        } else {
            if (pkg2nsmap != null && !pkg2nsmap.isEmpty()) {
                //if types should go into namespaces that are mapped against the package name for the type
                if (pkg2nsmap.get(packageName) != null) {
                    //return that mapping
                    return pkg2nsmap.get(packageName);
                } else {
                    return getNsGen().schemaNamespaceFromPackageName(packageName).toString();
                }
            } else {
                // if  pkg2nsmap is null and if not default schema ns found for the custom bean
                return getNsGen().schemaNamespaceFromPackageName(packageName).toString();
            }
        }
    }

    public boolean isUseWSDLTypesNamespace() {
        return useWSDLTypesNamespace;
    }

    public void setUseWSDLTypesNamespace(boolean useWSDLTypesNamespace) {
        this.useWSDLTypesNamespace = useWSDLTypesNamespace;
    }

    public Map<String,String> getPkg2nsmap() {
        return pkg2nsmap;
    }

    public void setPkg2nsmap(Map<String,String> pkg2nsmap) {
        this.pkg2nsmap = pkg2nsmap;
    }

    public String getTargetNamespace() {
        return targetNamespace;
    }

    protected String getClassName(Class<?> type) {
        String name = type.getName();
        if (name.indexOf("$") > 0) {
            name = name.replace('$', '_');
        }
        return name;
    }

    protected String getSimpleClassName(Class type) {
        String simpleClassName = type.getName();
        int idx = simpleClassName.lastIndexOf('.');
        if (idx != -1 && idx < (simpleClassName.length() - 1)) {
            simpleClassName = simpleClassName.substring(idx + 1);
        }

        return simpleClassName.replace('$', '_');
    }

    protected String getQualifiedName(Package packagez) {
        if (packagez != null) {
            return packagez.getName();
        } else {
            return "";
        }
    }

    public void setNonRpcMethods(ArrayList<String> nonRpcMethods) {
        if (nonRpcMethods != null) {
            this.nonRpcMethods = nonRpcMethods;
        }
    }

    public void setAxisService(AxisService service) {
        this.service = service;
    }

    public String getCustomSchemaLocation() {
        return customSchemaLocation;
    }

    public void setCustomSchemaLocation(String customSchemaLocation) {
        this.customSchemaLocation = customSchemaLocation;
    }

    public String getMappingFileLocation() {
        return mappingFileLocation;
    }

    public void setMappingFileLocation(String mappingFileLocation) {
        this.mappingFileLocation = mappingFileLocation;
    }

    protected String getParameterName(Annotation[][] parameterAnnotation,
                                      int j,
                                      String[] parameterNames) {
        String parameterName = null;
        if (parameterAnnotation.length > 0) {
            WebParamAnnotation annotation =
                    JSR181Helper.INSTANCE.getWebParamAnnotation(parameterAnnotation[j]);
            if (annotation != null) {
                parameterName = annotation.getName();
            }
        }
        if (parameterName == null || "".equals(parameterName)) {
            if(parameterNames != null && parameterNames.length > j) {
                parameterName = parameterNames[j];
            }
            if (parameterName == null || "".equals(parameterName)) {
                parameterName = "args" + j;
            }
        }
        return parameterName;
    }

    public class MathodComparator implements Comparator<Method> {
        public int compare(Method method1, Method method2) {
            String[] values = new String[2];
            values[0] = method1.getName();
            values[1] = method2.getName();
            Arrays.sort(values);
            if (values[0].equals(method1.getName())) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public class PropertyComparator implements Comparator<PropertyDescriptor> {
        public int compare(PropertyDescriptor propertyDescriptor1,
                PropertyDescriptor propertyDescriptor2) {

            String[] values = new String[2];
            values[0] = propertyDescriptor1.getName();
            values[1] = propertyDescriptor2.getName();
            Arrays.sort(values);
            if (values[0].equals(propertyDescriptor1.getName())) {
                return 0;
            } else {
                return 1;
            }
        }
    }
}


text:
package com.cloudera.spark.cloud.common

import java.io.{File, FileNotFoundException}

import com.cloudera.spark.cloud.s3.S3AConstants
import com.cloudera.spark.cloud.CommitterBinding
import org.apache.hadoop.conf.Configuration
import org.scalatest.concurrent.Eventually
import org.scalatest.BeforeAndAfter

import org.apache.spark.{LocalSparkContext, SparkFunSuite}
import org.apache.spark.internal.Logging

/**
 * A cloud suite.
 * Adds automatic loading of a Hadoop configuration file with login credentials and
 * options to enable/disable tests, and a mechanism to conditionally declare tests
 * based on these details
 */
abstract class CloudSuite extends SparkFunSuite
    with LocalSparkContext with BeforeAndAfter
    with Eventually with S3AConstants with CloudSuiteTrait {
}

object CloudSuite extends Logging with S3AConstants
  with CloudSuiteTrait {

  private var configLogged = false

  /**
   * Load the configuration file from the system property `SYSPROP_CLOUD_TEST_CONFIGURATION_FILE`.
   * Throws FileNotFoundException if a configuration is named but not present.
   * @return the configuration
   */
  def loadConfiguration(): Configuration = {
    val config = new Configuration(true)
    getKnownSysprop(SYSPROP_CLOUD_TEST_CONFIGURATION_FILE).foreach { filename =>
      logDebug(s"Configuration property = `$filename`")
      val f = new File(filename)
      if (f.exists()) {
        // unsynced but its only a log statement
        if (configLogged) {
          configLogged = true
          logInfo(s"Loading configuration from $f")
        }
        config.addResource(f.toURI.toURL)
      } else {
        throw new FileNotFoundException(s"No file '$filename'" +
          s" declared in property $SYSPROP_CLOUD_TEST_CONFIGURATION_FILE")
      }
    }
    overlayConfiguration(
      config,
      Seq(
        HIVE_TESTS_DISABLED,
        REQUIRED_HADOOP_VERSION,
        SCALE_TEST_ENABLED,
        SCALE_TEST_SIZE_FACTOR,
        S3A_CLIENT_FACTORY_IMPL,
        S3A_COMMITTER_TEST_ENABLED,
        S3A_ENCRYPTION_KEY_1,
        S3A_ENCRYPTION_KEY_2
      )
    )

    // setup the committer from any property passed in
    getKnownSysprop(S3A_COMMITTER_NAME).foreach(committer => {
      val binding = CommitterBinding.COMMITTERS_BY_NAME(committer.toLowerCase())
      binding.bind(config)
      logInfo(s"Using committer binding $binding")
    })
    config
  }

}

redpajama_set_name: RedPajamaGithub


text:
import { Null, Primitive } from "@entity-space/utils";
import { InSetCriterionShape } from "./in-set-criterion-shape";

export function inSetShape<T extends Primitive | typeof Null, U extends T[]>(
    ...valueTypes: [...U]
): InSetCriterionShape<[...U][number]>;
export function inSetShape<T extends Primitive | typeof Null>(valueTypes: T[]): InSetCriterionShape<T>;
export function inSetShape<T extends Primitive | typeof Null>(...args: any): InSetCriterionShape<T> {
    if (Array.isArray(args[0])) {
        return new InSetCriterionShape(args[0]);
    } else {
        return new InSetCriterionShape(args);
    }
}


text:
import logging

from grazer.util import get_session

logger = logging.getLogger(__name__)

def fetch_page(link, cfg):
    reader = cfg.reader
    headers = cfg.headers
    proxies = cfg.proxies
    parser = cfg.parser
    session = get_session(cfg.cookies)

    return reader.read_page(session, link, parser, headers, proxies)

def scrape(data, mappings):
    logger.debug("Retrieved data: {0}".format(data))

    parsed_data = [result
                   for mapping in mappings
                   for result in mapping.parse(data)]
    return list(parsed_data)


text:
<?php

namespace Drupal\quickedit\Annotation;

use Drupal\Component\Annotation\Plugin;

/**
 * Defines an InPlaceEditor annotation object.
 *
 * Plugin Namespace: Plugin\InPlaceEditor
 *
 * For a working example, see \Drupal\quickedit\Plugin\InPlaceEditor\PlainTextEditor
 *
 * @see \Drupal\quickedit\Plugin\InPlaceEditorBase
 * @see \Drupal\quickedit\Plugin\InPlaceEditorInterface
 * @see \Drupal\quickedit\Plugin\InPlaceEditorManager
 * @see plugin_api
 *
 * @Annotation
 */
class InPlaceEditor extends Plugin {

  /**
   * The plugin ID.
   *
   * @var string
   */
  public $id;

  /**
   * The name of the module providing the in-place editor plugin.
   *
   * @var string
   */
  public $module;

}


text:
module MtimeRequestStub
  def stub_mtime(path)
    stub_request(:post, "https://example-nsu.akamai.net#{path}")
  end
end


text:
"""Command Line Interface"""
import sys
import os
import argparse
import logging
import pathlib
from urllib.error import URLError

import xmlschema
from xmlschema import XMLSchema, XMLSchema11, iter_errors, to_json, from_json, etree_tostring
from xmlschema.exceptions import XMLSchemaValueError

PROGRAM_NAME = os.path.basename(sys.argv[0])

CONVERTERS_MAP = {
    'unordered': xmlschema.UnorderedConverter,
    'parker': xmlschema.ParkerConverter,
    'badgerfish': xmlschema.BadgerFishConverter,
    'abdera': xmlschema.AbderaConverter,
    'jsonml': xmlschema.JsonMLConverter,
    'columnar': xmlschema.ColumnarConverter,
}

def xsd_version_number(value):
    if value not in ('1.0', '1.1'):
        raise argparse.ArgumentTypeError("%r is not a valid XSD version" % value)
    return value

def defuse_data(value):
    if value not in ('always', 'remote', 'never'):
        raise argparse.ArgumentTypeError("%r is not a valid value" % value)
    return value

def get_loglevel(verbosity):
    if verbosity <= 0:
        return logging.ERROR
    elif verbosity == 1:
        return logging.WARNING
    elif verbosity == 2:
        return logging.INFO
    else:
        return logging.DEBUG

def get_converter(name):
    if not isinstance(name, str):
        return None

    try:
        return CONVERTERS_MAP[name.lower()]
    except KeyError:
        raise ValueError("--converter must be in {!r}".format(tuple(CONVERTERS_MAP)))

def xml2json():
    parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True,
                                     description="decode a set of XML files to JSON.")
    parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \
                   "Try '%(prog)s --help' for more information."

    parser.add_argument('-v', dest='verbosity', action='count', default=0,
                        help="increase output verbosity.")
    parser.add_argument('--schema', type=str, metavar='PATH',
                        help="path or URL to an XSD schema.")
    parser.add_argument('--version', type=xsd_version_number, default='1.0',
                        help="XSD schema validator to use (default is 1.0).")
    parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append',
                        metavar="URI/URL", help="schema location hint overrides.")
    parser.add_argument('--converter', type=str, metavar='NAME',
                        help="use a different XML to JSON convention instead of "
                             "the default converter. Option value can be one of "
                             "{!r}.".format(tuple(CONVERTERS_MAP)))
    parser.add_argument('--indent', type=int, default=None,
                        help="indentation for a pretty-printed JSON output "
                             "(default is the most compact representation)")
    parser.add_argument('--lazy', action='store_true', default=False,
                        help="use lazy decoding mode (slower but use less memory).")
    parser.add_argument('--defuse', metavar='(always, remote, never)',
                        type=defuse_data, default='remote',
                        help="when to defuse XML data, on remote resources for default.")
    parser.add_argument('-o', '--output', type=str, default='.',
                        help="where to write the encoded XML files, current dir by default.")
    parser.add_argument('-f', '--force', action="store_true", default=False,
                        help="do not prompt before overwriting.")
    parser.add_argument('files', metavar='[XML_FILE ...]', nargs='+',
                        help="XML files to be decoded to JSON.")

    args = parser.parse_args()

    loglevel = get_loglevel(args.verbosity)
    schema_class = XMLSchema if args.version == '1.0' else XMLSchema11
    converter = get_converter(args.converter)
    if args.schema is not None:
        schema = schema_class(args.schema, locations=args.locations, loglevel=loglevel)
    else:
        schema = None

    json_options = {}
    if args.indent is not None and args.indent >= 0:
        json_options['indent'] = args.indent

    base_path = pathlib.Path(args.output)
    if not base_path.exists():
        base_path.mkdir()
    elif not base_path.is_dir():
        raise XMLSchemaValueError("{!r} is not a directory".format(str(base_path)))

    tot_errors = 0
    for xml_path in map(pathlib.Path, args.files):
        json_path = base_path.joinpath(xml_path.name).with_suffix('.json')
        if json_path.exists() and not args.force:
            print("skip {}: the destination file exists!".format(str(json_path)))
            continue

        with open(str(json_path), 'w') as fp:
            try:
                errors = to_json(
                    xml_document=str(xml_path),
                    fp=fp,
                    schema=schema,
                    cls=schema_class,
                    converter=converter,
                    lazy=args.lazy,
                    defuse=args.defuse,
                    validation='lax',
                    json_options=json_options,
                )
            except (xmlschema.XMLSchemaException, URLError) as err:
                tot_errors += 1
                print("error with {}: {}".format(str(xml_path), str(err)))
                continue
            else:
                if not errors:
                    print("{} converted to {}".format(str(xml_path), str(json_path)))
                else:
                    tot_errors += len(errors)
                    print("{} converted to {} with {} errors".format(
                        str(xml_path), str(json_path), len(errors)
                    ))

    sys.exit(tot_errors)

def json2xml():
    parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True,
                                     description="encode a set of JSON files to XML.")
    parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \
                   "Try '%(prog)s --help' for more information."

    parser.add_argument('-v', dest='verbosity', action='count', default=0,
                        help="increase output verbosity.")
    parser.add_argument('--schema', type=str, metavar='PATH',
                        help="path or URL to an XSD schema.")
    parser.add_argument('--version', type=xsd_version_number, default='1.0',
                        help="XSD schema validator to use (default is 1.0).")
    parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append',
                        metavar="URI/URL", help="schema location hint overrides.")
    parser.add_argument('--converter', type=str, metavar='NAME',
                        help="use a different XML to JSON convention instead of "
                             "the default converter. Option value can be one of "
                             "{!r}.".format(tuple(CONVERTERS_MAP)))
    parser.add_argument('--indent', type=int, default=4,
                        help="indentation for XML output (default is 4 spaces)")
    parser.add_argument('-o', '--output', type=str, default='.',
                        help="where to write the encoded XML files, current dir by default.")
    parser.add_argument('-f', '--force', action="store_true", default=False,
                        help="do not prompt before overwriting")
    parser.add_argument('files', metavar='[JSON_FILE ...]', nargs='+',
                        help="JSON files to be encoded to XML.")

    args = parser.parse_args()

    loglevel = get_loglevel(args.verbosity)
    schema_class = XMLSchema if args.version == '1.0' else XMLSchema11
    converter = get_converter(args.converter)
    schema = schema_class(args.schema, locations=args.locations, loglevel=loglevel)

    base_path = pathlib.Path(args.output)
    if not base_path.exists():
        base_path.mkdir()
    elif not base_path.is_dir():
        raise XMLSchemaValueError("{!r} is not a directory".format(str(base_path)))

    tot_errors = 0
    for json_path in map(pathlib.Path, args.files):
        xml_path = base_path.joinpath(json_path.name).with_suffix('.xml')
        if xml_path.exists() and not args.force:
            print("skip {}: the destination file exists!".format(str(xml_path)))
            continue

        with open(str(json_path)) as fp:
            try:
                root, errors = from_json(
                    source=fp,
                    schema=schema,
                    converter=converter,
                    validation='lax',
                    indent=args.indent,
                )
            except (xmlschema.XMLSchemaException, URLError) as err:
                tot_errors += 1
                print("error with {}: {}".format(str(xml_path), str(err)))
                continue
            else:
                if not errors:
                    print("{} converted to {}".format(str(json_path), str(xml_path)))
                else:
                    tot_errors += len(errors)
                    print("{} converted to {} with {} errors".format(
                        str(json_path), str(xml_path), len(errors)
                    ))

        with open(str(xml_path), 'w') as fp:
            fp.write(etree_tostring(root))

    sys.exit(tot_errors)

def validate():
    parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True,
                                     description="validate a set of XML files.")
    parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \
                   "Try '%(prog)s --help' for more information."
    parser.add_argument('-v', dest='verbosity', action='count', default=0,
                        help="increase output verbosity.")
    parser.add_argument('--schema', type=str, metavar='PATH',
                        help="path or URL to an XSD schema.")
    parser.add_argument('--version', type=xsd_version_number, default='1.0',
                        help="XSD schema validator to use (default is 1.0).")
    parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append',
                        metavar="URI/URL", help="schema location hint overrides.")
    parser.add_argument('--lazy', action='store_true', default=False,
                        help="use lazy validation mode (slower but use less memory).")
    parser.add_argument('--defuse', metavar='(always, remote, never)',
                        type=defuse_data, default='remote',
                        help="when to defuse XML data, on remote resources for default.")
    parser.add_argument('files', metavar='[XML_FILE ...]', nargs='+',
                        help="XML files to be validated.")

    args = parser.parse_args()

    schema_class = XMLSchema if args.version == '1.0' else XMLSchema11

    tot_errors = 0
    for filepath in args.files:
        try:
            errors = list(iter_errors(filepath, schema=args.schema, cls=schema_class,
                                      locations=args.locations, lazy=args.lazy, defuse=args.defuse))
        except (xmlschema.XMLSchemaException, URLError) as err:
            tot_errors += 1
            print(str(err))
            continue
        else:
            if not errors:
                print("{} is valid".format(filepath))
            else:
                tot_errors += len(errors)
                print("{} is not valid".format(filepath))

    sys.exit(tot_errors)


text:
package com.google.gdata.data.webmastertools;

import com.google.gdata.data.BaseEntry;
import com.google.gdata.data.Category;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.Kind;

import java.util.List;

/**
 * Describes a crawl issue entry.
 *
 *
 */
@Kind.Term(CrawlIssueEntry.KIND)
public class CrawlIssueEntry extends BaseEntry<CrawlIssueEntry> {

  /**
   * Crawl Issue Entry kind term value.
   */
  public static final String KIND = Namespaces.WT_PREFIX + "crawl_issue_entry";

  /**
   * Crawl Issue Entry kind category.
   */
  public static final Category CATEGORY = new
      Category(com.google.gdata.util.Namespaces.gKind, KIND);

  /**
   * Default mutable constructor.
   */
  public CrawlIssueEntry() {
    super();
    getCategories().add(CATEGORY);
  }

  /**
   * Constructs a new instance by doing a shallow copy of data from an existing
   * {@link BaseEntry} instance.
   *
   * @param sourceEntry source entry
   */
  public CrawlIssueEntry(BaseEntry<?> sourceEntry) {
    super(sourceEntry);
  }

  @Override
  public void declareExtensions(ExtensionProfile extProfile) {
    if (extProfile.isDeclared(CrawlIssueEntry.class)) {
      return;
    }
    super.declareExtensions(extProfile);
    extProfile.declare(CrawlIssueEntry.class,
        CrawlIssueCrawlType.getDefaultDescription(true, false));
    extProfile.declare(CrawlIssueEntry.class, CrawlIssueDateDetected.class);
    extProfile.declare(CrawlIssueEntry.class, CrawlIssueDetail.class);
    extProfile.declare(CrawlIssueEntry.class,
        CrawlIssueIssueType.getDefaultDescription(true, false));
    extProfile.declare(CrawlIssueEntry.class,
        CrawlIssueLinkedFromUrl.getDefaultDescription(false, true));
    extProfile.declare(CrawlIssueEntry.class,
        CrawlIssueUrl.getDefaultDescription(true, false));
  }

  /**
   * Returns the crawl issue crawl type.
   *
   * @return crawl issue crawl type
   */
  public CrawlIssueCrawlType getCrawlType() {
    return getExtension(CrawlIssueCrawlType.class);
  }

  /**
   * Sets the crawl issue crawl type.
   *
   * @param crawlType crawl issue crawl type or null to reset
   */
  public void setCrawlType(CrawlIssueCrawlType crawlType) {
    if (crawlType == null) {
      removeExtension(CrawlIssueCrawlType.class);
    } else {
      setExtension(crawlType);
    }
  }

  /**
   * Returns whether it has the crawl issue crawl type.
   *
   * @return whether it has the crawl issue crawl type
   */
  public boolean hasCrawlType() {
    return hasExtension(CrawlIssueCrawlType.class);
  }

  /**
   * Returns the crawl issue date detected.
   *
   * @return crawl issue date detected
   */
  public CrawlIssueDateDetected getDateDetected() {
    return getExtension(CrawlIssueDateDetected.class);
  }

  /**
   * Sets the crawl issue date detected.
   *
   * @param dateDetected crawl issue date detected or null to reset
   */
  public void setDateDetected(CrawlIssueDateDetected dateDetected) {
    if (dateDetected == null) {
      removeExtension(CrawlIssueDateDetected.class);
    } else {
      setExtension(dateDetected);
    }
  }

  /**
   * Returns whether it has the crawl issue date detected.
   *
   * @return whether it has the crawl issue date detected
   */
  public boolean hasDateDetected() {
    return hasExtension(CrawlIssueDateDetected.class);
  }

  /**
   * Returns the crawl issue detail.
   *
   * @return crawl issue detail
   */
  public CrawlIssueDetail getDetail() {
    return getExtension(CrawlIssueDetail.class);
  }

  /**
   * Sets the crawl issue detail.
   *
   * @param detail crawl issue detail or null to reset
   */
  public void setDetail(CrawlIssueDetail detail) {
    if (detail == null) {
      removeExtension(CrawlIssueDetail.class);
    } else {
      setExtension(detail);
    }
  }

  /**
   * Returns whether it has the crawl issue detail.
   *
   * @return whether it has the crawl issue detail
   */
  public boolean hasDetail() {
    return hasExtension(CrawlIssueDetail.class);
  }

  /**
   * Returns the crawl issue issue type.
   *
   * @return crawl issue issue type
   */
  public CrawlIssueIssueType getIssueType() {
    return getExtension(CrawlIssueIssueType.class);
  }

  /**
   * Sets the crawl issue issue type.
   *
   * @param issueType crawl issue issue type or null to reset
   */
  public void setIssueType(CrawlIssueIssueType issueType) {
    if (issueType == null) {
      removeExtension(CrawlIssueIssueType.class);
    } else {
      setExtension(issueType);
    }
  }

  /**
   * Returns whether it has the crawl issue issue type.
   *
   * @return whether it has the crawl issue issue type
   */
  public boolean hasIssueType() {
    return hasExtension(CrawlIssueIssueType.class);
  }

  /**
   * Returns the crawl issue linked from urls.
   *
   * @return crawl issue linked from urls
   */
  public List<CrawlIssueLinkedFromUrl> getLinkedFroms() {
    return getRepeatingExtension(CrawlIssueLinkedFromUrl.class);
  }

  /**
   * Adds a new crawl issue linked from url.
   *
   * @param linkedFrom crawl issue linked from url
   */
  public void addLinkedFrom(CrawlIssueLinkedFromUrl linkedFrom) {
    getLinkedFroms().add(linkedFrom);
  }

  /**
   * Returns whether it has the crawl issue linked from urls.
   *
   * @return whether it has the crawl issue linked from urls
   */
  public boolean hasLinkedFroms() {
    return hasRepeatingExtension(CrawlIssueLinkedFromUrl.class);
  }

  /**
   * Returns the crawl issue url.
   *
   * @return crawl issue url
   */
  public CrawlIssueUrl getUrl() {
    return getExtension(CrawlIssueUrl.class);
  }

  /**
   * Sets the crawl issue url.
   *
   * @param url crawl issue url or null to reset
   */
  public void setUrl(CrawlIssueUrl url) {
    if (url == null) {
      removeExtension(CrawlIssueUrl.class);
    } else {
      setExtension(url);
    }
  }

  /**
   * Returns whether it has the crawl issue url.
   *
   * @return whether it has the crawl issue url
   */
  public boolean hasUrl() {
    return hasExtension(CrawlIssueUrl.class);
  }

  @Override
  protected void validate() {
  }

  @Override
  public String toString() {
    return "{CrawlIssueEntry " + super.toString() + "}";
  }

}


text:
package org.oxbow.markdownfx;

import java.util.Arrays;

import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import org.controlsfx.control.action.ActionGroup;
import org.controlsfx.control.action.ActionMap;
import static org.controlsfx.control.action.ActionMap.actions;
import org.controlsfx.control.action.ActionProxy;
import org.controlsfx.control.action.ActionUtils;
import org.controlsfx.control.action.ActionUtils.ActionTextBehavior;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.Dialogs;

public class Start extends javafx.application.Application implements DocumentEditorProvider {

    private TabPane tabs = new TabPane();
    private Stage stage;

    public Start() {
    	ActionMap.register(this);
	}

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

    	stage = primaryStage;

        createDocumentEditor();

        MenuBar menuBar = ActionUtils.createMenuBar( Arrays.asList(
              new ActionGroup("File", actions("newdoc", "opendoc", "savedoc", "---", "appexit")),
              new ActionGroup("Edit", actions("cut", "copy", "paste"))
        ));

        menuBar.setUseSystemMenuBar(true); // Mac OSX support

        ToolBar toolBar = ActionUtils.createToolBar(
        	actions("newdoc", "opendoc", "savedoc",	"---", "cut", "copy", "paste"),
            ActionTextBehavior.HIDE
        );

        BorderPane content = new BorderPane();
        content.setTop(new VBox(menuBar, toolBar));
        content.setCenter(tabs);
        content.setPrefSize(1000, 800);
//        Pane statusBar = new Pane( new Label("v 1.0.0"));
//        statusBar.setPadding(new Insets(5,5,5,5));
//        content.setBottom(statusBar);

        primaryStage.setTitle("Markdown Pad FX");
        primaryStage.setScene(new Scene(content));
        primaryStage.show();
    }

    @ActionProxy(
    	id="newdoc",
    	text="New",
    	graphic="font>icomoon|FILE2",
    	longText = "Create New Document")
    private DocumentEditor createDocumentEditor() {
        final DocumentEditor editor = new DocumentEditor("");
        Tab tab = new Tab( "New Document" );
        tab.setContent(editor);
        tab.setOnCloseRequest(new EventHandler<Event>() {

            public void handle(Event e) {

               Dialogs dlg = Dialogs.create().title("Confirmation").message("Close tab?");
               if ( editor.isDirty() && dlg.showConfirm() != Dialog.Actions.YES ){
                  e.consume();
               }

            }
        });

        tabs.getTabs().add(tab);
        tabs.getSelectionModel().select(tab);
        return editor;
    }

    @ActionProxy( id ="appexit", text="Exit")
    private void appExit(ActionEvent e) {
    	if ( stage != null ) stage.close();
    }

    @ActionProxy( id ="opendoc", text="Open", graphic="font>icomoon|FOLDER_OPEN")
    private void openDocument(ActionEvent e) {
    	System.out.println("Start.openDocument()");
    }

    @ActionProxy( id ="savedoc", text="Save", graphic="font>icomoon|DISK")
    private void saveDocument(ActionEvent e) {
    	System.out.println("Start.saveDocument()");
    }

    @ActionProxy( id ="cut", text="Cut", graphic="font>icomoon|SCISSORS")
    private void cut(ActionEvent e) {
    	System.out.println("Start.cut()");
    }

    @ActionProxy( id ="copy", text="Copy", graphic="font>icomoon|COPY")
    private void copy(ActionEvent e) {
    	System.out.println("Start.copy()");
    }

    @ActionProxy( id ="paste", text="Paste", graphic="font>icomoon|PASTE2")
    private void paste(ActionEvent e) {
    	System.out.println("Start.paste()");
    }

    public DocumentEditor getDocumentEditor() {
        Tab tab = tabs.getSelectionModel().getSelectedItem();
        return  tab == null? null: (DocumentEditor) tab.getContent();
    }

}


text:
New Pong
https://docs.google.com/presentation/d/1muVrJvM1yrxy8eDaRSKprNwQP87L3mtYQu-v1B7wjhQ/edit?usp=sharing