public void dotestArtifactExceptions(boolean are, boolean anfe) throws Exception {
    ArtifactItem item = new ArtifactItem();

    item.setArtifactId("artifactId");
    item.setClassifier("");
    item.setGroupId("groupId");
    item.setType("type");
    item.setVersion("1.0");

    List<ArtifactItem> list = new ArrayList<ArtifactItem>();
    list.add(item);
    mojo.setArtifactItems(list);

    // init classifier things
    mojo.setFactory(DependencyTestUtils.getArtifactFactory());
    mojo.setResolver(new StubArtifactResolver(null, are, anfe));
    mojo.setLocal(new StubArtifactRepository(this.testDir.getAbsolutePath()));

    try {
      mojo.execute();
      fail("ExpectedException");
    } catch (MojoExecutionException e) {
      if (are) {
        assertEquals("Unable to resolve artifact.", e.getMessage());
      } else {
        assertEquals("Unable to find artifact.", e.getMessage());
      }
    }
  }
  @Test
  public void test_strict() throws Exception {
    MavenProjectStub project = new MavenProjectStub();

    /*LicenseFormatMojo format = new LicenseFormatMojo();
    format.basedir = new File("src/test/resources/check/issue76");
    format.header = "src/test/resources/test-header1.txt";
    format.project = project;
    format.execute();*/

    // all the headers are by default checked not strictlty
    LicenseCheckMojo check = new LicenseCheckMojo();
    check.basedir = new File("src/test/resources/check/issue76");
    check.header = "src/test/resources/test-header1.txt";
    check.project = project;
    check.strictCheck = false;
    check.execute();

    // all the headers are by default checked not strictlty
    check.strictCheck = true;
    try {
      check.execute();
    } catch (MojoExecutionException e) {
      assertEquals("Some files do not have the expected license header", e.getMessage());
    }
    System.out.println(check.missingHeaders);
    assertEquals(check.missingHeaders.size(), 4);
  }
 public void testNoArtifactItems() {
   try {
     mojo.getProcessedArtifactItems(false);
     fail("Expected Exception");
   } catch (MojoExecutionException e) {
     assertEquals("There are no artifactItems configured.", e.getMessage());
   }
 }
 public void assertMarkerFile(boolean val, ArtifactItem item) {
   UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler(item, mojo.getMarkersDirectory());
   try {
     assertEquals(val, handle.isMarkerSet());
   } catch (MojoExecutionException e) {
     fail(e.getLongMessage());
   }
 }
  @Test
  public void should_fail_if_io_error_occurs_when_reading_cql_script() {
    CqlExecCassandraMojo cqlExecCassandraMojo = builder.cqlScript(file("emptyfile.cql")).build();
    mockToThrows(new IOException());

    try {
      cqlExecCassandraMojo.execute();
      fail();
    } catch (MojoExecutionException e) {
      assertEquals("Could not parse or load cql file", e.getMessage());
    } catch (MojoFailureException e) {
      fail(e.getMessage());
    }
  }
 /**
  * List the dependencies needed for compilation, those dependencies are used to get the include
  * paths needed for compilation and to get the libraries paths and names needed for linking.
  */
 @Override
 protected List<Artifact> getArtifacts() {
   try {
     final List<String> scopes = new ArrayList<String>();
     scopes.add(Artifact.SCOPE_COMPILE);
     scopes.add(Artifact.SCOPE_PROVIDED);
     // scopes.add(Artifact.SCOPE_RUNTIME);
     scopes.add(Artifact.SCOPE_SYSTEM);
     // scopes.add(Artifact.SCOPE_TEST);
     return getNarManager().getDependencies(scopes);
   } catch (final MojoExecutionException e) {
     e.printStackTrace();
   } catch (final MojoFailureException e) {
     e.printStackTrace();
   }
   return Collections.EMPTY_LIST;
 }
  @Test
  public void should_fail_if_file_not_found_occurs_when_reading_cql_script() {
    CqlExecCassandraMojo cqlExecCassandraMojo = builder.cqlScript(file("emptyfile.cql")).build();
    mockToThrows(new FileNotFoundException());

    try {
      cqlExecCassandraMojo.execute();
      fail();
    } catch (MojoExecutionException e) {
      assertThat(
          e.getMessage(),
          allOf(
              startsWith("Cql file '"),
              endsWith("emptyfile.cql' was deleted before I could read it")));
    } catch (MojoFailureException e) {
      fail(e.getMessage());
    }
  }
  @Test
  public void should_fail_when_request_fails() {
    CqlExecCassandraMojo cqlExecCassandraMojo = builder.cqlStatement(CQL_STATEMENT).build();
    mockThriftExecutionWith(
        new ThrowsException(
            new ThriftApiExecutionException(new InvalidRequestException("bad statement"))));

    try {
      cqlExecCassandraMojo.execute();
      fail();
    } catch (MojoExecutionException e) {
      assertEquals(
          "There was a problem calling Apache Cassandra's Thrift API. Details: The request was not properly formatted bad statement",
          e.getMessage());
    } catch (MojoFailureException e) {
      fail(e.getMessage());
    }
  }
Example #9
0
  /** @param xstreamObject not null */
  private void addAlias(XStream xstreamObject) {
    try {
      addAlias(xstreamObject, getMavenModelJarFile(), "org.apache.maven.model");
      addAlias(xstreamObject, getMavenSettingsJarFile(), "org.apache.maven.settings");
    } catch (MojoExecutionException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("MojoExecutionException: " + e.getMessage(), e);
      }
    } catch (ArtifactResolutionException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("ArtifactResolutionException: " + e.getMessage(), e);
      }
    } catch (ArtifactNotFoundException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("ArtifactNotFoundException: " + e.getMessage(), e);
      }
    } catch (ProjectBuildingException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("ProjectBuildingException: " + e.getMessage(), e);
      }
    }

    // TODO need to handle specific Maven objects like DefaultArtifact?
  }
  /**
   * @throws MojoExecutionException
   * @throws MojoFailureException
   */
  public void execute() throws MojoExecutionException, MojoFailureException {
    try {
      // Validate the NDK
      final File ndkBuildFile = new File(getAndroidNdk().getNdkBuildPath());
      NativeHelper.validateNDKVersion(ndkBuildFile.getParentFile());

      // Validate the makefile - if our packaging type is so (for example) and there are
      // dependencies on .a files (or shared files for that matter) the makefile should include
      // the include of our Android Maven plugin generated makefile.
      validateMakefile(project, makefile);

      String[] ndkArchitectures =
          getAndroidNdk()
              .getNdkArchitectures(
                  ndkClassifier, ndkArchitecture, applicationMakefile, project.getBasedir());
      for (String ndkArchitecture : ndkArchitectures) {
        Preparation preparation = new Preparation().invoke(ndkArchitecture);
        boolean libsDirectoryExists = preparation.isLibsDirectoryExists();
        File directoryToRemove = preparation.getDirectoryToRemove();

        // Start setting up the command line to be executed
        final CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
        // Add an error listener to the build - this allows the build to conditionally fail
        // depending on a) the output of the build b) whether or not build errors (output on stderr)
        // should be
        // ignored and c) whether the pattern matches or not
        executor.setErrorListener(getNdkErrorListener());

        final Set<Artifact> nativeLibraryArtifacts = findNativeLibraryDependencies();

        // If there are any static libraries the code needs to link to, include those in the make
        // file
        final Set<Artifact> resolveNativeLibraryArtifacts =
            AetherHelper.resolveArtifacts(
                nativeLibraryArtifacts, repoSystem, repoSession, projectRepos);
        if (getLog().isDebugEnabled()) {
          getLog()
              .debug(
                  "resolveArtifacts found "
                      + resolveNativeLibraryArtifacts.size()
                      + ": "
                      + resolveNativeLibraryArtifacts.toString());
        }

        final File makefileDir = new File(project.getBuild().getDirectory(), NDK_MAKFILE_DIRECTORY);
        makefileDir.mkdirs();
        final File androidMavenMakefile = new File(makefileDir, "android_maven_plugin_makefile.mk");

        // set the ndk build directory
        if (ndkBuildDirectory == null) {
          ndkBuildDirectory = project.getBasedir().getAbsolutePath();
        }

        final MakefileHelper makefileHelper =
            new MakefileHelper(
                getLog(), repoSystem, repoSession, projectRepos, unpackedApkLibsDirectory);
        final MakefileHelper.MakefileHolder makefileHolder =
            makefileHelper.createMakefileFromArtifacts(
                new File(ndkBuildDirectory),
                resolveNativeLibraryArtifacts,
                ndkArchitecture,
                useHeaderArchives);
        IOUtil.copy(makefileHolder.getMakeFile(), new FileOutputStream(androidMavenMakefile));

        // Add the path to the generated makefile - this is picked up by the build (by an include
        // from the user)
        executor.addEnvironment(
            "ANDROID_MAVEN_PLUGIN_MAKEFILE", androidMavenMakefile.getAbsolutePath());

        setupNativeLibraryEnvironment(
            makefileHelper, executor, resolveNativeLibraryArtifacts, ndkArchitecture);

        // Adds the location of the Makefile capturer file - this file will after the build include
        // things like header files, flags etc.  It is processed after the build to retrieve the
        // headers
        // and also capture flags etc ...
        final File makefileCaptureFile =
            File.createTempFile("android_maven_plugin_makefile_captures", ".tmp");
        makefileCaptureFile.deleteOnExit();
        executor.addEnvironment(
            MakefileHelper.MAKEFILE_CAPTURE_FILE, makefileCaptureFile.getAbsolutePath());

        // Add any defined system properties
        if (systemProperties != null && !systemProperties.isEmpty()) {
          for (Map.Entry<String, String> entry : systemProperties.entrySet()) {
            executor.addEnvironment(entry.getKey(), entry.getValue());
          }
        }
        executor.setLogger(this.getLog());
        // Setup the command line for the make
        final List<String> commands = new ArrayList<String>();
        // Setup the build directory (defaults to the current directory) but may be different
        // depending
        // on user configuration
        commands.add("-C");
        commands.add(ndkBuildDirectory);

        // If the build should use a custom makefile or not - some validation is done to ensure
        // this exists and all
        if (makefile != null) {
          File makeFile = new File(project.getBasedir(), makefile);
          if (!makeFile.exists()) {
            getLog().error("Specified makefile " + makeFile + " does not exist");
            throw new MojoExecutionException("Specified makefile " + makeFile + " does not exist");
          }
          commands.add("-f");
          commands.add(makefile);
        }

        configureApplicationMakefile(commands);
        configureMaxJobs(commands);
        configureNdkToolchain(commands);

        // Anything else on the command line the user wants to add - simply splice it up and
        // add it one by one to the command line
        if (ndkBuildAdditionalCommandline != null) {
          String[] additionalCommands = ndkBuildAdditionalCommandline.split(" ");
          for (final String command : additionalCommands) {
            commands.add(command);
          }
        }
        // If a build target is specified, tag that onto the command line as the
        // very last of the parameters
        if (target != null) {
          commands.add(target);
        } else /*if ( "a".equals( project.getPackaging() ) )*/ {
          commands.add(project.getArtifactId());
        }

        final String ndkBuildPath = resolveNdkBuildExecutable();
        getLog().info(ndkBuildPath + " " + commands.toString());

        executor.executeCommand(ndkBuildPath, commands, project.getBasedir(), true);

        cleanUp(
            preparation.getNativeLibDirectory(),
            ndkArchitecture,
            libsDirectoryExists,
            directoryToRemove,
            makefileHolder,
            makefileCaptureFile);
      }
    } catch (MojoExecutionException e) {
      getLog().error("Error during build: " + e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      getLog().error("Error while executing: " + e.getMessage());
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  public boolean mojo(List<String> args, MOJO_VARIANTS variant) {
    boolean success = false;
    try {
      File pom = new File(folder.getPath() + File.separator + "pom.xml");
      if (!pom.exists()) {
        success = streamMockPOM(pom, model.getName());
      }

      MavenProject mp = new MavenProject();

      final Hyperjaxb3Mojo mojo = new Hyperjaxb3Mojo();
      mojo.setVerbose(true);

      mojo.setBindingDirectory(getMetaInfDir());
      mojo.setSchemaDirectory(getMetaInfDir());

      int j = 0;
      String[] excludedSchemas = new String[preexistingSchemas.size()];
      for (File f : preexistingSchemas) {
        excludedSchemas[j++] = f.getName();
      }
      mojo.setSchemaExcludes(excludedSchemas);

      int k = 0;
      String[] excludedBindings = new String[preesistingBindings.size()];
      for (File f : preesistingBindings) {
        excludedBindings[k++] = f.getName();
      }
      mojo.setBindingExcludes(excludedBindings);

      mojo.setGenerateDirectory(getXjcDir());
      mojo.setExtension(true);
      mojo.variant = variant.getLabel();

      File perx =
          new File(
              getBinDir().getPath()
                  + File.separator
                  + "META-INF"
                  + File.separator
                  + "persistence.xml");
      if (perx.exists()) {
        mojo.persistenceXml = perx;
        try {
          Document dox = parseXML(perx);

          XPath xpath = XPathFactory.newInstance().newXPath();
          XPathExpression expr = xpath.compile("//persistence-unit/@name");

          mojo.persistenceUnitName = (String) expr.evaluate(dox, XPathConstants.STRING);

        } catch (Exception e) {
          mojo.persistenceXml =
              new File(getMetaInfDir() + File.separator + "persistence-template-hibernate.xml");
          mojo.persistenceUnitName = model.getName();
        }
      } else {
        mojo.persistenceXml =
            new File(getMetaInfDir() + File.separator + "persistence-template-hibernate.xml");
        mojo.persistenceUnitName = model.getName();
      }

      mojo.generateEquals = false;
      mojo.generateHashCode = false;
      mojo.setProject(mp);

      mojo.setArgs(args);

      mojo.setForceRegenerate(true);
      mojo.execute();
      success = true;
    } catch (MojoExecutionException e) {
      e.printStackTrace();
    }
    return success;
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    initMojo();
    getLog().info("Scanning: " + magentoPath);
    getLog().info("");
    if (mVersion != null) {
      getLog().info("Version: Magento " + mVersion.toString());
    }

    // parse sql properties from local.xml
    final Path localXmlPath = Paths.get(magentoPath + "/app/etc/local.xml");
    Document localXml = null;
    if (Files.exists(localXmlPath)) {
      localXml = MagentoXmlUtil.readXmlFile(localXmlPath.toAbsolutePath().toString());
    } else {
      throw new MojoExecutionException(
          "Could not read or parse /app/etc/local.xml."
              + " Use -DmagentoPath= to set Magento dir.");
    }
    final Map<String, String> dbSettings = MagentoXmlUtil.getDbValues(localXml);
    final String jdbcUrl =
        MagentoSqlUtil.getJdbcUrl(
            dbSettings.get("host"), dbSettings.get("port"), dbSettings.get("dbname"));

    // fetch installdate
    final String magentoInstallDate = MagentoXmlUtil.getMagentoInstallData(localXml);
    getLog().info("Installed: " + magentoInstallDate);
    getLog().info("");

    // read baseUrl
    MagentoCoreConfig baseUrl = null;
    try {
      baseUrl = new MagentoCoreConfig("web/unsecure/base_url");
    } catch (Exception e) {
      throw new MojoExecutionException("Error creating config entry. " + e.getMessage(), e);
    }

    String sqlError = SQL_CONNECTION_VALID;
    try {
      baseUrl =
          MagentoSqlUtil.getCoreConfigData(
              baseUrl, dbSettings.get("user"), dbSettings.get("password"), jdbcUrl, getLog());
      getLog().info("URL: " + baseUrl.getValue());
      getLog().info("");
    } catch (MojoExecutionException e) {
      sqlError = e.getMessage();
    }

    getLog()
        .info(
            "Database: "
                + dbSettings.get("dbname")
                + " via "
                + dbSettings.get("user")
                + "@"
                + dbSettings.get("host")
                + ":"
                + dbSettings.get("port"));
    getLog().info("Connection: " + sqlError);
    getLog().info("");

    if (!skipSize) {
      MutableLong rootSizeTotal = new MutableLong();
      try {
        FileSizeVisitor fs = new FileSizeVisitor(rootSizeTotal);
        Files.walkFileTree(Paths.get(magentoPath), fs);
      } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
      }
      getLog()
          .info(
              "Magento files total: "
                  + String.format("%,8d", rootSizeTotal.toLong()).trim()
                  + " bytes");
      if (SQL_CONNECTION_VALID.equals(sqlError)) {
        try {
          final Map<String, Integer> dbDetails =
              MagentoSqlUtil.getDbSize(
                  dbSettings.get("dbname"),
                  dbSettings.get("user"),
                  dbSettings.get("password"),
                  jdbcUrl,
                  getLog());
          final List<MysqlTable> logTableDetails =
              MagentoSqlUtil.getLogTablesSize(
                  dbSettings.get("dbname"),
                  dbSettings.get("user"),
                  dbSettings.get("password"),
                  jdbcUrl,
                  getLog());
          getLog()
              .info(
                  "Database total: "
                      + String.format("%,8d", dbDetails.get("totalRows")).trim()
                      + " entries / "
                      + String.format("%,8d", dbDetails.get("totalSize")).trim()
                      + "mb");
          int logSizeTotal = 0;
          int logRowsTotal = 0;
          for (MysqlTable t : logTableDetails) {
            logSizeTotal += t.getTableSizeInMb();
            logRowsTotal += t.getTableRows();
            if (showDetails) {
              getLog()
                  .info(
                      " "
                          + t.getTableName()
                          + ": "
                          + t.getFormatedTableEntries()
                          + " entries / "
                          + t.getFormatedTableSizeInMb()
                          + "mb");
            }
          }
          getLog()
              .info(
                  "Log tables total: "
                      + String.format("%,8d", logRowsTotal).trim()
                      + " entries / "
                      + String.format("%,8d", logSizeTotal).trim()
                      + "mb");
        } catch (MojoExecutionException e) {
          getLog().info("Error: " + e.getMessage());
        }
      }
      getLog().info("");
    }
    // parse modules
    final Path modulesXmlPath = Paths.get(magentoPath + "/app/etc/modules");
    if (!Files.exists(modulesXmlPath)) {
      throw new MojoExecutionException("Could not find /app/etc/modules directory.");
    }

    DirectoryStream<Path> files = null;
    final ArrayList<MagentoModule> localModules = new ArrayList<MagentoModule>();
    final ArrayList<MagentoModule> communityModules = new ArrayList<MagentoModule>();
    try {
      files = Files.newDirectoryStream(modulesXmlPath);
      for (Path path : files) {
        if (!path.getFileName().toString().startsWith("Mage")) {
          MagentoModule m = new MagentoModule(path);
          if (m.getCodePool().equals("local")) {
            localModules.add(m);
          } else {
            communityModules.add(m);
          }
        }
      }
    } catch (IOException e) {
      throw new MojoExecutionException("Could not read modules directory. " + e.getMessage(), e);
    } finally {
      try {
        files.close();
      } catch (IOException e) {
        throw new MojoExecutionException("Error closing directory stream. " + e.getMessage(), e);
      }
    }

    // print module sorted module list
    final MagentoModuleComperator mmc = new MagentoModuleComperator();
    Collections.sort(localModules, mmc);
    Collections.sort(communityModules, mmc);

    getLog().info("Installed modules in..");

    getLog().info("..local: ");
    for (MagentoModule m : localModules) {
      getLog()
          .info(
              m.getNamespace()
                  + "_"
                  + m.getName()
                  + " version: "
                  + m.getVersion()
                  + " active: "
                  + m.isActive());
    }
    if (localModules.size() == 0) {
      getLog().info("--none--");
    }
    getLog().info("");

    getLog().info("..community: ");
    for (MagentoModule m : communityModules) {
      getLog()
          .info(
              m.getNamespace()
                  + "_"
                  + m.getName()
                  + " version: "
                  + m.getVersion()
                  + " active: "
                  + m.isActive());
    }
    if (communityModules.size() == 0) {
      getLog().info("--none--");
    }
    getLog().info("");

    // check local overlays for content
    getLog().info("Overlay status..");
    int fileCount = -1;
    final File localMage = new File(magentoPath + "/app/code/local/Mage");
    if (localMage.exists()) {
      fileCount = localMage.list().length;
      if (fileCount > 0) {
        getLog().info("local/Mage: " + localMage.list().length + " file(s)");
      }
    }
    final File localVarien = new File(magentoPath + "/app/code/local/Varien");

    if (localVarien.exists()) {
      fileCount = localVarien.list().length;
      if (fileCount > 0) {
        getLog().info("local/Varien: " + localVarien.list().length + " file(s)");
      }
    }

    if (fileCount == -1) {
      getLog().info("..not in use.");
    }
  }