Search in sources :

Example 96 with Message

use of org.apache.cxf.common.i18n.Message in project cxf by apache.

the class ClassUtils method copyXmlFile.

private void copyXmlFile(File from, File to) throws ToolException, IOException {
    String dir = to.getCanonicalPath().substring(0, to.getCanonicalPath().lastIndexOf(File.separator));
    File dirFile = new File(dir);
    dirFile.mkdirs();
    try (InputStream input = Files.newInputStream(from.toPath());
        OutputStream output = Files.newOutputStream(to.toPath())) {
        byte[] b = new byte[1024 * 3];
        int len = 0;
        while (len != -1) {
            len = input.read(b);
            if (len != -1) {
                output.write(b, 0, len);
            }
        }
        output.flush();
    } catch (Exception e) {
        Message msg = new Message("FAIL_TO_COPY_GENERATED_RESOURCE_FILE", LOG);
        throw new ToolException(msg, e);
    }
}
Also used : Message(org.apache.cxf.common.i18n.Message) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) File(java.io.File) IOException(java.io.IOException)

Example 97 with Message

use of org.apache.cxf.common.i18n.Message in project fabric8 by jboss-fuse.

the class DynamicXJC method compileSchemas.

public CompileResults compileSchemas() {
    SchemaCompiler compiler = createSchemaCompiler();
    // our hashcode + timestamp ought to be enough.
    String stem = toString().replaceAll("@", "_") + "-" + System.currentTimeMillis();
    File src = new File(tmpdir, stem + "-src");
    if (!src.mkdir()) {
        throw new IllegalStateException("Unable to create working directory " + src.getPath());
    }
    boolean first = true;
    StringBuilder sb = new StringBuilder();
    for (String rawUrl : getSchemaUrls()) {
        String schemaUrl = resolveUrl(rawUrl);
        InnerErrorListener listener = new InnerErrorListener(schemaUrl);
        Object elForRun = ReflectionInvokationHandler.createProxyWrapper(listener, JAXBUtils.getParamClass(compiler, "setErrorListener"));
        compiler.setErrorListener(elForRun);
        compiler.parseSchema(new InputSource(schemaUrl));
        S2JJAXBModel intermediateModel = compiler.bind();
        listener.throwException();
        JCodeModel codeModel = intermediateModel.generateCode(null, elForRun);
        for (Iterator<JPackage> packages = codeModel.packages(); packages.hasNext(); ) {
            JPackage jpackage = packages.next();
            if (!isValidPackage(jpackage)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append(':');
            }
            sb.append(jpackage.name());
        }
        JAXBUtils.logGeneratedClassNames(LOG, codeModel);
        try {
            Object writer = JAXBUtils.createFileCodeWriter(src);
            codeModel.build(writer);
        } catch (Exception e) {
            throw new IllegalStateException("Unable to write generated Java files for schemas: " + e.getMessage(), e);
        }
    }
    String packageList = sb.toString();
    File classes = new File(tmpdir, stem + "-classes");
    if (!classes.mkdir()) {
        throw new IllegalStateException("Unable to create working directory " + classes.getPath());
    }
    StringBuilder classPath = new StringBuilder();
    try {
        setupClasspath(classPath, classLoader);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    List<File> srcFiles = FileUtils.getFilesRecurse(src, ".+\\.java$");
    if (!compileJavaSrc(classPath.toString(), srcFiles, classes.toString())) {
        LOG.log(Level.SEVERE, new Message("COULD_NOT_COMPILE_SRC", LOG, getSchemaUrls().toString()).toString());
    }
    FileUtils.removeDir(src);
    URL[] urls;
    try {
        urls = new URL[] { classes.toURI().toURL() };
    } catch (MalformedURLException mue) {
        throw new IllegalStateException("Internal error; a directory returns a malformed URL: " + mue.getMessage(), mue);
    }
    ClassLoader cl = ClassLoaderUtils.getURLClassLoader(urls, classLoader);
    JAXBContext context;
    Map<String, Object> contextProperties = jaxbContextProperties;
    if (contextProperties == null) {
        contextProperties = Collections.emptyMap();
    }
    try {
        if (StringUtils.isEmpty(packageList)) {
            context = JAXBContext.newInstance(new Class[0], contextProperties);
        } else {
            context = JAXBContext.newInstance(packageList, cl, contextProperties);
        }
    } catch (JAXBException jbe) {
        throw new IllegalStateException("Unable to create JAXBContext for generated packages: " + jbe.getMessage(), jbe);
    }
    // keep around for class loader discovery later
    classes.deleteOnExit();
    // FileUtils.removeDir(classes);
    return new CompileResults(cl, context);
}
Also used : InputSource(org.xml.sax.InputSource) MalformedURLException(java.net.MalformedURLException) Message(org.apache.cxf.common.i18n.Message) JAXBContext(javax.xml.bind.JAXBContext) SchemaCompiler(org.apache.cxf.common.jaxb.JAXBUtils.SchemaCompiler) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) S2JJAXBModel(org.apache.cxf.common.jaxb.JAXBUtils.S2JJAXBModel) JAXBException(javax.xml.bind.JAXBException) JPackage(org.apache.cxf.common.jaxb.JAXBUtils.JPackage) JCodeModel(org.apache.cxf.common.jaxb.JAXBUtils.JCodeModel) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) SAXParseException(org.xml.sax.SAXParseException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JDefinedClass(org.apache.cxf.common.jaxb.JAXBUtils.JDefinedClass) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 98 with Message

use of org.apache.cxf.common.i18n.Message in project tomee by apache.

the class EndpointImpl method createBinding.

final void createBinding(BindingInfo bi) throws EndpointException {
    if (null != bi) {
        String namespace = bi.getBindingId();
        try {
            final BindingFactory bf = bus.getExtension(BindingFactoryManager.class).getBindingFactory(namespace);
            if (null == bf) {
                Message msg = new Message("NO_BINDING_FACTORY", BUNDLE, namespace);
                throw new EndpointException(msg);
            }
            binding = bf.createBinding(bi);
        } catch (BusException ex) {
            throw new EndpointException(ex);
        }
    }
}
Also used : Message(org.apache.cxf.common.i18n.Message) BindingFactoryManager(org.apache.cxf.binding.BindingFactoryManager) BusException(org.apache.cxf.BusException) BindingFactory(org.apache.cxf.binding.BindingFactory)

Example 99 with Message

use of org.apache.cxf.common.i18n.Message in project tomee by apache.

the class JAXBSchemaInitializer method end.

public void end(FaultInfo fault) {
    MessagePartInfo part = fault.getFirstMessagePart();
    Class<?> cls = part.getTypeClass();
    Class<?> cl2 = (Class<?>) fault.getProperty(Class.class.getName());
    if (cls != cl2) {
        QName name = (QName) fault.getProperty("elementName");
        part.setElementQName(name);
        JAXBBeanInfo beanInfo = getBeanInfo(cls);
        if (beanInfo == null) {
            throw new Fault(new Message("NO_BEAN_INFO", LOG, cls.getName()));
        }
        SchemaInfo schemaInfo = serviceInfo.getSchema(part.getElementQName().getNamespaceURI());
        if (schemaInfo != null && !isExistSchemaElement(schemaInfo.getSchema(), part.getElementQName())) {
            XmlSchemaElement el = new XmlSchemaElement(schemaInfo.getSchema(), true);
            el.setName(part.getElementQName().getLocalPart());
            el.setNillable(true);
            schemaInfo.setElement(null);
            Iterator<QName> itr = beanInfo.getTypeNames().iterator();
            if (!itr.hasNext()) {
                return;
            }
            QName typeName = itr.next();
            el.setSchemaTypeName(typeName);
        }
    } else if (part.getXmlSchema() == null) {
        try {
            cls.getConstructor(new Class[] { String.class });
        } catch (Exception e) {
            try {
                cls.getConstructor(new Class[0]);
            } catch (Exception e2) {
                // no String or default constructor, we cannot use it
                return;
            }
        }
        // not mappable in JAXBContext directly, we'll have to do it manually :-(
        SchemaInfo schemaInfo = serviceInfo.getSchema(part.getElementQName().getNamespaceURI());
        if (schemaInfo == null || isExistSchemaElement(schemaInfo.getSchema(), part.getElementQName())) {
            return;
        }
        XmlSchemaElement el = new XmlSchemaElement(schemaInfo.getSchema(), true);
        el.setName(part.getElementQName().getLocalPart());
        schemaInfo.setElement(null);
        part.setXmlSchema(el);
        XmlSchemaComplexType ct = new XmlSchemaComplexType(schemaInfo.getSchema(), false);
        el.setSchemaType(ct);
        XmlSchemaSequence seq = new XmlSchemaSequence();
        ct.setParticle(seq);
        Method[] methods = cls.getMethods();
        for (Method m : methods) {
            if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
                int beginIdx = m.getName().startsWith("get") ? 3 : 2;
                try {
                    m.getDeclaringClass().getMethod("set" + m.getName().substring(beginIdx), m.getReturnType());
                    JAXBBeanInfo beanInfo = getBeanInfo(m.getReturnType());
                    if (beanInfo != null) {
                        el = new XmlSchemaElement(schemaInfo.getSchema(), false);
                        el.setName(m.getName().substring(beginIdx));
                        Iterator<QName> itr = beanInfo.getTypeNames().iterator();
                        if (!itr.hasNext()) {
                            return;
                        }
                        QName typeName = itr.next();
                        el.setSchemaTypeName(typeName);
                    }
                    seq.getItems().add(el);
                } catch (Exception e) {
                // not mappable
                }
            }
        }
    }
}
Also used : Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) MessagePartInfo(org.apache.cxf.service.model.MessagePartInfo) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) JAXBBeanInfo(org.apache.cxf.common.jaxb.JAXBBeanInfo) Iterator(java.util.Iterator) XmlSchemaComplexType(org.apache.ws.commons.schema.XmlSchemaComplexType) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 100 with Message

use of org.apache.cxf.common.i18n.Message in project tomee by apache.

the class JAXBEncoderDecoder method marshallException.

public static void marshallException(Marshaller marshaller, Exception elValue, MessagePartInfo part, Object source) {
    XMLStreamWriter writer = getStreamWriter(source);
    QName qn = part.getElementQName();
    try {
        writer.writeStartElement("ns1", qn.getLocalPart(), qn.getNamespaceURI());
        Class<?> cls = part.getTypeClass();
        XmlAccessType accessType = Utils.getXmlAccessType(cls);
        String namespace = part.getElementQName().getNamespaceURI();
        String attNs = namespace;
        SchemaInfo sch = part.getMessageInfo().getOperation().getInterface().getService().getSchema(namespace);
        if (sch == null) {
            LOG.warning("Schema associated with " + namespace + " is null");
            namespace = null;
            attNs = null;
        } else {
            if (!sch.isElementFormQualified()) {
                namespace = null;
            }
            if (!sch.isAttributeFormQualified()) {
                attNs = null;
            }
        }
        List<Member> combinedMembers = new ArrayList<>();
        for (Field f : Utils.getFields(cls, accessType)) {
            XmlAttribute at = f.getAnnotation(XmlAttribute.class);
            if (at == null) {
                combinedMembers.add(f);
            } else {
                QName fname = new QName(attNs, StringUtils.isEmpty(at.name()) ? f.getName() : at.name());
                ReflectionUtil.setAccessible(f);
                Object o = Utils.getFieldValue(f, elValue);
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                writeObject(marshaller, frag, newJAXBElement(fname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, fname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(fname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        for (Method m : Utils.getGetters(cls, accessType)) {
            if (!m.isAnnotationPresent(XmlAttribute.class)) {
                combinedMembers.add(m);
            } else {
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                XmlAttribute at = m.getAnnotation(XmlAttribute.class);
                QName mname = new QName(namespace, StringUtils.isEmpty(at.name()) ? name : at.name());
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                Object o = Utils.getMethodValue(m, elValue);
                writeObject(marshaller, frag, newJAXBElement(mname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, mname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(mname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        XmlAccessorOrder xmlAccessorOrder = cls.getAnnotation(XmlAccessorOrder.class);
        if (xmlAccessorOrder != null && xmlAccessorOrder.value().equals(XmlAccessOrder.ALPHABETICAL)) {
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    return m1.getName().compareTo(m2.getName());
                }
            });
        }
        XmlType xmlType = cls.getAnnotation(XmlType.class);
        if (xmlType != null && xmlType.propOrder().length > 1 && !xmlType.propOrder()[0].isEmpty()) {
            final List<String> orderList = Arrays.asList(xmlType.propOrder());
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    String m1Name = getName(m1);
                    String m2Name = getName(m2);
                    int m1Index = orderList.indexOf(m1Name);
                    int m2Index = orderList.indexOf(m2Name);
                    if (m1Index != -1 && m2Index != -1) {
                        return m1Index - m2Index;
                    }
                    if (m1Index == -1 && m2Index != -1) {
                        return 1;
                    }
                    if (m1Index != -1 && m2Index == -1) {
                        return -1;
                    }
                    return 0;
                }
            });
        }
        for (Member member : combinedMembers) {
            if (member instanceof Field) {
                Field f = (Field) member;
                QName fname = new QName(namespace, f.getName());
                ReflectionUtil.setAccessible(f);
                if (JAXBSchemaInitializer.isArray(f.getGenericType())) {
                    writeArrayObject(marshaller, writer, fname, f.get(elValue));
                } else {
                    Object o = Utils.getFieldValue(f, elValue);
                    writeObject(marshaller, writer, newJAXBElement(fname, String.class, o));
                }
            } else {
                // it's a Method
                Method m = (Method) member;
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                QName mname = new QName(namespace, name);
                if (JAXBSchemaInitializer.isArray(m.getGenericReturnType())) {
                    writeArrayObject(marshaller, writer, mname, m.invoke(elValue));
                } else {
                    Object o = Utils.getMethodValue(m, elValue);
                    writeObject(marshaller, writer, newJAXBElement(mname, String.class, o));
                }
            }
        }
        writer.writeEndElement();
        writer.flush();
    } catch (Exception e) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
    } finally {
        StaxUtils.close(writer);
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessorOrder) Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) PrivilegedActionException(java.security.PrivilegedActionException) XmlType(javax.xml.bind.annotation.XmlType) Field(java.lang.reflect.Field) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Member(java.lang.reflect.Member) DocumentFragment(org.w3c.dom.DocumentFragment) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Aggregations

Message (org.apache.cxf.common.i18n.Message)201 ToolException (org.apache.cxf.tools.common.ToolException)69 IOException (java.io.IOException)45 QName (javax.xml.namespace.QName)42 Fault (org.apache.cxf.interceptor.Fault)34 XMLStreamException (javax.xml.stream.XMLStreamException)27 JAXBException (javax.xml.bind.JAXBException)23 ArrayList (java.util.ArrayList)19 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)17 Element (org.w3c.dom.Element)17 File (java.io.File)16 WSDLException (javax.wsdl.WSDLException)15 Method (java.lang.reflect.Method)14 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)13 ServiceInfo (org.apache.cxf.service.model.ServiceInfo)12 InputStream (java.io.InputStream)11 HashMap (java.util.HashMap)11 List (java.util.List)11 Map (java.util.Map)11 ServiceConstructionException (org.apache.cxf.service.factory.ServiceConstructionException)11