Java Code Examples for com.github.javaparser.ast.CompilationUnit#addImport()

The following examples show how to use com.github.javaparser.ast.CompilationUnit#addImport() . 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: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
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 2
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
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 3
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with Apache License 2.0 6 votes vote down vote up
void organiseImports(CompilationUnit cu) {
    List<ImportDeclaration> importDecls = new ArrayList<>();
    for (ImportDeclaration importDeclaration : cu.getImports()) {
        if (importDeclaration.getNameAsString().startsWith("org.jctools.util.Unsafe")) {
            continue;
        }
        importDecls.add(importDeclaration);
    }
    cu.getImports().clear();
    for (ImportDeclaration importDecl : importDecls) {
        cu.addImport(importDecl);
    }
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceArray"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongArray"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueueUtil"));
    cu.addImport(staticImportDeclaration("org.jctools.queues.atomic.AtomicQueueUtil.*"));
}
 
Example 4
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addMonitoringToResource(CompilationUnit cu, MethodDeclaration[] methods, String nameURL) {
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));

    for (MethodDeclaration md : methods) {
        BlockStmt body = md.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"));
        NodeList<Statement> statements = body.getStatements();
        ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a return statement!"));
        statements.addFirst(parseStatement("double startTime = System.nanoTime();"));
        statements.addBefore(parseStatement("double endTime = System.nanoTime();"), returnStmt);
        statements.addBefore(parseStatement("SystemMetricsCollector.registerElapsedTimeSampleMetrics(\"" + nameURL + "\", endTime - startTime);"), returnStmt);
        md.setBody(wrapBodyAddingExceptionLogging(body, nameURL));
    }
}
 
Example 5
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
void organiseImports(CompilationUnit cu) {
    List<ImportDeclaration> importDecls = new ArrayList<>();
    for (ImportDeclaration importDeclaration : cu.getImports()) {
        String name = importDeclaration.getNameAsString();
        if (name.startsWith("org.jctools.util.Unsafe")) {
            continue;
        }

        if (name.startsWith("org.jctools.queues.LinkedArrayQueueUtil")) {
            continue;
        }

        importDecls.add(importDeclaration);
    }
    cu.getImports().clear();
    for (ImportDeclaration importDecl : importDecls) {
        cu.addImport(importDecl);
    }
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceArray"));

    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueue"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueue.Supplier"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueueUtil"));
    cu.addImport(importDeclaration("org.jctools.queues.QueueProgressIndicators"));
    cu.addImport(importDeclaration("org.jctools.queues.IndexedQueueSizeUtil"));
    cu.addImport(staticImportDeclaration("org.jctools.queues.atomic.AtomicQueueUtil.*"));
}
 
Example 6
Source File: MessageConsumerGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
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 7
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void addMonitoringImports(CompilationUnit cu) {
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.DMNResultMetricsBuilder"), false, false));
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));
}
 
Example 8
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
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);
  }
}