Ejemplo n.º 1
0
  private boolean evaluate(
      GraphRewrite event, EvaluationContext context, EvaluationStrategy evaluationStrategy) {
    try {
      ExecutionStatistics.get().begin("JavaClass.evaluate");

      final ParameterStore store = DefaultParameterStore.getInstance(context);
      final Pattern compiledPattern = referencePattern.getCompiledPattern(store);

      /*
       * Only set in the case of a query with no "from" variable.
       */
      String initialQueryID = null;

      QueryBuilderFrom query;
      initialQueryID = "iqi." + UUID.randomUUID().toString();

      // prepare initialQueryID
      if (!StringUtils.isBlank(getInputVariablesName())) {
        QueryBuilderFrom fromQuery = Query.from(getInputVariablesName());
        QueryBuilderPiped piped =
            fromQuery.piped(
                new QueryGremlinCriterion() {
                  @Override
                  public void query(GraphRewrite event, GremlinPipeline<Vertex, Vertex> pipeline) {
                    pipeline
                        .out(FileReferenceModel.FILE_MODEL)
                        .in(FileReferenceModel.FILE_MODEL)
                        .has(
                            JavaTypeReferenceModel.RESOLVED_SOURCE_SNIPPIT,
                            Text.REGEX,
                            compiledPattern.toString());
                  }
                });
        piped.as(initialQueryID).evaluate(event, context);
      } else {
        GremlinPipeline<Vertex, Vertex> resolvedTextSearch =
            new GremlinPipeline<>(event.getGraphContext().getGraph());
        resolvedTextSearch.V();
        resolvedTextSearch.has(
            JavaTypeReferenceModel.RESOLVED_SOURCE_SNIPPIT, Text.REGEX, titanify(compiledPattern));

        if (!resolvedTextSearch.iterator().hasNext()) return false;

        Variables.instance(event)
            .setVariable(
                initialQueryID,
                new FramedVertexIterable<>(
                    event.getGraphContext().getFramed(),
                    resolvedTextSearch,
                    JavaTypeReferenceModel.class));
      }
      query = Query.from(initialQueryID);

      if (lineMatchPattern != null) {
        final Pattern compiledLineMatchPattern = lineMatchPattern.getCompiledPattern(store);
        query.withProperty(
            JavaTypeReferenceModel.SOURCE_SNIPPIT,
            QueryPropertyComparisonType.REGEX,
            compiledLineMatchPattern.pattern());
      }
      String uuid = UUID.randomUUID().toString();
      query.as(uuid);

      if (typeFilterPattern != null) {
        Pattern compiledTypeFilterPattern = typeFilterPattern.getCompiledPattern(store);
        query.piped(new TypeFilterCriterion(compiledTypeFilterPattern));
      }
      if (!locations.isEmpty())
        query.withProperty(JavaTypeReferenceModel.REFERENCE_TYPE, locations);

      List<WindupVertexFrame> results = new ArrayList<>();
      if (query.evaluate(event, context)) {
        Iterable<? extends WindupVertexFrame> frames = Variables.instance(event).findVariable(uuid);
        for (WindupVertexFrame frame : frames) {
          FileModel fileModel = ((FileReferenceModel) frame).getFile();
          Iterable<JavaClassModel> javaClasses = null;
          if (fileModel instanceof AbstractJavaSourceModel)
            javaClasses = ((AbstractJavaSourceModel) fileModel).getJavaClasses();
          else if (fileModel instanceof JavaClassFileModel)
            javaClasses = Arrays.asList(((JavaClassFileModel) fileModel).getJavaClass());

          for (JavaClassModel javaClassModel : javaClasses) {
            if (typeFilterPattern == null
                || typeFilterPattern.parse(javaClassModel.getQualifiedName()).matches()) {
              JavaTypeReferenceModel model = (JavaTypeReferenceModel) frame;
              ParameterizedPatternResult referenceResult =
                  referencePattern.parse(model.getResolvedSourceSnippit());
              if (referenceResult.matches()) {
                evaluationStrategy.modelMatched();

                if (referenceResult.submit(event, context)
                    && (typeFilterPattern == null
                        || typeFilterPattern
                            .parse(javaClassModel.getQualifiedName())
                            .submit(event, context))) {
                  boolean annotationMatched =
                      matchAnnotationConditions(event, context, evaluationStrategy, model);
                  if (!annotationMatched) {
                    evaluationStrategy.modelSubmissionRejected();
                  } else {
                    results.add(model);
                    evaluationStrategy.modelSubmitted(model);
                  }
                } else {
                  evaluationStrategy.modelSubmissionRejected();
                }
              }
            }
          }
        }
        Variables.instance(event).removeVariable(uuid);
        if (initialQueryID != null) Variables.instance(event).removeVariable(initialQueryID);

        setResults(event, getVarname(), results);
        return !results.isEmpty();
      }
      return false;
    } finally {
      ExecutionStatistics.get().end("JavaClass.evaluate");
    }
  }
  @Override
  public void perform(
      final GraphRewrite event, final EvaluationContext context, final ReportModel payload) {
    String templatePath = payload.getTemplatePath();
    String outputFilename = payload.getReportFilename();

    ExecutionStatistics.get()
        .begin("FreeMarkerIterationOperation.render(" + templatePath + ", " + outputFilename + ")");
    try {
      ReportService reportService = new ReportService(event.getGraphContext());

      Path outputDir = Paths.get(reportService.getReportDirectory());

      if (!Files.isDirectory(outputDir)) {
        Files.createDirectories(outputDir);
      }

      Path outputPath = outputDir.resolve(outputFilename);

      LOG.info(
          "Reporting: Writing template \""
              + templatePath
              + "\" to output file \""
              + outputPath.toAbsolutePath().toString()
              + "\"");

      Configuration freemarkerConfig =
          new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
      DefaultObjectWrapperBuilder objectWrapperBuilder =
          new DefaultObjectWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
      objectWrapperBuilder.setUseAdaptersForContainers(true);
      freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());
      freemarkerConfig.setAPIBuiltinEnabled(true);
      freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());
      freemarkerConfig.setTemplateUpdateDelayMilliseconds(3600);

      Template template = freemarkerConfig.getTemplate(templatePath);

      Variables variables = Variables.instance(event);

      // just the variables
      Map<String, Object> vars =
          FreeMarkerUtil.findFreeMarkerContextVariables(
              variables, variableNames.toArray(new String[variableNames.size()]));

      if (useDefaultPayloadVariableName) {
        vars.put(DEFAULT_ITERATION_PAYLOAD_NAME, payload);
      }

      // also, extension functions (these are kept separate from vars in order to prevent them
      // from being stored in the associated data with the reportmodel)
      final Map<String, Object> freeMarkerExtensions;
      freeMarkerExtensions =
          furnace
              .getLockManager()
              .performLocked(
                  LockMode.WRITE,
                  new Callable<Map<String, Object>>() {
                    @Override
                    public Map<String, Object> call() throws Exception {
                      return FreeMarkerUtil.findFreeMarkerExtensions(furnace, event);
                    }
                  });

      Map<String, Object> objects = new HashMap<>(vars);
      objects.putAll(freeMarkerExtensions);

      try (FileWriter fw = new FileWriter(outputPath.toFile())) {
        template.process(objects, fw);
      }

      FreeMarkerUtil.addAssociatedReportData(event.getGraphContext(), payload, vars);
    } catch (IOException | TemplateException e) {
      LOG.log(
          Level.WARNING,
          "Template \""
              + templatePath
              + "\" Failed to write report at \""
              + outputFilename
              + "\" due to: "
              + e.getMessage(),
          e);
    } finally {
      ExecutionStatistics.get()
          .end("FreeMarkerIterationOperation.render(" + templatePath + ", " + outputFilename + ")");
    }
  }