Java Code Examples for com.github.javaparser.ast.CompilationUnit#setPackageDeclaration()
The following examples show how to use
com.github.javaparser.ast.CompilationUnit#setPackageDeclaration() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApplicationGenerator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
private List<GeneratedFile> generateApplicationSections() { ArrayList<GeneratedFile> generatedFiles = new ArrayList<>(); for (Generator generator : generators) { ApplicationSection section = generator.section(); if (section == null) { continue; } CompilationUnit sectionUnit = new CompilationUnit(); sectionUnit.setPackageDeclaration( this.packageName ); sectionUnit.addType( section.classDeclaration() ); generatedFiles.add( new GeneratedFile(GeneratedFile.Type.APPLICATION_SECTION, getFilePath(section.sectionClassName()), sectionUnit.toString())); } return generatedFiles; }
Example 2
Source File: ProcessToExecModelGenerator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public MethodDeclaration generateMethod(WorkflowProcess process) { CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/ProcessTemplate.java")); clazz.setPackageDeclaration(process.getPackageName()); String extractedProcessId = extractProcessId(process.getId()); String packageName = clazz.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse(null); ProcessMetaData metadata = new ProcessMetaData(process.getId(), extractedProcessId, process.getName(), process.getVersion(), packageName, "process"); MethodDeclaration processMethod = new MethodDeclaration(); processVisitor.visitProcess(process, processMethod, metadata); return processMethod; }
Example 3
Source File: CdpClientGenerator.java From selenium with Apache License 2.0 | 6 votes |
public void dumpTo(Path target) { if (type instanceof ObjectType) { CompilationUnit unit = new CompilationUnit(); unit.setPackageDeclaration(getNamespace()); unit.addImport(Beta.class); unit.addImport(JsonInput.class); unit.addType(toTypeDeclaration()); Path eventFile = target.resolve(capitalize(name) + ".java"); ensureFileDoesNotExists(eventFile); try { Files.write(eventFile, unit.toString().getBytes()); } catch (IOException e) { throw new UncheckedIOException(e); } } }
Example 4
Source File: CdpClientGenerator.java From selenium with Apache License 2.0 | 6 votes |
public void dumpTo(Path target) { CompilationUnit unit = new CompilationUnit(); unit.setPackageDeclaration("org.openqa.selenium.devtools." + domain.name.toLowerCase() + ".model"); unit.addImport(Beta.class); unit.addImport(JsonInput.class); unit.addType(toTypeDeclaration()); Path typeFile = target.resolve(capitalize(name) + ".java"); ensureFileDoesNotExists(typeFile); try { Files.write(typeFile, unit.toString().getBytes()); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 5
Source File: CDIDependencyInjectionAnnotator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public String objectMapperInjectorSource(String packageName) { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/rules/KogitoQuarkusObjectMapper.java")); clazz.setPackageDeclaration( packageName ); return clazz.toString(); }
Example 6
Source File: SpringDependencyInjectionAnnotator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public String objectMapperInjectorSource(String packageName) { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/rules/KogitoSpringObjectMapper.java")); clazz.setPackageDeclaration( packageName ); return clazz.toString(); }
Example 7
Source File: MessageProducerGenerator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public String generate() { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java")); clazz.setPackageDeclaration(process.getPackageName()); ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get(); template.setName(resourceClazzName); template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType())); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()))); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct")); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> { md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType())); md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName))); }); if (useInjection()) { annotator.withApplicationComponent(template); FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class).filter(fd -> fd.getVariable(0).getNameAsString().equals("emitter")).get(); annotator.withInjection(emitterField); annotator.withOutgoingMessage(emitterField, trigger.getName()); emitterField.getVariable(0).setType(annotator.emitterType("String")); MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methos in MessageProducerTemplate")); BlockStmt body = new BlockStmt(); MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send"); annotator.withMessageProducer(sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall").addArgument(new NameExpr("pi")).addArgument(new NameExpr(EVENT_DATA_VAR))); body.addStatement(sendMethodCall); produceMethod.setBody(body); template.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents")); } template.getMembers().sort(new BodyDeclarationComparator()); return clazz.toString(); }
Example 8
Source File: MessageDataEventGenerator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public String generate() { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java")); clazz.setPackageDeclaration(process.getPackageName()); ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in MessageDataEventTemplate")); template.setName(resourceClazzName); template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType())); template.findAll(ConstructorDeclaration.class).stream().forEach(cd -> cd.setName(resourceClazzName)); template.getMembers().sort(new BodyDeclarationComparator()); return clazz.toString(); }
Example 9
Source File: QueryEndpointGenerator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public String generate() { CompilationUnit cu = parse( this.getClass().getResourceAsStream("/class-templates/rules/RestQueryTemplate.java")); cu.setPackageDeclaration(query.getNamespace()); ClassOrInterfaceDeclaration clazz = cu .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); clazz.setName(targetCanonicalName); cu.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings); FieldDeclaration ruleUnitDeclaration = clazz .getFieldByName("ruleUnit") .orElseThrow(() -> new NoSuchElementException("ClassOrInterfaceDeclaration doesn't contain a field named ruleUnit!")); setUnitGeneric(ruleUnitDeclaration.getElementType()); if (annotator != null) { annotator.withInjection(ruleUnitDeclaration); } String returnType = getReturnType(clazz); generateConstructors(clazz); generateQueryMethods(cu, clazz, returnType); clazz.getMembers().sort(new BodyDeclarationComparator()); return cu.toString(); }
Example 10
Source File: RuleUnitDTOSourceClass.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public String generate() { CompilationUnit cu = new CompilationUnit(); cu.setPackageDeclaration(packageName); ClassOrInterfaceDeclaration dtoClass = cu.addClass(targetCanonicalName, Modifier.Keyword.PUBLIC); dtoClass.addImplementedType(String.format("java.util.function.Supplier<%s>", ruleUnit.getSimpleName())); MethodDeclaration supplier = dtoClass.addMethod("get", Modifier.Keyword.PUBLIC); supplier.addAnnotation(Override.class); supplier.setType(ruleUnit.getSimpleName()); BlockStmt supplierBlock = supplier.createBody(); supplierBlock.addStatement(String.format("%s unit = new %s();", ruleUnit.getSimpleName(), ruleUnit.getSimpleName())); for (RuleUnitVariable unitVarDeclaration : ruleUnit.getUnitVarDeclarations()) { FieldProcessor fieldProcessor = new FieldProcessor(unitVarDeclaration, ruleUnitHelper ); FieldDeclaration field = fieldProcessor.createField(); supplierBlock.addStatement(fieldProcessor.fieldInitializer()); dtoClass.addMember(field); field.createGetter(); field.createSetter(); } supplierBlock.addStatement("return unit;"); return cu.toString(); }
Example 11
Source File: ProcessToExecModelGenerator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public ProcessMetaData generate(WorkflowProcess process) { CompilationUnit parsedClazzFile = parse(this.getClass().getResourceAsStream(PROCESS_TEMPLATE_FILE)); parsedClazzFile.setPackageDeclaration(process.getPackageName()); Optional<ClassOrInterfaceDeclaration> processClazzOptional = parsedClazzFile.findFirst(ClassOrInterfaceDeclaration.class, sl -> true); String extractedProcessId = extractProcessId(process.getId()); if (!processClazzOptional.isPresent()) { throw new NoSuchElementException("Cannot find class declaration in the template"); } ClassOrInterfaceDeclaration processClazz = processClazzOptional.get(); processClazz.setName(StringUtils.capitalize(extractedProcessId + PROCESS_CLASS_SUFFIX)); String packageName = parsedClazzFile.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse(null); ProcessMetaData metadata = new ProcessMetaData(process.getId(), extractedProcessId, process.getName(), process.getVersion(), packageName, processClazz.getNameAsString()); Optional<MethodDeclaration> processMethod = parsedClazzFile.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("process")); processVisitor.visitProcess(process, processMethod.get(), metadata); metadata.setGeneratedClassModel(parsedClazzFile); return metadata; }
Example 12
Source File: MessageConsumerGenerator.java From kogito-runtimes with Apache License 2.0 | 4 votes |
public String generate() { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/MessageConsumerTemplate.java")); clazz.setPackageDeclaration(process.getPackageName()); clazz.addImport(modelfqcn); ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get(); template.setName(resourceClazzName); template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, dataClazzName)); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct")); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> { interpolateArguments(md, "String"); md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$Trigger$", trigger.getName()))); md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName))); md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataType$", trigger.getDataType()))); }); template.findAll(MethodCallExpr.class).forEach(this::interpolateStrings); if (useInjection()) { annotator.withApplicationComponent(template); template.findAll(FieldDeclaration.class, fd -> isProcessField(fd)).forEach(fd -> annotator.withNamedInjection(fd, processId)); template.findAll(FieldDeclaration.class, fd -> isApplicationField(fd)).forEach(fd -> annotator.withInjection(fd)); template.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents")); template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> annotator.withIncomingMessage(md, trigger.getName())); } else { template.findAll(FieldDeclaration.class, fd -> isProcessField(fd)).forEach(fd -> initializeProcessField(fd, template)); template.findAll(FieldDeclaration.class, fd -> isApplicationField(fd)).forEach(fd -> initializeApplicationField(fd, template)); } template.getMembers().sort(new BodyDeclarationComparator()); return clazz.toString(); }
Example 13
Source File: DMNRestResourceGenerator.java From kogito-runtimes with Apache License 2.0 | 4 votes |
public String generate() { CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java")); clazz.setPackageDeclaration(this.packageName); ClassOrInterfaceDeclaration template = clazz .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); template.setName(resourceClazzName); template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings); template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods); interpolateInputType(template); if (useInjection()) { template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd)); } else { template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(this::initializeApplicationField); } MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0); for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) { if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) { continue; } MethodDeclaration clonedMethod = dmnMethod.clone(); String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName()); clonedMethod.setName(name); MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!")); evaluateCall.setName(new SimpleName("evaluateDecisionService")); evaluateCall.addArgument(new StringLiteralExpr(ds.getName())); clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName()))); ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!")); if (ds.getOutputDecision().size() == 1) { MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class, mce -> mce.getNameAsString().equals("extractContextIfSucceded")) .orElseThrow(() -> new RuntimeException("Template was modified!")); rewrittenReturnExpr.setName("extractSingletonDSIfSucceded"); } if (useMonitoring) { addMonitoringToMethod(clonedMethod, ds.getName()); } template.addMember(clonedMethod); } if (useMonitoring) { addMonitoringImports(clazz); ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString())) .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed.")); addExceptionMetricsLogging(exceptionClazz, nameURL); addMonitoringToMethod(dmnMethod, nameURL); } template.getMembers().sort(new BodyDeclarationComparator()); return clazz.toString(); }
Example 14
Source File: UserTaskModelMetaData.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@SuppressWarnings({"unchecked"}) private CompilationUnit compilationUnitOutput() { CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream("/class-templates/TaskOutputTemplate.java")); compilationUnit.setPackageDeclaration(packageName); Optional<ClassOrInterfaceDeclaration> processMethod = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class, sl1 -> true); if (!processMethod.isPresent()) { throw new RuntimeException("Cannot find class declaration in the template"); } ClassOrInterfaceDeclaration modelClass = processMethod.get(); compilationUnit.addOrphanComment(new LineComment("Task output model for user task '" + humanTaskNode.getName() + "' in process '" + processId + "'")); addUserTaskAnnotation(modelClass); modelClass.setName(outputModelClassSimpleName); // setup of the toMap method body BlockStmt toMapBody = new BlockStmt(); ClassOrInterfaceType toMap = new ClassOrInterfaceType(null, new SimpleName(Map.class.getSimpleName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getSimpleName()), new ClassOrInterfaceType( null, Object.class.getSimpleName()))); VariableDeclarationExpr paramsField = new VariableDeclarationExpr(toMap, "params"); toMapBody.addStatement(new AssignExpr(paramsField, new ObjectCreationExpr(null, new ClassOrInterfaceType(null, HashMap.class.getSimpleName()), NodeList.nodeList()), AssignExpr.Operator.ASSIGN)); for (Entry<String, String> entry : humanTaskNode.getOutMappings().entrySet()) { if (entry.getValue() == null || INTERNAL_FIELDS.contains(entry.getKey())) { continue; } Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue())) .orElse(processVariableScope.findVariable(entry.getValue())); if (variable == null) { // check if given mapping is an expression Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(entry.getValue()); if (matcher.find()) { Map<String, String> dataOutputs = (Map<String, String>) humanTaskNode.getMetaData("DataOutputs"); variable = new Variable(); variable.setName(entry.getKey()); variable.setType(new ObjectDataType(dataOutputs.get(entry.getKey()))); } else { throw new IllegalStateException("Task " + humanTaskNode.getName() +" (output) " + entry.getKey() + " reference not existing variable " + entry.getValue()); } } FieldDeclaration fd = new FieldDeclaration().addVariable( new VariableDeclarator() .setType(variable.getType().getStringType()) .setName(entry.getKey())) .addModifier(Modifier.Keyword.PRIVATE); modelClass.addMember(fd); addUserTaskParamAnnotation(fd, UserTaskParam.ParamType.OUTPUT); fd.createGetter(); fd.createSetter(); // toMap method body MethodCallExpr putVariable = new MethodCallExpr(new NameExpr("params"), "put"); putVariable.addArgument(new StringLiteralExpr(entry.getKey())); putVariable.addArgument(new FieldAccessExpr(new ThisExpr(), entry.getKey())); toMapBody.addStatement(putVariable); } Optional<MethodDeclaration> toMapMethod = modelClass.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("toMap")); toMapBody.addStatement(new ReturnStmt(new NameExpr("params"))); toMapMethod.ifPresent(methodDeclaration -> methodDeclaration.setBody(toMapBody)); return compilationUnit; }
Example 15
Source File: CdpClientGenerator.java From selenium with Apache License 2.0 | 4 votes |
private void dumpMainClass(Path target) { CompilationUnit unit = new CompilationUnit(); unit.setPackageDeclaration(String.format("%s.%s", model.basePackage, name.toLowerCase())); unit.addImport(Beta.class); unit.addImport(Command.class); unit.addImport(Event.class); unit.addImport(ConverterFunctions.class); unit.addImport(ImmutableMap.class); unit.addImport(JsonInput.class); ClassOrInterfaceDeclaration classDecl = unit.addClass(name); if (description != null) { classDecl.setJavadocComment(description); } if (experimental) { classDecl.addAnnotation(Beta.class); } if (deprecated) { classDecl.addAnnotation(Deprecated.class); } commands.forEach(command -> { if (command.type instanceof ObjectType || command.type instanceof EnumType) { classDecl.addMember(command.type.toTypeDeclaration().setPublic(true).setStatic(true)); } command.parameters.forEach(parameter -> { if (parameter.type instanceof EnumType) { EnumType parameterType = ((EnumType) parameter.type); parameterType.name = capitalize(command.name) + parameterType.name; classDecl.addMember(parameter.type.toTypeDeclaration().setPublic(true)); } }); classDecl.addMember(command.toMethodDeclaration()); }); events.forEach(event -> { if (event.type instanceof EnumType) { classDecl.addMember(event.type.toTypeDeclaration().setPublic(true)); } classDecl.addMember(event.toMethodDeclaration()); }); Path commandFile = target.resolve(name + ".java"); ensureFileDoesNotExists(commandFile); try { Files.write(commandFile, unit.toString().getBytes()); } catch (IOException e) { throw new UncheckedIOException(e); } }