Search in sources :

Example 71 with JCodeModel

use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.

the class JAXBHelper method generateClassesFromXmlSchemas.

private static List<JDefinedClass> generateClassesFromXmlSchemas(String pack, JCodeModel codeModel, File schemaFile) throws GenerationException {
    try {
        ArrayList<JDefinedClass> classList = new ArrayList<JDefinedClass>();
        ArrayList<String> argList = new ArrayList<>();
        argList.add("-mark-generated");
        argList.add("-p");
        argList.add(pack);
        argList.add(schemaFile.getAbsolutePath());
        String[] args = argList.toArray(new String[argList.size()]);
        final Options opt = new Options();
        opt.setSchemaLanguage(Language.XMLSCHEMA);
        opt.parseArguments(args);
        ErrorReceiver receiver = new ErrorReceiverFilter() {

            @Override
            public void info(SAXParseException exception) {
                if (opt.verbose)
                    super.info(exception);
            }

            @Override
            public void warning(SAXParseException exception) {
                if (!opt.quiet)
                    super.warning(exception);
            }
        };
        Model model = ModelLoader.load(opt, codeModel, receiver);
        Outline outline = model.generateCode(opt, receiver);
        for (ClassOutline co : outline.getClasses()) {
            JDefinedClass cl = co.implClass;
            if (cl.outer() == null) {
                classList.add(cl);
            }
        }
        return classList;
    } catch (Exception e) {
        throw new GenerationException(e);
    }
}
Also used : Options(com.sun.tools.xjc.Options) JDefinedClass(com.sun.codemodel.JDefinedClass) ArrayList(java.util.ArrayList) ClassOutline(com.sun.tools.xjc.outline.ClassOutline) Outline(com.sun.tools.xjc.outline.Outline) ErrorReceiver(com.sun.tools.xjc.ErrorReceiver) IOException(java.io.IOException) GenerationException(org.raml.jaxrs.generator.GenerationException) SAXParseException(org.xml.sax.SAXParseException) ClassOutline(com.sun.tools.xjc.outline.ClassOutline) ErrorReceiverFilter(com.sun.tools.xjc.util.ErrorReceiverFilter) SAXParseException(org.xml.sax.SAXParseException) Model(com.sun.tools.xjc.model.Model) JCodeModel(com.sun.codemodel.JCodeModel) GenerationException(org.raml.jaxrs.generator.GenerationException)

Example 72 with JCodeModel

use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.

the class SchemaTypeFactory method createXmlType.

public static TypeGenerator createXmlType(CurrentBuild currentBuild, GType type) {
    File schemaFile = null;
    try {
        schemaFile = JAXBHelper.saveSchema(type.schema(), currentBuild.getSchemaRepository());
        final JCodeModel codeModel = new JCodeModel();
        Map<String, JClass> generated = JAXBHelper.generateClassesFromXmlSchemas(currentBuild.getModelPackage(), schemaFile, codeModel);
        XmlSchemaTypeGenerator gen = new XmlSchemaTypeGenerator(type, codeModel, currentBuild.getModelPackage(), generated.values().iterator().next());
        type.setJavaType(gen.getGeneratedJavaType());
        currentBuild.newGenerator(type.name(), gen);
        return gen;
    } catch (Exception e) {
        throw new GenerationException(e);
    }
}
Also used : JClass(com.sun.codemodel.JClass) File(java.io.File) JCodeModel(com.sun.codemodel.JCodeModel)

Example 73 with JCodeModel

use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.

the class JsonSchemaTypeGenerator method output.

@Override
public void output(CodeContainer<JCodeModel> container, BuildPhase buildPhase) throws IOException {
    GenerationConfig config = build.getJsonMapperConfig();
    final SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), new SchemaStore()), new SchemaGenerator());
    final JCodeModel codeModel = new JCodeModel();
    File schemaFile = File.createTempFile("schema", "json", build.getSchemaRepository());
    Files.write(schema, schemaFile, Charset.defaultCharset());
    try {
        mapper.generate(codeModel, name.simpleName(), pack, schemaFile.toURL());
    } catch (IOException e) {
        throw new GenerationException(e);
    }
    container.into(codeModel);
}
Also used : RuleFactory(org.jsonschema2pojo.rules.RuleFactory) IOException(java.io.IOException) JCodeModel(com.sun.codemodel.JCodeModel) File(java.io.File)

Example 74 with JCodeModel

use of com.sun.codemodel.JCodeModel in project rest.li by linkedin.

the class RestRequestBuilderGenerator method run.

/**
 * @param generateLowercasePath true, files are generated with a lower case path; false, files are generated as spec specifies.
 */
public static GeneratorResult run(String resolverPath, String defaultPackage, String rootPath, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, RestliVersion deprecatedByVersion, String targetDirectoryPath, String[] sources, boolean generateLowercasePath) throws IOException {
    final RestSpecParser parser = new RestSpecParser();
    final JavaRequestBuilderGenerator generator = new JavaRequestBuilderGenerator(resolverPath, defaultPackage, generateDataTemplates, version, deprecatedByVersion, rootPath);
    final ClassLoader classLoader = JavaCodeUtil.classLoaderFromResolverPath(resolverPath);
    final RestSpecParser.ParseResult parseResult = parser.parseSources(sources);
    final StringBuilder message = new StringBuilder();
    for (CodeUtil.Pair<ResourceSchema, File> pair : parseResult.getSchemaAndFiles()) {
        ResourceSchema resourceSchema = pair.first;
        // Skip unstructured data resources for client generation
        if (resourceSchema == null || ResourceEntityType.UNSTRUCTURED_DATA == resourceSchema.getEntityType()) {
            continue;
        }
        try {
            final JDefinedClass clazz = generator.generate(resourceSchema, pair.second, rootPath);
        } catch (Exception e) {
            _log.error("Failed to generate request builders for schema: " + resourceSchema.getName(), e);
            message.append(e.getMessage()).append("\n");
        }
    }
    if (message.length() > 0) {
        throw new IOException(message.toString());
    }
    final DataTemplatePersistentClassChecker dataTemplateChecker = new DataTemplatePersistentClassChecker(generateImported, generator.getSpecGenerator(), generator.getJavaDataTemplateGenerator(), Collections.<File>emptySet());
    final JavaCodeUtil.PersistentClassChecker checker = new JavaCodeUtil.PersistentClassChecker() {

        @Override
        public boolean isPersistent(JDefinedClass clazz) {
            if (generateDataTemplates || generator.isGeneratedArrayClass(clazz)) {
                try {
                    Class.forName(clazz.fullName(), false, classLoader);
                } catch (ClassNotFoundException e) {
                    return true;
                }
            }
            return dataTemplateChecker.isPersistent(clazz);
        }
    };
    final JCodeModel requestBuilderCodeModel = generator.getCodeModel();
    final JCodeModel dataTemplateCodeModel = generator.getJavaDataTemplateGenerator().getCodeModel();
    final File targetDirectory = new File(targetDirectoryPath);
    final List<File> targetFiles = JavaCodeUtil.targetFiles(targetDirectory, requestBuilderCodeModel, classLoader, checker, generateLowercasePath);
    targetFiles.addAll(JavaCodeUtil.targetFiles(targetDirectory, dataTemplateCodeModel, classLoader, checker, generateLowercasePath));
    final List<File> modifiedFiles;
    if (FileUtil.upToDate(parseResult.getSourceFiles(), targetFiles)) {
        modifiedFiles = Collections.emptyList();
        _log.info("Target files are up-to-date: " + targetFiles);
    } else {
        modifiedFiles = targetFiles;
        _log.info("Generating " + targetFiles.size() + " files");
        _log.debug("Files: " + targetFiles);
        requestBuilderCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
        dataTemplateCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
    }
    return new DefaultGeneratorResult(parseResult.getSourceFiles(), targetFiles, modifiedFiles);
}
Also used : ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) CaseSensitiveFileCodeWriter(com.linkedin.pegasus.generator.CaseSensitiveFileCodeWriter) JDefinedClass(com.sun.codemodel.JDefinedClass) IOException(java.io.IOException) JCodeModel(com.sun.codemodel.JCodeModel) IOException(java.io.IOException) DataTemplatePersistentClassChecker(com.linkedin.pegasus.generator.DataTemplatePersistentClassChecker) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) CodeUtil(com.linkedin.pegasus.generator.CodeUtil) DefaultGeneratorResult(com.linkedin.pegasus.generator.DefaultGeneratorResult) DataTemplatePersistentClassChecker(com.linkedin.pegasus.generator.DataTemplatePersistentClassChecker) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) File(java.io.File)

Example 75 with JCodeModel

use of com.sun.codemodel.JCodeModel in project scout.rt by eclipse.

the class JaxWsAnnotationProcessor method generateEntryPoint.

/**
 * Generates the entry point and associated artifacts for the given definition.
 */
protected void generateEntryPoint(final EntryPointDefinition entryPointDefinition, final RoundEnvironment roundEnv) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
    final JCodeModel model = new JCodeModel();
    // Create EntryPoint class.
    final TypeElement _endpointInterface = entryPointDefinition.getEndpointInterface();
    final JClass endpointInterface = model.ref(_endpointInterface.getQualifiedName().toString());
    final JDefinedClass entryPoint = model._class(entryPointDefinition.getEntryPointQualifiedName())._implements(endpointInterface);
    // Add annotations to the EntryPoint.
    addAnnotations(model, entryPoint, entryPointDefinition, roundEnv);
    // Create handler chain.
    final HandlerChain _handlerChainAnnotation = _endpointInterface.getAnnotation(HandlerChain.class);
    if (_handlerChainAnnotation != null) {
        m_logger.info("Handler file not generated because provided as binding file [file={}, entryPoint={}, endpointInterface={}]", _handlerChainAnnotation.file(), entryPointDefinition.getEntryPointQualifiedName(), entryPointDefinition.getEndpointInterfaceQualifiedName());
    } else if (!entryPointDefinition.getHandlerChain().isEmpty() || entryPointDefinition.isAuthenticationEnabled()) {
        entryPoint.annotate(HandlerChain.class).param("file", new HandlerArtifactProcessor().generateHandlerArtifacts(entryPoint, entryPointDefinition, processingEnv, m_logger));
    }
    // Add JavaDoc to the EntryPoint.
    AptUtil.addJavaDoc(entryPoint, createJavaDocForEntryPoint(entryPointDefinition));
    // Inject WebServiceContext
    final JFieldVar webServiceContext = entryPoint.field(JMod.PROTECTED, WebServiceContext.class, WEBSERVICE_CONTEXT_FIELD_NAME);
    webServiceContext.annotate(Resource.class);
    // Overwrite all methods declared on the PortType interface.
    for (final Element _element : _endpointInterface.getEnclosedElements()) {
        if (!(ElementKind.METHOD.equals(_element.getKind()))) {
            continue;
        }
        final ExecutableElement _method = (ExecutableElement) _element;
        final String methodName = _method.getSimpleName().toString();
        final JType returnType = JTypeParser.parseType(model, _method.getReturnType());
        // Create the method.
        final JMethod method = entryPoint.method(JMod.PUBLIC, returnType, methodName);
        method.annotate(Override.class);
        // Add the method parameters.
        for (final VariableElement _param : _method.getParameters()) {
            method.param(JMod.FINAL, JTypeParser.parseType(model, _param.asType()), _param.getSimpleName().toString());
        }
        // Add exception throw clauses.
        final List<JClass> throwTypes = new ArrayList<>();
        for (final TypeMirror _throwType : _method.getThrownTypes()) {
            final JClass throwType = model.ref(_throwType.toString());
            throwTypes.add(throwType);
            method._throws(throwType);
        }
        // Create the method implementation.
        addEntryPointMethodImplementation(model, webServiceContext, method, throwTypes, TypeKind.VOID.equals(_method.getReturnType().getKind()), _endpointInterface.getQualifiedName().toString());
    }
    // Create the method to handle undeclared errors.
    addHandleUndeclaredFaultMethod(model, entryPoint);
    // Create the method to lookup the RunContext.
    addLookupRunContextMethod(model, entryPoint, webServiceContext);
    // Build and persist this compilation unit.
    AptUtil.buildAndPersist(model, processingEnv.getFiler());
    m_logger.info("Entry point successfully generated. [entryPoint={}, endpointInterface={}, entryPointDefinition={}]", entryPoint.fullName(), endpointInterface.fullName(), entryPointDefinition.getQualifiedName());
}
Also used : JDefinedClass(com.sun.codemodel.JDefinedClass) TypeElement(javax.lang.model.element.TypeElement) JClass(com.sun.codemodel.JClass) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) JCodeModel(com.sun.codemodel.JCodeModel) HandlerChain(javax.jws.HandlerChain) JFieldVar(com.sun.codemodel.JFieldVar) TypeMirror(javax.lang.model.type.TypeMirror) HandlerArtifactProcessor(org.eclipse.scout.jaxws.apt.internal.HandlerArtifactProcessor) JMethod(com.sun.codemodel.JMethod) JType(com.sun.codemodel.JType)

Aggregations

JCodeModel (com.sun.codemodel.JCodeModel)77 Test (org.junit.Test)59 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)52 JPackage (com.sun.codemodel.JPackage)47 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)45 JType (com.sun.codemodel.JType)41 JDefinedClass (com.sun.codemodel.JDefinedClass)15 JClass (com.sun.codemodel.JClass)12 Schema (org.jsonschema2pojo.Schema)11 RuleFactory (org.jsonschema2pojo.rules.RuleFactory)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 TextNode (com.fasterxml.jackson.databind.node.TextNode)6 File (java.io.File)6 IOException (java.io.IOException)5 JBlock (com.sun.codemodel.JBlock)4 JCatchBlock (com.sun.codemodel.JCatchBlock)4 JMethod (com.sun.codemodel.JMethod)4 JTryBlock (com.sun.codemodel.JTryBlock)4 JVar (com.sun.codemodel.JVar)4 URL (java.net.URL)4