com.github.javaparser.ast.expr.Name Java Examples

The following examples show how to use com.github.javaparser.ast.expr.Name. 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: ASTHelper.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addBlankImports(List<ImportDeclaration> imports, CompilationUnit nowCompilationUnit) {
    String lastStartWith = null;
    int size = imports.size();
    for (int i = size - 1; i >= 0; i--) {
        ImportDeclaration importDeclaration = imports.get(i);
        String importName = importDeclaration.getName().toString();
        int idx = importName.indexOf('.');
        if (idx > 0) {
            String nowStrartWith = importName.substring(0, idx + 1);
            if (lastStartWith != null && !lastStartWith.equals(nowStrartWith)) {
                Range range = new Range(Position.pos(0, 0), Position.pos(0, 0));
                ImportDeclaration emptyDeclaration = new ImportDeclaration(range, new Name(), false, false);
                imports.add(i + 1, emptyDeclaration);
                lastStartWith = null;
            } else {
                lastStartWith = nowStrartWith;
            }
        }
    }
}
 
Example #2
Source File: RegistryMethodVisitor.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
private String getClassName(MethodDeclaration methodDeclaration) {
    AtomicReference<String> className = new AtomicReference<>();
    methodDeclaration.findAncestor(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.class)
            .ifPresent(c -> className.set(c.getNameAsString()));
    String classNameStr = className.get() == null ? null : className.get();
    if (classNameStr == null) {
        return null;
    }

    AtomicReference<Name> packageName = new AtomicReference<>();
    methodDeclaration.findCompilationUnit()
            .ifPresent(c -> c.getPackageDeclaration()
                    .ifPresent(p -> packageName.set(p.getName()))
            );
    String packageNameStr = packageName.get() == null ? null : packageName.get().asString();

    if (packageNameStr == null) {
        return classNameStr;
    }
    return packageNameStr + "." + classNameStr;
}
 
Example #3
Source File: JavaEnumBuilderImpl.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates new java enum builder.
 *
 * @param packageName Package name.
 * @param name Enum name.
 */
public JavaEnumBuilderImpl(String packageName, String name) {
  super(packageName);
  declaration = getCompilationUnit().addEnum(name);
  declaration.setName(name);

  Name jsonPropertyName = new Name();
  jsonPropertyName.setQualifier(new Name(JSON_PROPERTY_PACKAGE));
  jsonPropertyName.setIdentifier(JSON_PROPERTY);
  getCompilationUnit().addImport(new ImportDeclaration(jsonPropertyName, false, false));
}
 
Example #4
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final Name n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    if (n.getQualifier().isPresent()) {
        n.getQualifier().get().accept(this, arg);
        printer.print(".");
    }
    printAnnotations(n.getAnnotations(), false, arg);
    printer.print(n.getIdentifier());

    printOrphanCommentsEnding(n);
}
 
Example #5
Source File: CompilationUnitUtils.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if given name is already imported on compilation unit.
 *
 * @param compilationUnit Compilation unit.
 * @param name Name to check for.
 * @return True if name is already imported.
 */
public static boolean isImported(CompilationUnit compilationUnit, Name name) {
  NodeList<ImportDeclaration> imports = compilationUnit.getImports();
  if (CollectionUtils.isNotEmpty(imports)) {
    for (ImportDeclaration importDeclaration : imports) {
      if (name.equals(importDeclaration.getName())) {
        return true;
      }
    }
  }

  return false;
}
 
Example #6
Source File: JavaClassBuilderImpl.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void addImport(String packageName, String object) {
  Name name = new Name();
  name.setQualifier(new Name(packageName));
  name.setIdentifier(object);

  if (!getPackageName().equalsIgnoreCase(packageName)
      && !CompilationUnitUtils.isImported(getCompilationUnit(), name)) {
    getCompilationUnit().addImport(new ImportDeclaration(name, false, false));
  }
}
 
Example #7
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 #8
Source File: ImpSortTest.java    From impsort-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveSamePackageImports() {
  Set<Import> imports = Stream
      .of(new Import(false, "abc.Blah", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.ef.Blah.Blah", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.ef.Blah2", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.efg.Blah2", "", "", LineEnding.AUTO.getChars()))
      .collect(Collectors.toSet());
  assertEquals(4, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports, Optional.empty());
  assertEquals(4, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports,
      Optional.of(new PackageDeclaration(new Name("abcd.ef"))));
  assertEquals(3, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertFalse(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports, Optional.of(new PackageDeclaration(new Name("abc"))));
  assertEquals(2, imports.size());
  assertFalse(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertFalse(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
}
 
Example #9
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ImportDeclaration n, Object arg) {
    Optional<Name> qualPath = n.getName().getQualifier();
    String qual = qualPath.map(value -> value.asString().replace('.', '/') + "/").orElse("");
    String id = n.getName().getIdentifier();
    String name = qual + id;
    imports.add(name);
    aliases.put(id, name);
    super.visit(n, arg);
}
 
Example #10
Source File: ModuleGenerator.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ModuleExportsDirective n, Void arg) {
  if (seenExports.contains(n.getNameAsString())) {
    return;
  }

  seenExports.add(n.getNameAsString());

  byteBuddyVisitor.visitExport(
    n.getNameAsString().replace('.', '/'),
    0,
    n.getModuleNames().stream().map(Name::asString).toArray(String[]::new));
}
 
Example #11
Source File: DependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Annotates given node with set of roles to enforce security
 *
 * @param node  node to be annotated
 * @param roles roles that are allowed
 */
default <T extends NodeWithAnnotations<?>> T withSecurityRoles(T node, String[] roles) {
    if (roles != null && roles.length > 0) {
        List<Expression> rolesExpr = new ArrayList<>();

        for (String role : roles) {
            rolesExpr.add(new StringLiteralExpr(role.trim()));
        }

        node.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.annotation.security.RolesAllowed"), new ArrayInitializerExpr(NodeList.nodeList(rolesExpr))));
    }
    return node;
}
 
Example #12
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey, String defaultValue) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey)),
                    new MemberValuePair("defaultValue", new StringLiteralExpr(defaultValue))
            )
    ));
    return node;
}
 
Example #13
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey))
            )
    ));
    return node;
}
 
Example #14
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 4 votes vote down vote up
protected ImportDeclaration importDeclaration(String name) {
    return new ImportDeclaration(new Name(name), false, false);
}
 
Example #15
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 4 votes vote down vote up
ImportDeclaration staticImportDeclaration(String name) {
    return new ImportDeclaration(new Name(name), true, false);
}
 
Example #16
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(Name n, Void arg) {
    out.println("Name: " + (extended ? n : n.getIdentifier()));
    super.visit(n, arg);
}
 
Example #17
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void addImport(String s) {
  cu.getImports().add(new ImportDeclaration(new Name(s), false, false));
}
 
Example #18
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 #19
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withNamed(T node, String name) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.inject.Named"), new StringLiteralExpr(name)));
    return node;
}
 
Example #20
Source File: DMNRestResourceGenerator.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/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 #21
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey, String defaultValue) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("org.springframework.beans.factory.annotation.Value"), new StringLiteralExpr("${" + configKey + ":" + defaultValue + "}")));
    return node;
}
 
Example #22
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("org.springframework.beans.factory.annotation.Value"), new StringLiteralExpr("${" + configKey + ":#{null}}")));
    return node;
}
 
Example #23
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withIncomingMessage(T node, String channel) {
    node.addAnnotation(new NormalAnnotationExpr(new Name("org.springframework.kafka.annotation.KafkaListener"), NodeList.nodeList(new MemberValuePair("topics", new StringLiteralExpr(channel)))));
    return node;
}
 
Example #24
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withOptionalInjection(T node) {
    node.addAnnotation(new NormalAnnotationExpr(new Name("org.springframework.beans.factory.annotation.Autowired"), NodeList.nodeList(new MemberValuePair("required", new BooleanLiteralExpr(false)))));
    return node;
}
 
Example #25
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withNamedApplicationComponent(T node, String name) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("org.springframework.stereotype.Component"), new StringLiteralExpr(name)));
    return node;
}
 
Example #26
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withNamed(T node, String name) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("org.springframework.beans.factory.annotation.Qualifier"), new StringLiteralExpr(name)));
    return node;
}
 
Example #27
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withOutgoingMessage(T node, String channel) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("io.smallrye.reactive.messaging.annotations.Channel"), new StringLiteralExpr(channel)));
    return node;
}
 
Example #28
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withIncomingMessage(T node, String channel) {
    node.addAnnotation(new SingleMemberAnnotationExpr(new Name("org.eclipse.microprofile.reactive.messaging.Incoming"), new StringLiteralExpr(channel)));
    return node;
}