Search in sources :

Example 1 with Property

use of com.sun.tools.xjc.api.Property in project axis-axis2-java-core by apache.

the class CodeGenerationUtility method processSchemas.

/**
 * @param additionalSchemas
 * @throws RuntimeException
 */
public static TypeMapper processSchemas(final List<XmlSchema> schemas, Element[] additionalSchemas, CodeGenConfiguration cgconfig) throws RuntimeException {
    try {
        // Work around MNG-6506.
        CodeGenerationUtility.class.getClassLoader().loadClass("com.sun.tools.xjc.reader.xmlschema.bindinfo.package-info");
        // check for the imported types. Any imported types are supposed to be here also
        if (schemas == null || schemas.isEmpty()) {
            // processes. Hence the default type mapper is set to the configuration
            return new DefaultTypeMapper();
        }
        final Map<XmlSchema, InputSource> schemaToInputSourceMap = new HashMap<>();
        final Map<String, StringBuffer> publicIDToStringMap = new HashMap<String, StringBuffer>();
        // create the type mapper
        JavaTypeMapper mapper = new JavaTypeMapper();
        String baseURI = cgconfig.getBaseURI();
        if (!baseURI.endsWith("/")) {
            baseURI = baseURI + "/";
        }
        for (int i = 0; i < schemas.size(); i++) {
            XmlSchema schema = schemas.get(i);
            InputSource inputSource = new InputSource(new StringReader(getSchemaAsString(schema)));
            // here we have to set a proper system ID. otherwise when processing the
            // included schaemas for this schema we have a problem
            // it creates the system ID using this target namespace value
            inputSource.setSystemId(baseURI + "xsd" + i + ".xsd");
            inputSource.setPublicId(schema.getTargetNamespace());
            schemaToInputSourceMap.put(schema, inputSource);
        }
        File outputDir = new File(cgconfig.getOutputLocation(), "src");
        outputDir.mkdir();
        Map<String, String> nsMap = cgconfig.getUri2PackageNameMap();
        EntityResolver resolver = new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                InputSource returnInputSource = null;
                for (XmlSchema key : schemaToInputSourceMap.keySet()) {
                    String nsp = key.getTargetNamespace();
                    if (nsp != null && nsp.equals(publicId)) {
                        // when returning the input stream we have to always return a new
                        // input stream.
                        // sinc jaxbri internally consumes the input stream it gives an
                        // exception.
                        returnInputSource = new InputSource(new StringReader(getSchemaAsString(key)));
                        InputSource existingInputSource = (InputSource) schemaToInputSourceMap.get(key);
                        returnInputSource.setSystemId(existingInputSource.getSystemId());
                        returnInputSource.setPublicId(existingInputSource.getPublicId());
                        break;
                    }
                }
                if (returnInputSource == null) {
                    // then we have to find this using the file system
                    if (systemId != null) {
                        returnInputSource = new InputSource(systemId);
                        returnInputSource.setSystemId(systemId);
                    }
                }
                if (returnInputSource == null) {
                    if (publicId != null) {
                        if (!publicIDToStringMap.containsKey(publicId)) {
                            URL url = new URL(publicId);
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
                            StringBuffer stringBuffer = new StringBuffer();
                            String str = null;
                            while ((str = bufferedReader.readLine()) != null) {
                                stringBuffer.append(str);
                            }
                            publicIDToStringMap.put(publicId, stringBuffer);
                        }
                        String schemaString = publicIDToStringMap.get(publicId).toString();
                        returnInputSource = new InputSource(new StringReader(schemaString));
                        returnInputSource.setPublicId(publicId);
                        returnInputSource.setSystemId(publicId);
                    }
                }
                return returnInputSource;
            }
        };
        Map<Object, Object> properties = cgconfig.getProperties();
        String bindingFileName = (String) properties.get(BINDING_FILE_NAME);
        for (XmlSchema key : schemaToInputSourceMap.keySet()) {
            SchemaCompiler sc = XJC.createSchemaCompiler();
            if (bindingFileName != null) {
                if (bindingFileName.endsWith(".jar")) {
                    scanEpisodeFile(new File(bindingFileName), sc);
                } else {
                    InputSource inputSoruce = new InputSource(new FileInputStream(bindingFileName));
                    inputSoruce.setSystemId(new File(bindingFileName).toURI().toString());
                    sc.getOptions().addBindFile(inputSoruce);
                }
            }
            if (nsMap != null) {
                for (Map.Entry<String, String> entry : nsMap.entrySet()) {
                    registerNamespace(sc, entry.getKey(), entry.getValue());
                }
            }
            sc.setEntityResolver(resolver);
            sc.setErrorListener(new ErrorListener() {

                public void error(SAXParseException saxParseException) {
                    log.error(saxParseException.getMessage());
                    log.debug(saxParseException.getMessage(), saxParseException);
                }

                public void fatalError(SAXParseException saxParseException) {
                    log.error(saxParseException.getMessage());
                    log.debug(saxParseException.getMessage(), saxParseException);
                }

                public void warning(SAXParseException saxParseException) {
                    log.warn(saxParseException.getMessage());
                    log.debug(saxParseException.getMessage(), saxParseException);
                }

                public void info(SAXParseException saxParseException) {
                    log.info(saxParseException.getMessage());
                    log.debug(saxParseException.getMessage(), saxParseException);
                }
            });
            sc.parseSchema((InputSource) schemaToInputSourceMap.get(key));
            sc.getOptions().addGrammar((InputSource) schemaToInputSourceMap.get(key));
            for (Object property : properties.keySet()) {
                String propertyName = (String) property;
                if (propertyName.startsWith("X")) {
                    String[] args = null;
                    String propertyValue = (String) properties.get(property);
                    if (propertyValue != null) {
                        args = new String[] { "-" + propertyName, propertyValue };
                    } else {
                        args = new String[] { "-" + propertyName };
                    }
                    sc.getOptions().parseArguments(args);
                }
            }
            // Bind the XML
            S2JJAXBModel jaxbModel = sc.bind();
            if (jaxbModel == null) {
                throw new RuntimeException("Unable to generate code using jaxbri");
            }
            // Emit the code artifacts
            JCodeModel codeModel = jaxbModel.generateCode(null, null);
            FileCodeWriter writer = new FileCodeWriter(outputDir, cgconfig.getOutputEncoding());
            codeModel.build(writer);
            for (Mapping mapping : jaxbModel.getMappings()) {
                QName qn = mapping.getElement();
                String typeName = mapping.getType().getTypeClass().fullName();
                mapper.addTypeMappingName(qn, typeName);
            }
            // process the unwrapped parameters
            if (!cgconfig.isParametersWrapped()) {
                // figure out the unwrapped operations
                for (AxisService axisService : cgconfig.getAxisServices()) {
                    for (Iterator<AxisOperation> operations = axisService.getOperations(); operations.hasNext(); ) {
                        AxisOperation op = operations.next();
                        if (WSDLUtil.isInputPresentForMEP(op.getMessageExchangePattern())) {
                            AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                            if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {
                                Mapping mapping = jaxbModel.get(message.getElementQName());
                                for (Property elementProperty : mapping.getWrapperStyleDrilldown()) {
                                    QName partQName = WSDLUtil.getPartQName(op.getName().getLocalPart(), WSDLConstants.INPUT_PART_QNAME_SUFFIX, elementProperty.elementName().getLocalPart());
                                    // this type is based on a primitive type- use the
                                    // primitive type name in this case
                                    String fullJaveName = elementProperty.type().fullName();
                                    if (elementProperty.type().isArray()) {
                                        fullJaveName = fullJaveName.concat("[]");
                                    }
                                    mapper.addTypeMappingName(partQName, fullJaveName);
                                    if (elementProperty.type().isPrimitive()) {
                                        mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                                    }
                                    if (elementProperty.type().isArray()) {
                                        mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                                    }
                                }
                            }
                        }
                        if (WSDLUtil.isOutputPresentForMEP(op.getMessageExchangePattern())) {
                            AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                            if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {
                                Mapping mapping = jaxbModel.get(message.getElementQName());
                                for (Property elementProperty : mapping.getWrapperStyleDrilldown()) {
                                    QName partQName = WSDLUtil.getPartQName(op.getName().getLocalPart(), WSDLConstants.OUTPUT_PART_QNAME_SUFFIX, elementProperty.elementName().getLocalPart());
                                    // this type is based on a primitive type- use the
                                    // primitive type name in this case
                                    String fullJaveName = elementProperty.type().fullName();
                                    if (elementProperty.type().isArray()) {
                                        fullJaveName = fullJaveName.concat("[]");
                                    }
                                    mapper.addTypeMappingName(partQName, fullJaveName);
                                    if (elementProperty.type().isPrimitive()) {
                                        mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                                    }
                                    if (elementProperty.type().isArray()) {
                                        mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Return the type mapper
        return mapper;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) AxisOperation(org.apache.axis2.description.AxisOperation) AxisService(org.apache.axis2.description.AxisService) Mapping(com.sun.tools.xjc.api.Mapping) SchemaCompiler(com.sun.tools.xjc.api.SchemaCompiler) DefaultTypeMapper(org.apache.axis2.wsdl.databinding.DefaultTypeMapper) URL(java.net.URL) ErrorListener(com.sun.tools.xjc.api.ErrorListener) FileCodeWriter(com.sun.codemodel.writer.FileCodeWriter) SAXParseException(org.xml.sax.SAXParseException) S2JJAXBModel(com.sun.tools.xjc.api.S2JJAXBModel) AxisMessage(org.apache.axis2.description.AxisMessage) Property(com.sun.tools.xjc.api.Property) QName(javax.xml.namespace.QName) EntityResolver(org.xml.sax.EntityResolver) JCodeModel(com.sun.codemodel.JCodeModel) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) XmlSchema(org.apache.ws.commons.schema.XmlSchema) JavaTypeMapper(org.apache.axis2.wsdl.databinding.JavaTypeMapper)

Example 2 with Property

use of com.sun.tools.xjc.api.Property in project jaxb-ri by eclipse-ee4j.

the class AbstractMappingImpl method buildDrilldown.

/**
 * Derived classes can use this method to implement {@link #calcDrilldown}.
 */
protected List<Property> buildDrilldown(CClassInfo typeBean) {
    // they must not contain xsd:choice
    if (containingChoice(typeBean)) {
        return null;
    }
    List<Property> result;
    CClassInfo bc = typeBean.getBaseClass();
    if (bc != null) {
        result = buildDrilldown(bc);
        if (result == null) {
            // aborted
            return null;
        }
    } else {
        result = new ArrayList<>();
    }
    for (CPropertyInfo p : typeBean.getProperties()) {
        if (p instanceof CElementPropertyInfo) {
            CElementPropertyInfo ep = (CElementPropertyInfo) p;
            // wrong. A+,B,C is eligible for drill-down.
            // if(ep.isCollection())
            // // content model like A+,B,C is not eligible
            // return null;
            List<? extends CTypeRef> ref = ep.getTypes();
            if (ref.size() != 1) {
                // content model like (A|B),C is not eligible
                return null;
            }
            result.add(createPropertyImpl(ep, ref.get(0).getTagName()));
        } else if (p instanceof ReferencePropertyInfo) {
            CReferencePropertyInfo rp = (CReferencePropertyInfo) p;
            Collection<CElement> elements = rp.getElements();
            if (elements.size() != 1) {
                return null;
            }
            CElement ref = elements.iterator().next();
            if (ref instanceof ClassInfo) {
                result.add(createPropertyImpl(rp, ref.getElementName()));
            } else {
                CElementInfo eref = (CElementInfo) ref;
                if (!eref.getSubstitutionMembers().isEmpty()) {
                    // elements with a substitution group isn't qualified for the wrapper style
                    return null;
                }
                // JAX-WS doesn't want to see JAXBElement, so we have to hide it for them.
                ElementAdapter fr;
                if (rp.isCollection()) {
                    fr = new ElementCollectionAdapter(parent.outline.getField(rp), eref);
                } else {
                    fr = new ElementSingleAdapter(parent.outline.getField(rp), eref);
                }
                result.add(new PropertyImpl(this, fr, eref.getElementName()));
            }
        } else {
            // according to the JAX-RPC spec 2.3.1.2, element refs are disallowed
            return null;
        }
    }
    return result;
}
Also used : CElementInfo(com.sun.tools.xjc.model.CElementInfo) CPropertyInfo(com.sun.tools.xjc.model.CPropertyInfo) CClassInfo(com.sun.tools.xjc.model.CClassInfo) CElementPropertyInfo(com.sun.tools.xjc.model.CElementPropertyInfo) CElement(com.sun.tools.xjc.model.CElement) CReferencePropertyInfo(com.sun.tools.xjc.model.CReferencePropertyInfo) ReferencePropertyInfo(org.glassfish.jaxb.core.v2.model.core.ReferencePropertyInfo) Collection(java.util.Collection) CReferencePropertyInfo(com.sun.tools.xjc.model.CReferencePropertyInfo) Property(com.sun.tools.xjc.api.Property) CClassInfo(com.sun.tools.xjc.model.CClassInfo) ClassInfo(org.glassfish.jaxb.core.v2.model.core.ClassInfo)

Aggregations

Property (com.sun.tools.xjc.api.Property)2 JCodeModel (com.sun.codemodel.JCodeModel)1 FileCodeWriter (com.sun.codemodel.writer.FileCodeWriter)1 BadCommandLineException (com.sun.tools.xjc.BadCommandLineException)1 ErrorListener (com.sun.tools.xjc.api.ErrorListener)1 Mapping (com.sun.tools.xjc.api.Mapping)1 S2JJAXBModel (com.sun.tools.xjc.api.S2JJAXBModel)1 SchemaCompiler (com.sun.tools.xjc.api.SchemaCompiler)1 CClassInfo (com.sun.tools.xjc.model.CClassInfo)1 CElement (com.sun.tools.xjc.model.CElement)1 CElementInfo (com.sun.tools.xjc.model.CElementInfo)1 CElementPropertyInfo (com.sun.tools.xjc.model.CElementPropertyInfo)1 CPropertyInfo (com.sun.tools.xjc.model.CPropertyInfo)1 CReferencePropertyInfo (com.sun.tools.xjc.model.CReferencePropertyInfo)1 URL (java.net.URL)1 Collection (java.util.Collection)1 QName (javax.xml.namespace.QName)1 AxisMessage (org.apache.axis2.description.AxisMessage)1 AxisOperation (org.apache.axis2.description.AxisOperation)1 AxisService (org.apache.axis2.description.AxisService)1