Search in sources :

Example 56 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project kie-wb-common by kiegroup.

the class JavaRoasterModelDriver method parseAnnotationWithValuePair.

public Pair<AnnotationSource<JavaClassSource>, List<DriverError>> parseAnnotationWithValuePair(String annotationClassName, ElementType target, String valuePairName, String literalValue) {
    List<DriverError> syntaxErrors = new ArrayList<DriverError>();
    String annotationStr = "@" + annotationClassName + "(" + valuePairName + "=" + literalValue + " )";
    String stub;
    AnnotationSource<JavaClassSource> annotation = null;
    if (ElementType.TYPE.equals(target)) {
        stub = annotationStr + " public class Stub { }";
    } else {
        stub = "public class Stub { " + annotationStr + " int dummy; }";
    }
    JavaClassSource temp = (JavaClassSource) Roaster.parse(JavaClass.class, stub);
    if (temp.getSyntaxErrors() != null && temp.getSyntaxErrors().size() > 0) {
        for (org.jboss.forge.roaster.model.SyntaxError syntaxError : temp.getSyntaxErrors()) {
            syntaxErrors.add(new DriverError(syntaxError.getDescription(), syntaxError.getLine(), syntaxError.getColumn()));
        }
    } else if (ElementType.TYPE.equals(target)) {
        annotation = temp.getAnnotation(annotationClassName);
    } else {
        annotation = temp.getField("dummy").getAnnotation(annotationClassName);
    }
    if (annotation == null) {
        syntaxErrors.add(new DriverError("Annotation value pair could not be parsed."));
    }
    return new Pair<>(annotation, syntaxErrors);
}
Also used : JavaClass(org.jboss.forge.roaster.model.JavaClass) ArrayList(java.util.ArrayList) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) SyntaxError(org.jboss.forge.roaster.model.SyntaxError) DriverError(org.kie.workbench.common.services.datamodeller.driver.model.DriverError) Pair(org.uberfire.commons.data.Pair)

Example 57 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project kie-wb-common by kiegroup.

the class JavaRoasterModelDriver method updateConstructors.

public void updateConstructors(JavaClassSource javaClassSource, DataObject dataObject, List<MethodSource<JavaClassSource>> allFieldsConstructorCandidates, List<MethodSource<JavaClassSource>> keyFieldsConstructorCandidates, List<MethodSource<JavaClassSource>> positionFieldsConstructorCandidates, ClassTypeResolver classTypeResolver) throws Exception {
    GenerationContext generationContext = new GenerationContext(null);
    GenerationEngine engine = GenerationEngine.getInstance();
    GenerationTools genTools = new GenerationTools();
    JavaRoasterModelDriver modelDriver = new JavaRoasterModelDriver();
    boolean needsAllFieldsConstructor;
    boolean needsKeyFieldsConstructor;
    boolean needsPositionFieldsConstructor;
    boolean needsEmptyConstructor;
    String defaultConstructorSource;
    String allFieldsConstructorSource;
    String keyFieldsConstructorSource;
    String positionFieldsConstructorSource;
    String equalsMethodSource;
    String hashCodeMethodSource;
    // check if the candidate methods has exactly the same body of the generated by the data modeller.
    List<MethodSource<JavaClassSource>> currentAllFieldsConstructors = modelDriver.filterGeneratedConstructors(allFieldsConstructorCandidates);
    List<MethodSource<JavaClassSource>> currentKeyFieldsConstructors = modelDriver.filterGeneratedConstructors(keyFieldsConstructorCandidates);
    List<MethodSource<JavaClassSource>> currentPositionFieldsConstructors = modelDriver.filterGeneratedConstructors(positionFieldsConstructorCandidates);
    if (logger.isDebugEnabled()) {
        logger.debug("allFieldsConstructorCandidates candidates: " + allFieldsConstructorCandidates.size());
        logger.debug(allFieldsConstructorCandidates.size() > 0 ? allFieldsConstructorCandidates.get(0).toString() : "");
        logger.debug("\n\n");
        logger.debug("currentAllFieldsConstructors: " + currentAllFieldsConstructors.size());
        logger.debug(currentAllFieldsConstructors.size() > 0 ? currentAllFieldsConstructors.get(0).toString() : "");
        logger.debug("\n\n");
        logger.debug("KeyFieldsConstructorCandidates: " + keyFieldsConstructorCandidates.size());
        logger.debug(keyFieldsConstructorCandidates.size() > 0 ? keyFieldsConstructorCandidates.get(0).toString() : "");
        logger.debug("\n\n");
        logger.debug("currentKeyFieldsConstructors: " + currentKeyFieldsConstructors.size());
        logger.debug(currentKeyFieldsConstructors.size() > 0 ? currentKeyFieldsConstructors.get(0).toString() : "");
        logger.debug("\n\n");
        logger.debug("positionFieldsConstructorCandidates: " + positionFieldsConstructorCandidates.size());
        logger.debug(positionFieldsConstructorCandidates.size() > 0 ? positionFieldsConstructorCandidates.get(0).toString() : "");
        logger.debug("\n\n");
        logger.debug("currentPositionFieldsConstructors: " + currentPositionFieldsConstructors.size());
        logger.debug(currentPositionFieldsConstructors.size() > 0 ? currentPositionFieldsConstructors.get(0).toString() : "");
        logger.debug("\n\n");
    }
    // delete current data modeller generated all fields, key fields, and position fields constructors if there are any.
    for (MethodSource<JavaClassSource> constructor : currentAllFieldsConstructors) {
        javaClassSource.removeMethod(constructor);
    }
    for (MethodSource<JavaClassSource> constructor : currentKeyFieldsConstructors) {
        javaClassSource.removeMethod(constructor);
    }
    for (MethodSource<JavaClassSource> constructor : currentPositionFieldsConstructors) {
        javaClassSource.removeMethod(constructor);
    }
    // calculate the file order for the fields.
    List<FieldSource<JavaClassSource>> fields = javaClassSource.getFields();
    if (fields != null && fields.size() > 0) {
        int fileOrder = 0;
        for (FieldSource<JavaClassSource> field : fields) {
            ObjectPropertyImpl objectProperty = (ObjectPropertyImpl) dataObject.getProperty(field.getName());
            if (objectProperty != null) {
                objectProperty.setFileOrder(fileOrder);
            }
            fileOrder++;
        }
    }
    // get the sorted list of all fields, position annotated and key annotated fields. These lists will be used
    // to identify collisions with client provided constructors.
    List<ObjectProperty> allFields = DataModelUtils.sortByFileOrder(DataModelUtils.filterAssignableFields(dataObject));
    List<ObjectProperty> positionFields = DataModelUtils.sortByPosition(DataModelUtils.filterPositionFields(dataObject));
    List<ObjectProperty> keyFields = DataModelUtils.sortByFileOrder(DataModelUtils.filterKeyFields(dataObject));
    // we always wants to generate the default constructor.
    needsEmptyConstructor = true;
    needsAllFieldsConstructor = allFields.size() > 0;
    needsPositionFieldsConstructor = positionFields.size() > 0 && !DataModelUtils.equalsByFieldName(allFields, positionFields) && !DataModelUtils.equalsByFieldType(allFields, positionFields);
    needsKeyFieldsConstructor = keyFields.size() > 0 && !DataModelUtils.equalsByFieldName(allFields, keyFields) && !DataModelUtils.equalsByFieldType(allFields, keyFields) && !DataModelUtils.equalsByFieldName(positionFields, keyFields) && !DataModelUtils.equalsByFieldType(positionFields, keyFields);
    List<MethodSource<JavaClassSource>> currentConstructors = new ArrayList<MethodSource<JavaClassSource>>();
    MethodSource<JavaClassSource> currentEquals = null;
    MethodSource<JavaClassSource> currentHashCode = null;
    MethodSource<JavaClassSource> newConstructor;
    // Iterate remaining methods looking for client provided constructors, hashCode and equals methods.
    List<MethodSource<JavaClassSource>> methods = javaClassSource.getMethods();
    if (methods != null) {
        for (MethodSource<JavaClassSource> method : methods) {
            if (method.isConstructor()) {
                currentConstructors.add(method);
                if (method.getParameters() == null || method.getParameters().size() == 0) {
                    needsEmptyConstructor = false;
                }
            } else if (isEquals(method)) {
                currentEquals = method;
            } else if (isHashCode(method)) {
                currentHashCode = method;
            }
        }
    }
    // check collisions with remaining constructors first.
    needsAllFieldsConstructor = needsAllFieldsConstructor && (findMatchingConstructorsByTypes(javaClassSource, allFields, classTypeResolver).size() == 0);
    needsPositionFieldsConstructor = needsPositionFieldsConstructor && (findMatchingConstructorsByTypes(javaClassSource, positionFields, classTypeResolver).size() == 0);
    needsKeyFieldsConstructor = needsKeyFieldsConstructor && (findMatchingConstructorsByTypes(javaClassSource, keyFields, classTypeResolver).size() == 0);
    // remove current equals and hashCode methods
    if (currentEquals != null) {
        javaClassSource.removeMethod(currentEquals);
    }
    if (currentHashCode != null) {
        javaClassSource.removeMethod(currentHashCode);
    }
    if (needsEmptyConstructor) {
        defaultConstructorSource = genTools.indent(engine.generateDefaultConstructorString(generationContext, dataObject));
        newConstructor = javaClassSource.addMethod(defaultConstructorSource);
        newConstructor.setConstructor(true);
    }
    if (needsAllFieldsConstructor) {
        allFieldsConstructorSource = genTools.indent(engine.generateAllFieldsConstructorString(generationContext, dataObject));
        if (allFieldsConstructorSource != null && !allFieldsConstructorSource.trim().isEmpty()) {
            newConstructor = javaClassSource.addMethod(allFieldsConstructorSource);
            newConstructor.setConstructor(true);
        }
    }
    if (needsPositionFieldsConstructor) {
        positionFieldsConstructorSource = genTools.indent(engine.generatePositionFieldsConstructorString(generationContext, dataObject));
        if (positionFieldsConstructorSource != null && !positionFieldsConstructorSource.trim().isEmpty()) {
            newConstructor = javaClassSource.addMethod(positionFieldsConstructorSource);
            newConstructor.setConstructor(true);
        }
    }
    if (needsKeyFieldsConstructor) {
        keyFieldsConstructorSource = genTools.indent(engine.generateKeyFieldsConstructorString(generationContext, dataObject));
        if (keyFieldsConstructorSource != null && !keyFieldsConstructorSource.trim().isEmpty()) {
            newConstructor = javaClassSource.addMethod(keyFieldsConstructorSource);
            newConstructor.setConstructor(true);
        }
    }
    if (keyFields.size() > 0) {
        equalsMethodSource = genTools.indent(engine.generateEqualsString(generationContext, dataObject));
        javaClassSource.addMethod(equalsMethodSource);
        hashCodeMethodSource = genTools.indent(engine.generateHashCodeString(generationContext, dataObject));
        javaClassSource.addMethod(hashCodeMethodSource);
    }
}
Also used : GenerationContext(org.kie.workbench.common.services.datamodeller.codegen.GenerationContext) GenerationTools(org.kie.workbench.common.services.datamodeller.codegen.GenerationTools) ObjectProperty(org.kie.workbench.common.services.datamodeller.core.ObjectProperty) ArrayList(java.util.ArrayList) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ObjectPropertyImpl(org.kie.workbench.common.services.datamodeller.core.impl.ObjectPropertyImpl) GenerationEngine(org.kie.workbench.common.services.datamodeller.codegen.GenerationEngine) MethodSource(org.jboss.forge.roaster.model.source.MethodSource) FieldSource(org.jboss.forge.roaster.model.source.FieldSource)

Example 58 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project kie-wb-common by kiegroup.

the class JavaRoasterModelDriver method isGeneratedConstructor.

/**
 * @param constructor a Constructor method to check.
 * @return true, if the given constructor was generated by the data modeler.
 */
public boolean isGeneratedConstructor(MethodSource<JavaClassSource> constructor) {
    if (constructor.isAbstract() || constructor.isStatic() || constructor.isFinal()) {
        return false;
    }
    if (!constructor.isPublic()) {
        // we only generate public constructors.
        return false;
    }
    if (constructor.getAnnotations() != null && constructor.getAnnotations().size() > 0) {
        // we never add annotations to constructors
        return false;
    }
    List<ParameterSource<JavaClassSource>> parameters = constructor.getParameters();
    List<String> expectedLines = new ArrayList<String>();
    String expectedLine;
    if (parameters != null) {
        for (ParameterSource<JavaClassSource> param : parameters) {
            if (param.getAnnotations() != null && param.getAnnotations().size() > 0) {
                // we never add annotations to parameters
                return false;
            }
            // ideally we should know if the parameter is final, but Roaster don't provide that info.
            expectedLine = "this." + param.getName() + "=" + param.getName() + ";";
            expectedLines.add(expectedLine);
        }
    }
    String body = constructor.getBody();
    if (body == null || (body = body.trim()).isEmpty()) {
        return false;
    }
    try {
        BufferedReader reader = new BufferedReader(new StringReader(body));
        String line = null;
        int lineNumber = 0;
        while ((line = reader.readLine()) != null) {
            lineNumber++;
            if (lineNumber > expectedLines.size()) {
                return false;
            }
            if (!line.trim().equals(expectedLines.get(lineNumber - 1))) {
                return false;
            }
        }
        return lineNumber == expectedLines.size();
    } catch (IOException e) {
        return false;
    }
}
Also used : ParameterSource(org.jboss.forge.roaster.model.source.ParameterSource) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) IOException(java.io.IOException)

Example 59 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project camel by apache.

the class ValidateMojo method execute.

// CHECKSTYLE:OFF
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    CamelCatalog catalog = new DefaultCamelCatalog();
    // add activemq as known component
    catalog.addComponent("activemq", "org.apache.activemq.camel.component.ActiveMQComponent");
    // enable did you mean
    catalog.setSuggestionStrategy(new LuceneSuggestionStrategy());
    // enable loading other catalog versions dynamically
    catalog.setVersionManager(new MavenVersionManager());
    // enable caching
    catalog.enableCache();
    if (downloadVersion) {
        String catalogVersion = catalog.getCatalogVersion();
        String version = findCamelVersion(project);
        if (version != null && !version.equals(catalogVersion)) {
            // the project uses a different Camel version so attempt to load it
            getLog().info("Downloading Camel version: " + version);
            boolean loaded = catalog.loadVersion(version);
            if (!loaded) {
                getLog().warn("Error downloading Camel version: " + version);
            }
        }
    }
    // if using the same version as the camel-maven-plugin we must still load it
    if (catalog.getLoadedVersion() == null) {
        catalog.loadVersion(catalog.getCatalogVersion());
    }
    if (catalog.getLoadedVersion() != null) {
        getLog().info("Using Camel version: " + catalog.getLoadedVersion());
    } else {
        // force load version from the camel-maven-plugin
        getLog().info("Using Camel version: " + catalog.getCatalogVersion());
    }
    List<CamelEndpointDetails> endpoints = new ArrayList<>();
    List<CamelSimpleExpressionDetails> simpleExpressions = new ArrayList<>();
    Set<File> javaFiles = new LinkedHashSet<File>();
    Set<File> xmlFiles = new LinkedHashSet<File>();
    // find all java route builder classes
    if (includeJava) {
        List list = project.getCompileSourceRoots();
        for (Object obj : list) {
            String dir = (String) obj;
            findJavaFiles(new File(dir), javaFiles);
        }
        if (includeTest) {
            list = project.getTestCompileSourceRoots();
            for (Object obj : list) {
                String dir = (String) obj;
                findJavaFiles(new File(dir), javaFiles);
            }
        }
    }
    // find all xml routes
    if (includeXml) {
        List list = project.getResources();
        for (Object obj : list) {
            Resource dir = (Resource) obj;
            findXmlFiles(new File(dir.getDirectory()), xmlFiles);
        }
        if (includeTest) {
            list = project.getTestResources();
            for (Object obj : list) {
                Resource dir = (Resource) obj;
                findXmlFiles(new File(dir.getDirectory()), xmlFiles);
            }
        }
    }
    for (File file : javaFiles) {
        if (matchFile(file)) {
            try {
                List<CamelEndpointDetails> fileEndpoints = new ArrayList<>();
                List<CamelSimpleExpressionDetails> fileSimpleExpressions = new ArrayList<>();
                List<String> unparsable = new ArrayList<>();
                // parse the java source code and find Camel RouteBuilder classes
                String fqn = file.getPath();
                String baseDir = ".";
                JavaType out = Roaster.parse(file);
                // we should only parse java classes (not interfaces and enums etc)
                if (out != null && out instanceof JavaClassSource) {
                    JavaClassSource clazz = (JavaClassSource) out;
                    RouteBuilderParser.parseRouteBuilderEndpoints(clazz, baseDir, fqn, fileEndpoints, unparsable, includeTest);
                    RouteBuilderParser.parseRouteBuilderSimpleExpressions(clazz, baseDir, fqn, fileSimpleExpressions);
                    // add what we found in this file to the total list
                    endpoints.addAll(fileEndpoints);
                    simpleExpressions.addAll(fileSimpleExpressions);
                    // was there any unparsable?
                    if (logUnparseable && !unparsable.isEmpty()) {
                        for (String uri : unparsable) {
                            getLog().warn("Cannot parse endpoint uri " + uri + " in java file " + file);
                        }
                    }
                }
            } catch (Exception e) {
                getLog().warn("Error parsing java file " + file + " code due " + e.getMessage(), e);
            }
        }
    }
    for (File file : xmlFiles) {
        if (matchFile(file)) {
            try {
                List<CamelEndpointDetails> fileEndpoints = new ArrayList<>();
                List<CamelSimpleExpressionDetails> fileSimpleExpressions = new ArrayList<>();
                // parse the xml source code and find Camel routes
                String fqn = file.getPath();
                String baseDir = ".";
                InputStream is = new FileInputStream(file);
                XmlRouteParser.parseXmlRouteEndpoints(is, baseDir, fqn, fileEndpoints);
                is.close();
                // need a new stream
                is = new FileInputStream(file);
                XmlRouteParser.parseXmlRouteSimpleExpressions(is, baseDir, fqn, fileSimpleExpressions);
                is.close();
                // add what we found in this file to the total list
                endpoints.addAll(fileEndpoints);
                simpleExpressions.addAll(fileSimpleExpressions);
            } catch (Exception e) {
                getLog().warn("Error parsing xml file " + file + " code due " + e.getMessage(), e);
            }
        }
    }
    int endpointErrors = 0;
    int unknownComponents = 0;
    int incapableErrors = 0;
    for (CamelEndpointDetails detail : endpoints) {
        getLog().debug("Validating endpoint: " + detail.getEndpointUri());
        EndpointValidationResult result = catalog.validateEndpointProperties(detail.getEndpointUri(), ignoreLenientProperties);
        boolean ok = result.isSuccess();
        if (!ok && ignoreUnknownComponent && result.getUnknownComponent() != null) {
            // if we failed due unknown component then be okay if we should ignore that
            unknownComponents++;
            ok = true;
        }
        if (!ok && ignoreIncapable && result.getIncapable() != null) {
            // if we failed due incapable then be okay if we should ignore that
            incapableErrors++;
            ok = true;
        }
        if (!ok) {
            if (result.getUnknownComponent() != null) {
                unknownComponents++;
            } else if (result.getIncapable() != null) {
                incapableErrors++;
            } else {
                endpointErrors++;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("Endpoint validation error at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n\n");
            String out = result.summaryErrorMessage(false);
            sb.append(out);
            sb.append("\n\n");
            getLog().warn(sb.toString());
        } else if (showAll) {
            StringBuilder sb = new StringBuilder();
            sb.append("Endpoint validation passsed at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            sb.append("\n\t").append(result.getUri());
            sb.append("\n\n");
            getLog().info(sb.toString());
        }
    }
    String endpointSummary;
    if (endpointErrors == 0) {
        int ok = endpoints.size() - endpointErrors - incapableErrors - unknownComponents;
        endpointSummary = String.format("Endpoint validation success: (%s = passed, %s = invalid, %s = incapable, %s = unknown components)", ok, endpointErrors, incapableErrors, unknownComponents);
    } else {
        int ok = endpoints.size() - endpointErrors - incapableErrors - unknownComponents;
        endpointSummary = String.format("Endpoint validation error: (%s = passed, %s = invalid, %s = incapable, %s = unknown components)", ok, endpointErrors, incapableErrors, unknownComponents);
    }
    if (endpointErrors > 0) {
        getLog().warn(endpointSummary);
    } else {
        getLog().info(endpointSummary);
    }
    int simpleErrors = 0;
    for (CamelSimpleExpressionDetails detail : simpleExpressions) {
        SimpleValidationResult result;
        boolean predicate = detail.isPredicate();
        if (predicate) {
            getLog().debug("Validating simple predicate: " + detail.getSimple());
            result = catalog.validateSimplePredicate(detail.getSimple());
        } else {
            getLog().debug("Validating simple expression: " + detail.getSimple());
            result = catalog.validateSimpleExpression(detail.getSimple());
        }
        if (!result.isSuccess()) {
            simpleErrors++;
            StringBuilder sb = new StringBuilder();
            sb.append("Simple validation error at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            String[] lines = result.getError().split("\n");
            for (String line : lines) {
                sb.append("\n\t").append(line);
            }
            sb.append("\n");
            getLog().warn(sb.toString());
        } else if (showAll) {
            StringBuilder sb = new StringBuilder();
            sb.append("Simple validation passed at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            sb.append("\n\t").append(result.getSimple());
            sb.append("\n\n");
            getLog().info(sb.toString());
        }
    }
    String simpleSummary;
    if (simpleErrors == 0) {
        int ok = simpleExpressions.size() - simpleErrors;
        simpleSummary = String.format("Simple validation success: (%s = passed, %s = invalid)", ok, simpleErrors);
    } else {
        int ok = simpleExpressions.size() - simpleErrors;
        simpleSummary = String.format("Simple validation error: (%s = passed, %s = invalid)", ok, simpleErrors);
    }
    if (failOnError && (endpointErrors > 0 || simpleErrors > 0)) {
        throw new MojoExecutionException(endpointSummary + "\n" + simpleSummary);
    }
    if (simpleErrors > 0) {
        getLog().warn(simpleSummary);
    } else {
        getLog().info(simpleSummary);
    }
}
Also used : MavenVersionManager(org.apache.camel.catalog.maven.MavenVersionManager) CamelEndpointDetails(org.apache.camel.parser.model.CamelEndpointDetails) LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) LuceneSuggestionStrategy(org.apache.camel.catalog.lucene.LuceneSuggestionStrategy) ArrayList(java.util.ArrayList) List(java.util.List) SimpleValidationResult(org.apache.camel.catalog.SimpleValidationResult) DefaultCamelCatalog(org.apache.camel.catalog.DefaultCamelCatalog) CamelCatalog(org.apache.camel.catalog.CamelCatalog) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.apache.maven.model.Resource) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) FileInputStream(java.io.FileInputStream) JavaType(org.jboss.forge.roaster.model.JavaType) EndpointValidationResult(org.apache.camel.catalog.EndpointValidationResult) DefaultCamelCatalog(org.apache.camel.catalog.DefaultCamelCatalog) CamelSimpleExpressionDetails(org.apache.camel.parser.model.CamelSimpleExpressionDetails) File(java.io.File)

Example 60 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project camel by apache.

the class RoasterSimpleToDTest method parse.

@Test
public void parse() throws Exception {
    JavaClassSource clazz = (JavaClassSource) Roaster.parse(new File("src/test/java/org/apache/camel/parser/java/MySimpleToDRoute.java"));
    MethodSource<JavaClassSource> method = CamelJavaParserHelper.findConfigureMethod(clazz);
    List<CamelEndpointDetails> details = new ArrayList<>();
    RouteBuilderParser.parseRouteBuilderEndpoints(clazz, ".", "src/test/java/org/apache/camel/parser/java/MySimpleToDRoute.java", details);
    LOG.info("{}", details);
    List<ParserResult> list = CamelJavaParserHelper.parseCamelConsumerUris(method, true, true);
    for (ParserResult result : list) {
        LOG.info("Consumer: " + result.getElement());
    }
    Assert.assertEquals("direct:start", list.get(0).getElement());
    list = CamelJavaParserHelper.parseCamelProducerUris(method, true, true);
    for (ParserResult result : list) {
        LOG.info("Producer: " + result.getElement());
    }
    Assert.assertEquals("toD", list.get(0).getNode());
    Assert.assertEquals("log:a", list.get(0).getElement());
    Assert.assertEquals("to", list.get(1).getNode());
    Assert.assertEquals("log:b", list.get(1).getElement());
    Assert.assertEquals("to", list.get(2).getNode());
    Assert.assertEquals("log:c", list.get(2).getElement());
    Assert.assertEquals(3, list.size());
    Assert.assertEquals(4, details.size());
    Assert.assertEquals("direct:start", details.get(0).getEndpointUri());
    Assert.assertEquals("log:a", details.get(1).getEndpointUri());
    Assert.assertEquals("log:b", details.get(2).getEndpointUri());
    Assert.assertEquals("log:c", details.get(3).getEndpointUri());
}
Also used : CamelEndpointDetails(org.apache.camel.parser.model.CamelEndpointDetails) ParserResult(org.apache.camel.parser.ParserResult) ArrayList(java.util.ArrayList) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) File(java.io.File) Test(org.junit.Test)

Aggregations

JavaClassSource (org.jboss.forge.roaster.model.source.JavaClassSource)95 File (java.io.File)37 ArrayList (java.util.ArrayList)28 Test (org.junit.Test)26 ParserResult (org.apache.camel.parser.ParserResult)19 List (java.util.List)15 IOException (java.io.IOException)14 MethodSource (org.jboss.forge.roaster.model.source.MethodSource)12 InputStream (java.io.InputStream)10 Collections (java.util.Collections)10 Roaster (org.jboss.forge.roaster.Roaster)10 BufferedReader (java.io.BufferedReader)8 HashMap (java.util.HashMap)8 Matcher (java.util.regex.Matcher)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 ObjectProperty (org.kie.workbench.common.services.datamodeller.core.ObjectProperty)8 Arrays (java.util.Arrays)7 Map (java.util.Map)7 Import (org.jboss.forge.roaster.model.source.Import)7 ClassTypeResolver (org.kie.soup.project.datamodel.commons.types.ClassTypeResolver)7