Ejemplo n.º 1
0
  private static String readClassFromCamelResource(
      File file, StringBuilder buffer, BuildContext buildContext) throws MojoExecutionException {
    // skip directories as there may be a sub .resolver directory such as in camel-script
    if (file.isDirectory()) {
      return null;
    }
    String name = file.getName();
    if (name.charAt(0) != '.') {
      if (buffer.length() > 0) {
        buffer.append(" ");
      }
      buffer.append(name);
    }

    if (!buildContext.hasDelta(file)) {
      // if this file has not changed,
      // then no need to store the javatype
      // for the json file to be generated again
      // (but we do need the name above!)
      return null;
    }

    // find out the javaType for each data format
    try {
      String text = loadText(new FileInputStream(file));
      Map<String, String> map = parseAsMap(text);
      return map.get("class");
    } catch (IOException e) {
      throw new MojoExecutionException("Failed to read file " + file + ". Reason: " + e, e);
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant#build(int,
   *     org.eclipse.core.runtime.IProgressMonitor)
   */
  @Override
  public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception {
    final IMaven maven = MavenPlugin.getMaven();
    final BuildContext buildContext = getBuildContext();
    final MavenProject project = getMavenProjectFacade().getMavenProject();
    final MojoExecution mojoExecution = getMojoExecution();

    // execute mojo
    final Set<IProject> result = super.build(kind, monitor);

    // tell m2e builder to refresh generated files
    File generated =
        maven.getMojoParameterValue(project, mojoExecution, "outputDirectory", File.class, monitor);
    if (generated != null) {
      buildContext.refresh(generated);
    }

    return result;
  }
  @Override
  public void execute(FrontendPluginFactory factory) throws TaskRunnerException {
    if (shouldExecute()) {
      factory.getEmberRunner().execute(arguments, environmentVariables);

      if (outputdir != null) {
        getLog().info("Refreshing files after ember: " + outputdir);
        buildContext.refresh(outputdir);
      }
    } else {
      getLog().info("Skipping ember as no modified files in " + srcdir);
    }
  }
Ejemplo n.º 4
0
  List<String> getIncludedFiles(File sourceDirectory, String[] includes, String[] excludes) {
    Scanner scanner = buildContext.newScanner(sourceDirectory, true);
    scanner.setIncludes(includes);
    scanner.setExcludes(excludes);
    scanner.scan();

    String[] includedFiles = scanner.getIncludedFiles();
    for (int i = 0; i < includedFiles.length; i++) {
      includedFiles[i] = new File(scanner.getBasedir(), includedFiles[i]).getAbsolutePath();
    }

    String[] result = new String[includedFiles.length];
    System.arraycopy(includedFiles, 0, result, 0, includedFiles.length);
    return Arrays.asList(result);
  }
  public static String[] getModifiedFiles(
      BuildContext buildContext, File source, String[] includes, String[] excludes)
      throws Exception {
    if ((source == null) || !source.exists()) {
      return null;
    }

    final Scanner ds = buildContext.newScanner(source);

    if ((includes != null) && (includes.length > 0)) {
      ds.setIncludes(includes);
    }

    if ((excludes != null) && (excludes.length > 0)) {
      ds.setExcludes(excludes);
    }

    ds.scan();

    return ds.getIncludedFiles();
  }
Ejemplo n.º 6
0
  public void doExecute() throws MojoExecutionException, MojoFailureException {
    setup();

    // java -cp gwt-dev.jar:gwt-user.jar
    // com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName
    // some.package.MyCssResource -css
    // input.css
    if (cssFiles != null) {
      for (String file : cssFiles) {
        final String typeName =
            FilenameUtils.separatorsToSystem(file)
                .substring(0, file.lastIndexOf('.'))
                .replace(File.separatorChar, '.');
        final File javaOutput =
            new File(getGenerateDirectory(), typeName.replace('.', File.separatorChar) + ".java");
        for (Resource resource : getProject().getResources()) {
          final File candidate = new File(resource.getDirectory(), file);
          if (candidate.exists()) {
            if (buildContext.isUptodate(javaOutput, candidate)) {
              getLog().debug(javaOutput.getAbsolutePath() + " is up to date. Generation skipped");
              break;
            }

            getLog().info("Generating " + javaOutput + " with typeName " + typeName);
            ensureTargetPackageExists(getGenerateDirectory(), typeName);

            try {
              final StringBuilder content = new StringBuilder();
              createJavaCommand()
                  .setMainClass("com.google.gwt.resources.css.InterfaceGenerator")
                  .addToClasspath(getClasspath(Artifact.SCOPE_COMPILE))
                  .arg("-standalone")
                  .arg("-typeName")
                  .arg(typeName)
                  .arg("-css")
                  .arg(candidate.getAbsolutePath())
                  .addToClasspath(getJarFiles(GWT_DEV, false))
                  .addToClasspath(getJarFiles(GWT_USER, false))
                  .setOut(
                      new StreamConsumer() {
                        public void consumeLine(String line) {
                          content.append(line).append(SystemUtils.LINE_SEPARATOR);
                        }
                      })
                  .execute();
              if (content.length() == 0) {
                throw new MojoExecutionException(
                    "cannot generate java source from file " + file + ".");
              }
              final OutputStreamWriter outputWriter =
                  new OutputStreamWriter(buildContext.newFileOutputStream(javaOutput), encoding);
              try {
                outputWriter.write(content.toString());
              } finally {
                IOUtil.close(outputWriter);
              }
            } catch (IOException e) {
              throw new MojoExecutionException("Failed to write to file: " + javaOutput, e);
            } catch (JavaCommandException e) {
              throw new MojoExecutionException(e.getMessage(), e);
            }
            break;
          }
        }
      }
    }
  }
Ejemplo n.º 7
0
  public static void prepareLanguage(
      Log log,
      MavenProject project,
      MavenProjectHelper projectHelper,
      File languageOutDir,
      File schemaOutDir,
      BuildContext buildContext)
      throws MojoExecutionException {

    File camelMetaDir = new File(languageOutDir, "META-INF/services/org/apache/camel/");

    // first we need to setup the output directory because the next check
    // can stop the build before the end and eclipse always needs to know about that directory
    if (projectHelper != null) {
      projectHelper.addResource(
          project,
          languageOutDir.getPath(),
          Collections.singletonList("**/dataformat.properties"),
          Collections.emptyList());
    }

    if (!PackageHelper.haveResourcesChanged(
        log, project, buildContext, "META-INF/services/org/apache/camel/language")) {
      return;
    }

    Map<String, String> javaTypes = new HashMap<String, String>();

    StringBuilder buffer = new StringBuilder();
    int count = 0;
    for (Resource r : project.getBuild().getResources()) {
      File f = new File(r.getDirectory());
      if (!f.exists()) {
        f = new File(project.getBasedir(), r.getDirectory());
      }
      f = new File(f, "META-INF/services/org/apache/camel/language");

      if (f.exists() && f.isDirectory()) {
        File[] files = f.listFiles();
        if (files != null) {
          for (File file : files) {
            String javaType = readClassFromCamelResource(file, buffer, buildContext);
            if (!file.isDirectory() && file.getName().charAt(0) != '.') {
              count++;
            }
            if (javaType != null) {
              javaTypes.put(file.getName(), javaType);
            }
          }
        }
      }
    }

    // find camel-core and grab the data format model from there, and enrich this model with
    // information from this artifact
    // and create json schema model file for this data format
    try {
      if (count > 0) {
        Artifact camelCore = findCamelCoreArtifact(project);
        if (camelCore != null) {
          File core = camelCore.getFile();
          if (core != null) {
            URL url = new URL("file", null, core.getAbsolutePath());
            URLClassLoader loader = new URLClassLoader(new URL[] {url});
            for (Map.Entry<String, String> entry : javaTypes.entrySet()) {
              String name = entry.getKey();
              String javaType = entry.getValue();
              String modelName = asModelName(name);

              InputStream is =
                  loader.getResourceAsStream(
                      "org/apache/camel/model/language/" + modelName + ".json");
              if (is == null) {
                // use file input stream if we build camel-core itself, and thus do not have a JAR
                // which can be loaded by URLClassLoader
                is =
                    new FileInputStream(
                        new File(core, "org/apache/camel/model/language/" + modelName + ".json"));
              }
              String json = loadText(is);
              if (json != null) {
                LanguageModel languageModel = new LanguageModel();
                languageModel.setName(name);
                languageModel.setTitle("");
                languageModel.setModelName(modelName);
                languageModel.setLabel("");
                languageModel.setDescription("");
                languageModel.setJavaType(javaType);
                languageModel.setGroupId(project.getGroupId());
                languageModel.setArtifactId(project.getArtifactId());
                languageModel.setVersion(project.getVersion());

                List<Map<String, String>> rows =
                    JSonSchemaHelper.parseJsonSchema("model", json, false);
                for (Map<String, String> row : rows) {
                  if (row.containsKey("title")) {
                    languageModel.setTitle(row.get("title"));
                  }
                  if (row.containsKey("description")) {
                    languageModel.setDescription(row.get("description"));
                  }
                  if (row.containsKey("label")) {
                    languageModel.setLabel(row.get("label"));
                  }
                  if (row.containsKey("javaType")) {
                    languageModel.setModelJavaType(row.get("javaType"));
                  }
                }
                log.debug("Model " + languageModel);

                // build json schema for the data format
                String properties = after(json, "  \"properties\": {");
                String schema = createParameterJsonSchema(languageModel, properties);
                log.debug("JSon schema\n" + schema);

                // write this to the directory
                File dir = new File(schemaOutDir, schemaSubDirectory(languageModel.getJavaType()));
                dir.mkdirs();

                File out = new File(dir, name + ".json");
                OutputStream fos = buildContext.newFileOutputStream(out);
                fos.write(schema.getBytes());
                fos.close();

                buildContext.refresh(out);

                log.debug("Generated " + out + " containing JSon schema for " + name + " language");
              }
            }
          }
        }
      }
    } catch (Exception e) {
      throw new MojoExecutionException(
          "Error loading language model from camel-core. Reason: " + e, e);
    }

    if (count > 0) {
      Properties properties = new Properties();
      String names = buffer.toString();
      properties.put("languages", names);
      properties.put("groupId", project.getGroupId());
      properties.put("artifactId", project.getArtifactId());
      properties.put("version", project.getVersion());
      properties.put("projectName", project.getName());
      if (project.getDescription() != null) {
        properties.put("projectDescription", project.getDescription());
      }

      camelMetaDir.mkdirs();
      File outFile = new File(camelMetaDir, "language.properties");

      // check if the existing file has the same content, and if so then leave it as is so we do not
      // write any changes
      // which can cause a re-compile of all the source code
      if (outFile.exists()) {
        try {
          Properties existing = new Properties();

          InputStream is = new FileInputStream(outFile);
          existing.load(is);
          is.close();

          // are the content the same?
          if (existing.equals(properties)) {
            log.debug("No language changes detected");
            return;
          }
        } catch (IOException e) {
          // ignore
        }
      }

      try {
        OutputStream os = buildContext.newFileOutputStream(outFile);
        properties.store(os, "Generated by camel-package-maven-plugin");
        os.close();

        log.info(
            "Generated "
                + outFile
                + " containing "
                + count
                + " Camel "
                + (count > 1 ? "languages: " : "language: ")
                + names);

        if (projectHelper != null) {
          projectHelper.attachArtifact(project, "properties", "camelLanguage", outFile);
        }
      } catch (IOException e) {
        throw new MojoExecutionException(
            "Failed to write properties to " + outFile + ". Reason: " + e, e);
      }
    } else {
      log.debug(
          "No META-INF/services/org/apache/camel/language directory found. Are you sure you have created a Camel language?");
    }
  }