Search in sources :

Example 1 with ChildElementInfo

use of com.predic8.membrane.annot.model.ChildElementInfo in project service-proxy by membrane.

the class BlueprintParsers method writeParsers.

public void writeParsers(Model m) throws IOException {
    for (MainInfo main : m.getMains()) {
        for (ElementInfo ii : main.getIis()) {
            List<Element> sources = new ArrayList<Element>();
            sources.add(main.getElement());
            sources.add(ii.getElement());
            String interceptorClassName = ii.getElement().getQualifiedName().toString();
            try {
                FileObject o = processingEnv.getFiler().createSourceFile(main.getAnnotation().outputPackage() + ".blueprint" + "." + ii.getParserClassSimpleName(), sources.toArray(new Element[0]));
                BufferedWriter bw = new BufferedWriter(o.openWriter());
                try {
                    bw.write("/* Copyright 2014 predic8 GmbH, www.predic8.com\r\n" + "\r\n" + "   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n" + "   you may not use this file except in compliance with the License.\r\n" + "   You may obtain a copy of the License at\r\n" + "\r\n" + "   http://www.apache.org/licenses/LICENSE-2.0\r\n" + "\r\n" + "   Unless required by applicable law or agreed to in writing, software\r\n" + "   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n" + "   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n" + "   See the License for the specific language governing permissions and\r\n" + "   limitations under the License. */\r\n" + "\r\n" + "package " + main.getAnnotation().outputPackage() + ".blueprint;\r\n" + "\r\n" + "import com.predic8.membrane.annot.parser.BlueprintElementParser;\r\n" + "import com.predic8.membrane.annot.parser.BlueprintParser;\r\n" + "import org.apache.aries.blueprint.ParserContext;\r\n" + "import org.osgi.service.blueprint.reflect.Metadata;\r\n" + "import org.apache.aries.blueprint.mutable.MutableBeanMetadata;\r\n" + "import org.osgi.service.blueprint.reflect.BeanMetadata;\r\n" + "import org.w3c.dom.Element;\r\n" + "");
                    bw.write("\r\n" + "/**\r\n" + "  * Automatically generated by " + BlueprintParsers.class.getName() + ".\r\n" + "  */\r\n" + "public class " + ii.getParserClassSimpleName() + " extends BlueprintElementParser {\r\n" + "	public Metadata parse(BlueprintParser globalParser, Element element, ParserContext context) {\r\n" + "		MutableBeanMetadata mcm = context.createMetadata(MutableBeanMetadata.class);\r\n" + "		mcm.setId(context.generateId());\r\n" + "		mcm.setScope(BeanMetadata.SCOPE_SINGLETON);\r\n" + "		mcm.setRuntimeClass(" + interceptorClassName + ".class);\r\n" + "		applySpringInterfacePatches(context, " + interceptorClassName + ".class, mcm);\r\n" + "\r\n");
                    if (ii.isHasIdField())
                        bw.write("		setPropertyIfSet(context, \"id\", element, mcm);\r\n");
                    bw.write("		setIdIfNeeded(element, context, \"" + ii.getAnnotation().name() + "\");\r\n");
                    for (AttributeInfo ai : ii.getAis()) {
                        if (ai.getXMLName().equals("id"))
                            continue;
                        if (ai.isBeanReference(processingEnv.getTypeUtils())) {
                            if (!ai.isRequired())
                                bw.write("		if (element.hasAttribute(\"" + ai.getXMLName() + "\"))\r\n");
                            bw.write("		setPropertyReference(context, \"" + ai.getSpringName() + "\", element.getAttribute(\"" + ai.getXMLName() + "\"), mcm);\r\n");
                        } else {
                            bw.write("		setProperty" + (ai.isRequired() ? "" : "IfSet") + "(context, \"" + ai.getXMLName() + "\", \"" + ai.getSpringName() + "\", element, mcm" + (ai.isEnum(processingEnv.getTypeUtils()) ? ", true" : "") + ");\r\n");
                        }
                        if (ai.getXMLName().equals("name"))
                            bw.write("		element.removeAttribute(\"name\");\r\n");
                    }
                    if (ii.getOai() != null) {
                        bw.write("		setProperties(context, \"" + ii.getOai().getSpringName() + "\", element, mcm);\r\n");
                    }
                    if (ii.getTci() != null)
                        bw.write("		setProperty(context, mcm, \"" + ii.getTci().getPropertyName() + "\", element.getTextContent());\r\n");
                    else
                        bw.write("		parseChildren(element, context, mcm, globalParser);\r\n");
                    for (ChildElementInfo cei : ii.getCeis()) if (cei.isList() && cei.isRequired()) {
                        bw.write("		if (!isPropertySet(mcm, \"" + cei.getPropertyName() + "\"))\r\n");
                        bw.write("			throw new RuntimeException(\"Property '" + cei.getPropertyName() + "' is required, but none was defined (empty list).\");\r\n");
                    }
                    bw.write("" + "		return mcm;\r\n");
                    bw.write("	}\r\n");
                    bw.write("	@Override\r\n" + "	protected void handleChildObject(Element ele, ParserContext context, MutableBeanMetadata mcm, Class<?> clazz, Object child) {\r\n");
                    for (ChildElementInfo cei : ii.getCeis()) {
                        bw.write("		if (" + cei.getTypeDeclaration().getQualifiedName() + ".class.isAssignableFrom(clazz)) {\r\n");
                        if (cei.isList())
                            bw.write("			appendToListProperty(context, mcm, \"" + cei.getPropertyName() + "\"" + ", child);\r\n");
                        else
                            bw.write("			setProperty(context, mcm, \"" + cei.getPropertyName() + "\"" + ", child);\r\n");
                        bw.write("		} else \r\n");
                    }
                    bw.write("		{\r\n" + "			throw new RuntimeException(\"Unknown child class \\\"\" + clazz + \"\\\".\");\r\n" + "		}\r\n");
                    bw.write("	}\r\n");
                    bw.write("}\r\n" + "");
                } finally {
                    bw.close();
                }
            } catch (FilerException e) {
                if (e.getMessage().contains("Source file already created"))
                    return;
                throw e;
            }
        }
    }
}
Also used : AttributeInfo(com.predic8.membrane.annot.model.AttributeInfo) MainInfo(com.predic8.membrane.annot.model.MainInfo) ElementInfo(com.predic8.membrane.annot.model.ElementInfo) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) FileObject(javax.tools.FileObject) FilerException(javax.annotation.processing.FilerException) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) BufferedWriter(java.io.BufferedWriter)

Example 2 with ChildElementInfo

use of com.predic8.membrane.annot.model.ChildElementInfo in project service-proxy by membrane.

the class HelpReference method handle.

private void handle(Model m, MainInfo main, ElementInfo ei) throws XMLStreamException {
    xew.writeStartElement("element");
    xew.writeAttribute("name", ei.getAnnotation().name());
    if (ei.getAnnotation().mixed())
        xew.writeAttribute("mixed", "true");
    xew.writeAttribute("topLevel", Boolean.toString(ei.getAnnotation().topLevel()));
    xew.writeAttribute("id", ei.getId());
    if (!ei.getAnnotation().topLevel()) {
        String primaryParentId = getPrimaryParentId(m, main, ei);
        if (primaryParentId != null)
            xew.writeAttribute("primaryParentId", primaryParentId);
    }
    handleDoc(ei);
    List<AttributeInfo> ais = ei.getAis();
    Collections.sort(ais, new Comparator<AttributeInfo>() {

        @Override
        public int compare(AttributeInfo o1, AttributeInfo o2) {
            return o1.getXMLName().compareTo(o2.getXMLName());
        }
    });
    OtherAttributesInfo oai = ei.getOai();
    if (ais.size() > 0 && ais.get(0).getXMLName().equals("id"))
        ais.remove(0);
    if (ais.size() > 0 || oai != null) {
        xew.writeStartElement("attributes");
        for (AttributeInfo ai : ais) handle(ai);
        if (oai != null) {
            xew.writeStartElement("any");
            handleDoc(oai);
            xew.writeEndElement();
        }
        xew.writeEndElement();
    }
    List<ChildElementInfo> ceis = ei.getCeis();
    if (ceis.size() > 0) {
        xew.writeStartElement("children");
        for (ChildElementInfo cei : ceis) handle(m, main, cei);
        xew.writeEndElement();
    }
    xew.writeEndElement();
}
Also used : AttributeInfo(com.predic8.membrane.annot.model.AttributeInfo) OtherAttributesInfo(com.predic8.membrane.annot.model.OtherAttributesInfo) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo)

Example 3 with ChildElementInfo

use of com.predic8.membrane.annot.model.ChildElementInfo in project service-proxy by membrane.

the class HelpReference method getPrimaryParentId.

private String getPrimaryParentId(Model m, MainInfo mi, ElementInfo ei) {
    // choose a random parent (TODO: choose a better one)
    Set<ElementInfo> possibleParents = new HashSet<ElementInfo>();
    for (Map.Entry<TypeElement, ChildElementDeclarationInfo> e : mi.getChildElementDeclarations().entrySet()) if (e.getValue().getElementInfo().contains(ei)) {
        for (ChildElementInfo usedBy : e.getValue().getUsedBy()) {
            ElementInfo e2 = mi.getElements().get(usedBy.getEi().getElement());
            if (e2 != null)
                possibleParents.add(e2);
        }
    }
    for (ElementInfo ei2 : possibleParents) if (ei2.getAnnotation().topLevel())
        return ei2.getId();
    possibleParents.remove(ei);
    if (possibleParents.size() > 0)
        return possibleParents.iterator().next().getId();
    return null;
}
Also used : ElementInfo(com.predic8.membrane.annot.model.ElementInfo) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) TypeElement(javax.lang.model.element.TypeElement) Map(java.util.Map) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) ChildElementDeclarationInfo(com.predic8.membrane.annot.model.ChildElementDeclarationInfo) HashSet(java.util.HashSet)

Example 4 with ChildElementInfo

use of com.predic8.membrane.annot.model.ChildElementInfo in project service-proxy by membrane.

the class Parsers method writeParsers.

public void writeParsers(Model m) throws IOException {
    for (MainInfo main : m.getMains()) {
        for (ElementInfo ii : main.getIis()) {
            List<Element> sources = new ArrayList<Element>();
            sources.add(main.getElement());
            sources.add(ii.getElement());
            String interceptorClassName = ii.getElement().getQualifiedName().toString();
            try {
                FileObject o = processingEnv.getFiler().createSourceFile(main.getAnnotation().outputPackage() + "." + ii.getParserClassSimpleName(), sources.toArray(new Element[0]));
                BufferedWriter bw = new BufferedWriter(o.openWriter());
                try {
                    bw.write("/* Copyright 2012 predic8 GmbH, www.predic8.com\r\n" + "\r\n" + "   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n" + "   you may not use this file except in compliance with the License.\r\n" + "   You may obtain a copy of the License at\r\n" + "\r\n" + "   http://www.apache.org/licenses/LICENSE-2.0\r\n" + "\r\n" + "   Unless required by applicable law or agreed to in writing, software\r\n" + "   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n" + "   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n" + "   See the License for the specific language governing permissions and\r\n" + "   limitations under the License. */\r\n" + "\r\n" + "package " + main.getAnnotation().outputPackage() + ";\r\n" + "\r\n" + "import org.w3c.dom.Element;\r\n" + "import org.springframework.beans.factory.xml.ParserContext;\r\n" + "import org.springframework.beans.factory.support.BeanDefinitionBuilder;\r\n");
                    if (!main.getAnnotation().outputPackage().equals("com.predic8.membrane.core.config.spring"))
                        bw.write("import com.predic8.membrane.core.config.spring.*;\r\n");
                    bw.write("\r\n" + "/**\r\n" + "  * Automatically generated by " + Parsers.class.getName() + ".\r\n" + "  */\r\n" + "public class " + ii.getParserClassSimpleName() + " extends AbstractParser {\r\n" + "\r\n" + "	protected Class<?> getBeanClass(org.w3c.dom.Element element) {\r\n" + "		return " + interceptorClassName + ".class;\r\n" + "	}\r\n");
                    bw.write("	@Override\r\n" + "	protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {\r\n");
                    if (ii.isHasIdField())
                        bw.write("		setPropertyIfSet(\"id\", element, builder);\r\n");
                    bw.write("		setIdIfNeeded(element, parserContext, \"" + ii.getAnnotation().name() + "\");\r\n");
                    for (AttributeInfo ai : ii.getAis()) {
                        if (ai.getXMLName().equals("id"))
                            continue;
                        if (ai.isBeanReference(processingEnv.getTypeUtils())) {
                            if (!ai.isRequired())
                                bw.write("		if (element.hasAttribute(\"" + ai.getXMLName() + "\"))\r\n");
                            bw.write("		builder.addPropertyReference(\"" + ai.getSpringName() + "\", element.getAttribute(\"" + ai.getXMLName() + "\"));\r\n");
                        } else {
                            bw.write("		setProperty" + (ai.isRequired() ? "" : "IfSet") + "(\"" + ai.getXMLName() + "\", \"" + ai.getSpringName() + "\", element, builder" + (ai.isEnum(processingEnv.getTypeUtils()) ? ", true" : "") + ");\r\n");
                        }
                        if (ai.getXMLName().equals("name"))
                            bw.write("		element.removeAttribute(\"name\");\r\n");
                    }
                    if (ii.getOai() != null) {
                        bw.write("		setProperties(\"" + ii.getOai().getSpringName() + "\", element, builder);\r\n");
                    }
                    for (ChildElementInfo cei : ii.getCeis()) if (cei.isList())
                        bw.write("		builder.addPropertyValue(\"" + cei.getPropertyName() + "\", new java.util.ArrayList<Object>());\r\n");
                    if (ii.getTci() != null)
                        bw.write("		builder.addPropertyValue(\"" + ii.getTci().getPropertyName() + "\", element.getTextContent());\r\n");
                    else
                        bw.write("		parseChildren(element, parserContext, builder);\r\n");
                    for (ChildElementInfo cei : ii.getCeis()) if (cei.isList() && cei.isRequired()) {
                        bw.write("		if (builder.getBeanDefinition().getPropertyValues().getPropertyValue(\"" + cei.getPropertyName() + "[0]\") == null)\r\n");
                        bw.write("			throw new RuntimeException(\"Property '" + cei.getPropertyName() + "' is required, but none was defined (empty list).\");\r\n");
                    }
                    bw.write("	}\r\n" + "");
                    bw.write("@Override\r\n" + "protected void handleChildObject(Element ele, ParserContext parserContext, BeanDefinitionBuilder builder, Class<?> clazz, Object child) {\r\n");
                    for (ChildElementInfo cei : ii.getCeis()) {
                        bw.write("	if (" + cei.getTypeDeclaration().getQualifiedName() + ".class.isAssignableFrom(clazz)) {\r\n" + "		setProperty(builder, \"" + cei.getPropertyName() + "\"" + (cei.isList() ? "+\"[\"+ incrementCounter(builder, \"" + cei.getPropertyName() + "\") + \"]\" " : "") + ", child);\r\n" + "	} else \r\n");
                    }
                    bw.write("	{\r\n" + "		throw new RuntimeException(\"Unknown child class \\\"\" + clazz + \"\\\".\");\r\n" + "	}\r\n");
                    bw.write("}\r\n");
                    bw.write("}\r\n" + "");
                } finally {
                    bw.close();
                }
            } catch (FilerException e) {
                if (e.getMessage().contains("Source file already created"))
                    return;
                throw e;
            }
        }
    }
}
Also used : AttributeInfo(com.predic8.membrane.annot.model.AttributeInfo) MainInfo(com.predic8.membrane.annot.model.MainInfo) ElementInfo(com.predic8.membrane.annot.model.ElementInfo) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) FileObject(javax.tools.FileObject) FilerException(javax.annotation.processing.FilerException) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) BufferedWriter(java.io.BufferedWriter)

Example 5 with ChildElementInfo

use of com.predic8.membrane.annot.model.ChildElementInfo in project service-proxy by membrane.

the class SpringConfigurationXSDGeneratingAnnotationProcessor method scan.

private void scan(Model m, MainInfo main, ElementInfo ii, TypeElement te) {
    TypeMirror superclass = te.getSuperclass();
    if (superclass instanceof DeclaredType)
        scan(m, main, ii, (TypeElement) ((DeclaredType) superclass).asElement());
    for (Element e2 : te.getEnclosedElements()) {
        MCAttribute a = e2.getAnnotation(MCAttribute.class);
        if (a != null) {
            AttributeInfo ai = new AttributeInfo();
            ai.setAnnotation(a);
            ai.setE((ExecutableElement) e2);
            ai.setRequired(isRequired(e2));
            ii.getAis().add(ai);
            ii.setHasIdField(ii.isHasIdField() || ai.getXMLName().equals("id"));
        }
        MCOtherAttributes d = e2.getAnnotation(MCOtherAttributes.class);
        if (d != null) {
            OtherAttributesInfo oai = new OtherAttributesInfo();
            oai.setOtherAttributesSetter((ExecutableElement) e2);
            ii.setOai(oai);
        }
        MCChildElement b = e2.getAnnotation(MCChildElement.class);
        if (b != null) {
            ChildElementInfo cei = new ChildElementInfo();
            cei.setEi(ii);
            cei.setAnnotation(b);
            cei.setE((ExecutableElement) e2);
            List<? extends VariableElement> parameters = cei.getE().getParameters();
            if (parameters.size() == 0)
                throw new ProcessingException("Setter must have exactly one parameter.", e2);
            TypeMirror setterArgType = parameters.get(0).asType();
            if (!(setterArgType instanceof DeclaredType))
                throw new ProcessingException("Setter argument must be of an @MCElement-annotated type.", parameters.get(0));
            cei.setTypeDeclaration((TypeElement) ((DeclaredType) setterArgType).asElement());
            cei.setPropertyName(AnnotUtils.dejavaify(e2.getSimpleName().toString().substring(3)));
            cei.setRequired(isRequired(e2));
            ii.getCeis().add(cei);
            // unwrap "java.util.List<?>" and "java.util.Collection<?>"
            if (cei.getTypeDeclaration().getQualifiedName().toString().startsWith("java.util.List") || cei.getTypeDeclaration().getQualifiedName().toString().startsWith("java.util.Collection")) {
                cei.setTypeDeclaration((TypeElement) ((DeclaredType) ((DeclaredType) setterArgType).getTypeArguments().get(0)).asElement());
                cei.setList(true);
            }
            ChildElementDeclarationInfo cedi;
            if (!main.getChildElementDeclarations().containsKey(cei.getTypeDeclaration())) {
                cedi = new ChildElementDeclarationInfo();
                cedi.setTarget(cei.getTypeDeclaration());
                cedi.setRaiseErrorWhenNoSpecimen(!cei.getAnnotation().allowForeign());
                main.getChildElementDeclarations().put(cei.getTypeDeclaration(), cedi);
            } else {
                cedi = main.getChildElementDeclarations().get(cei.getTypeDeclaration());
                cedi.setRaiseErrorWhenNoSpecimen(cedi.isRaiseErrorWhenNoSpecimen() || !cei.getAnnotation().allowForeign());
            }
            cedi.addUsedBy(cei);
        }
        MCTextContent c = e2.getAnnotation(MCTextContent.class);
        if (c != null) {
            TextContentInfo tci = new TextContentInfo();
            tci.setPropertyName(AnnotUtils.dejavaify(e2.getSimpleName().toString().substring(3)));
            ii.setTci(tci);
        }
    }
    HashSet<Integer> childOrders = new HashSet<Integer>();
    for (ChildElementInfo cei : ii.getCeis()) {
        if (!childOrders.add(cei.getAnnotation().order()))
            throw new ProcessingException("@MCChildElement(order=...) must be unique.", cei.getE());
    }
    Collections.sort(ii.getCeis());
}
Also used : OtherAttributesInfo(com.predic8.membrane.annot.model.OtherAttributesInfo) TextContentInfo(com.predic8.membrane.annot.model.TextContentInfo) ChildElementInfo(com.predic8.membrane.annot.model.ChildElementInfo) AttributeInfo(com.predic8.membrane.annot.model.AttributeInfo) TypeMirror(javax.lang.model.type.TypeMirror) ChildElementDeclarationInfo(com.predic8.membrane.annot.model.ChildElementDeclarationInfo) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

ChildElementInfo (com.predic8.membrane.annot.model.ChildElementInfo)9 ElementInfo (com.predic8.membrane.annot.model.ElementInfo)7 AttributeInfo (com.predic8.membrane.annot.model.AttributeInfo)5 TypeElement (javax.lang.model.element.TypeElement)5 ChildElementDeclarationInfo (com.predic8.membrane.annot.model.ChildElementDeclarationInfo)4 MainInfo (com.predic8.membrane.annot.model.MainInfo)4 BufferedWriter (java.io.BufferedWriter)4 ArrayList (java.util.ArrayList)4 FilerException (javax.annotation.processing.FilerException)4 Element (javax.lang.model.element.Element)4 FileObject (javax.tools.FileObject)4 OtherAttributesInfo (com.predic8.membrane.annot.model.OtherAttributesInfo)2 TextContentInfo (com.predic8.membrane.annot.model.TextContentInfo)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 TreeSet (java.util.TreeSet)1 DeclaredType (javax.lang.model.type.DeclaredType)1 TypeMirror (javax.lang.model.type.TypeMirror)1