예제 #1
0
  /**
   * Get the CtClass object linked to a Class object
   *
   * @param object
   * @return
   */
  public static CtClass<?> getClassElement(
      String[] sourcefolder, String cp, final String classFullName) {
    Factory factory = SpoonHelpers.obtainFactory();
    SpoonCompiler compiler = new JDTBasedSpoonCompiler(factory);

    for (String srcitem : sourcefolder) {
      compiler.addInputSource(new File(srcitem));
    }

    // Updating classpath
    if (cp != null) compiler.setSourceClasspath(cp);

    // Build (in memory)
    compiler.build();

    List<CtClass<?>> elements =
        Query.getElements(
            factory,
            new Filter<CtClass<?>>() {
              @Override
              public boolean matches(CtClass<?> arg0) {
                return arg0.getQualifiedName().equals(classFullName);
              }
            });

    if (elements.size() == 1) return elements.get(0);
    else return null;
  }
 protected List<CtLiteral> getLiterals(CtMethod method) {
   if (!literalsByMethod.containsKey(method)) {
     literalsByMethod.put(
         method, Query.getElements(method, new TypeFilter<CtLiteral>(CtLiteral.class)));
   }
   return literalsByMethod.get(method);
 }
예제 #3
0
 @Test
 public void printerCanPrintInvocationWithoutException() throws Exception {
   String packageName = "spoon.test.subclass.prettyprinter";
   String className = "DefaultPrettyPrinterExample";
   String qualifiedName = packageName + "." + className;
   SpoonCompiler comp = new Launcher().createCompiler();
   List<SpoonResource> fileToBeSpooned =
       SpoonResourceHelper.resources(
           "./src/test/resources/printer-test/" + qualifiedName.replace('.', '/') + ".java");
   assertEquals(1, fileToBeSpooned.size());
   comp.addInputSources(fileToBeSpooned);
   List<SpoonResource> classpath =
       SpoonResourceHelper.resources(
           "./src/test/resources/printer-test/DefaultPrettyPrinterDependency.jar");
   assertEquals(1, classpath.size());
   comp.setSourceClasspath(classpath.get(0).getPath());
   comp.build();
   Factory factory = comp.getFactory();
   CtType<?> theClass = factory.Type().get(qualifiedName);
   List<CtInvocation<?>> elements =
       Query.getElements(theClass, new TypeFilter<CtInvocation<?>>(CtInvocation.class));
   assertEquals(3, elements.size());
   CtInvocation<?> mathAbsInvocation = elements.get(1);
   assertEquals("java.lang.Math.abs(message.length())", mathAbsInvocation.toString());
 }
 protected List<CtStatement> getAssertStatement(CtMethod method) {
   List<CtStatement> statements = Query.getElements(method, new TypeFilter(CtStatement.class));
   return statements
       .stream()
       .filter(stmt -> stmt.getParent() instanceof CtBlock)
       .filter(stmt -> AmplificationChecker.isAssert(stmt))
       .collect(Collectors.toList());
 }
예제 #5
0
 @Override
 public <T extends CtBlock<R>> T insertBefore(
     Filter<? extends CtStatement> insertionPoints, CtStatementList statements) {
   for (CtStatement e : Query.getElements(this, insertionPoints)) {
     e.insertBefore(statements);
   }
   return (T) this;
 }
예제 #6
0
 protected void generateProcessedSourceFilesUsingTypes(Filter<CtType<?>> typeFilter) {
   if (factory.getEnvironment().getDefaultFileGenerator() != null) {
     factory.getEnvironment().debugMessage("Generating source using types...");
     ProcessingManager processing = new QueueProcessingManager(factory);
     processing.addProcessor(factory.getEnvironment().getDefaultFileGenerator());
     if (typeFilter != null) {
       processing.process(Query.getElements(factory.Package().getRootPackage(), typeFilter));
     } else {
       processing.process(factory.Package().getRootPackage());
     }
   }
 }
예제 #7
0
  @Test
  public void testCanVisitFieldAccessAndSubClasses() throws Exception {
    final Factory factory = build(FieldAccessSample.class);

    final List<CtFieldRead<?>> fieldsRead =
        Query.getElements(
            factory,
            new AbstractFilter<CtFieldRead<?>>(CtFieldRead.class) {
              @Override
              public boolean matches(CtFieldRead<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(2, fieldsRead.size());

    final List<CtFieldWrite<?>> fieldsWrite =
        Query.getElements(
            factory,
            new AbstractFilter<CtFieldWrite<?>>(CtFieldWrite.class) {
              @Override
              public boolean matches(CtFieldWrite<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(3, fieldsWrite.size());

    final List<CtFieldAccess<?>> fieldsAccess =
        Query.getElements(
            factory,
            new AbstractFilter<CtFieldAccess<?>>(CtFieldAccess.class) {
              @Override
              public boolean matches(CtFieldAccess<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(5, fieldsAccess.size());
  }
예제 #8
0
  @Test
  public void testCanVisitVariableAccessAndSubClasses() throws Exception {
    final Factory factory = build(VariableAccessSample.class);

    final List<CtVariableRead<?>> variablesRead =
        Query.getElements(
            factory,
            new AbstractFilter<CtVariableRead<?>>(CtVariableRead.class) {
              @Override
              public boolean matches(CtVariableRead<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(2, variablesRead.size()); // System.out and s

    final List<CtVariableWrite<?>> variablesWrite =
        Query.getElements(
            factory,
            new AbstractFilter<CtVariableWrite<?>>(CtVariableWrite.class) {
              @Override
              public boolean matches(CtVariableWrite<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(1, variablesWrite.size());

    final List<CtVariableAccess<?>> variablesAccess =
        Query.getElements(
            factory,
            new AbstractFilter<CtVariableAccess<?>>(CtVariableAccess.class) {
              @Override
              public boolean matches(CtVariableAccess<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(3, variablesAccess.size());
  }
예제 #9
0
  @Test
  public void testCanVisitArrayAccessAndSubClasses() throws Exception {
    final Factory factory = build(ArrayAccessSample.class);

    final List<CtArrayRead<?>> arraysRead =
        Query.getElements(
            factory,
            new AbstractFilter<CtArrayRead<?>>(CtArrayRead.class) {
              @Override
              public boolean matches(CtArrayRead<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(2, arraysRead.size());

    final List<CtArrayWrite<?>> arraysWrite =
        Query.getElements(
            factory,
            new AbstractFilter<CtArrayWrite<?>>(CtArrayWrite.class) {
              @Override
              public boolean matches(CtArrayWrite<?> element) {
                return super.matches(element);
              }
            });

    assertEquals(1, arraysWrite.size());

    final List<CtArrayAccess<?, CtExpression<?>>> arraysAccess =
        Query.getElements(
            factory,
            new AbstractFilter<CtArrayAccess<?, CtExpression<?>>>(CtArrayAccess.class) {
              @Override
              public boolean matches(CtArrayAccess<?, CtExpression<?>> element) {
                return super.matches(element);
              }
            });

    assertEquals(3, arraysAccess.size());
  }
  public void reset(Coverage coverage, CtType testClass) {
    AmplificationHelper.reset();
    literalsByMethod = new HashMap<>();

    Set<CtType> codeFragmentsProvide = AmplificationHelper.computeClassProvider(testClass);

    List<Statement> codeFragmentsByClass =
        codeFragmentsProvide
            .stream()
            .flatMap(
                cl -> {
                  List<CtStatement> list = Query.getElements(cl, new TypeFilter(CtStatement.class));
                  return list.stream();
                })
            .filter(
                stmt -> {
                  try {
                    return stmt.getParent() != null;
                  } catch (Exception e) {
                    return false;
                  }
                })
            .filter(stmt -> stmt.getParent() instanceof CtBlock)
            .filter(stmt -> !stmt.toString().startsWith("super"))
            .filter(stmt -> !stmt.toString().startsWith("this("))
            .map(stmt -> new Statement(stmt))
            .collect(Collectors.toList());

    if (findClassUnderTest(testClass) != null) {
      coverageBycodeFragments = buildCodeFragmentFor(findClassUnderTest(testClass), coverage);
    } else {
      coverageBycodeFragments = new HashMap<>();
    }

    Set<Integer> ids = new HashSet<>();
    localVars =
        codeFragmentsByClass
            .stream()
            .filter(cf -> isValidCodeFragment(cf))
            .filter(cf -> ids.add(cf.id()))
            .collect(Collectors.toList());
  }
  public static Set<CtType> computeClassProvider(CtType testClass) {
    List<CtType> types =
        Query.getElements(testClass.getParent(CtPackage.class), new TypeFilter(CtType.class));
    types =
        types
            .stream()
            .filter(type -> type != null)
            .filter(type -> type.getPackage() != null)
            .filter(
                type ->
                    type.getPackage()
                        .getQualifiedName()
                        .equals(testClass.getPackage().getQualifiedName()))
            .collect(Collectors.toList());

    if (testClass.getParent(CtType.class) != null) {
      types.add(testClass.getParent(CtType.class));
    }

    types.addAll(
        types.stream().flatMap(type -> getImport(type).stream()).collect(Collectors.toSet()));

    return types.stream().collect(Collectors.toSet());
  }
예제 #12
0
 public <T extends CtReference> List<T> getReferences(ReferenceFilter<T> filter) {
   return Query.getReferences(this, filter);
 }
예제 #13
0
 public <E extends CtElement> List<E> getElements(Filter<E> filter) {
   return Query.getElements(this, filter);
 }
예제 #14
0
 @SuppressWarnings("unchecked")
 public <E extends CtElement> List<E> getAnnotatedChildren(
     Class<? extends Annotation> annotationType) {
   return (List<E>)
       Query.getElements(this, new AnnotationFilter<CtElement>(CtElement.class, annotationType));
 }