Java Code Examples for org.codehaus.plexus.util.DirectoryScanner#setIncludes()

The following examples show how to use org.codehaus.plexus.util.DirectoryScanner#setIncludes() . 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: AbstractRunMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private File lookForConfiguration(String filename) {
    File confBaseDir = new File(project.getBasedir(), DEFAULT_CONF_DIR);
    if (!confBaseDir.isDirectory()) {
        return null;
    }
    DirectoryScanner directoryScanner = new DirectoryScanner();
    directoryScanner.setBasedir(confBaseDir);
    String[] includes = Stream.concat(Stream.of(JSON_EXTENSION), YAML_EXTENSIONS.stream())
        .map(ext -> filename + ext)
        .toArray(String[]::new);
    directoryScanner.setIncludes(includes);
    directoryScanner.scan();
    return Arrays.stream(directoryScanner.getIncludedFiles())
        .map(found -> new File(confBaseDir, found))
        .findFirst()
        .orElse(null);
}
 
Example 2
Source File: ProjectScanner.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of packages from {@literal src/main/java}. This method scans for ".class" files in {@literal
 * target/classes}.
 *
 * @return the list of packages, empty if none.
 */
public Set<String> getPackagesFromMainSources() {
    Set<String> packages = new LinkedHashSet<>();
    File classes = getClassesDirectory();
    if (classes.isDirectory()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(classes);
        scanner.setIncludes(new String[]{"**/*.class"});
        scanner.addDefaultExcludes();
        scanner.scan();

        for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
            packages.add(Packages.getPackageName(scanner.getIncludedFiles()[i]));
        }
    }

    return packages;
}
 
Example 3
Source File: AbstractImpSortMojo.java    From impsort-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Stream<File> searchDir(File dir, boolean warnOnBadDir) {
  if (dir == null || !dir.exists() || !dir.isDirectory()) {
    if (warnOnBadDir && dir != null) {
      getLog().warn("Directory does not exist or is not a directory: " + dir);
    }
    return Stream.empty();
  }
  getLog().debug("Adding directory " + dir);
  DirectoryScanner ds = new DirectoryScanner();
  ds.setBasedir(dir);
  ds.setIncludes(includes != null && includes.length > 0 ? includes : DEFAULT_INCLUDES);
  ds.setExcludes(excludes);
  ds.addDefaultExcludes();
  ds.setCaseSensitive(false);
  ds.setFollowSymlinks(false);
  ds.scan();
  return Stream.of(ds.getIncludedFiles()).map(filename -> new File(dir, filename)).parallel();
}
 
Example 4
Source File: FormatterMojo.java    From formatter-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Add source files to the files list.
 *
 */
List<File> addCollectionFiles(File newBasedir) {
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(newBasedir);
    if (this.includes != null && this.includes.length > 0) {
        ds.setIncludes(this.includes);
    } else {
        ds.setIncludes(DEFAULT_INCLUDES);
    }

    ds.setExcludes(this.excludes);
    ds.addDefaultExcludes();
    ds.setCaseSensitive(false);
    ds.setFollowSymlinks(false);
    ds.scan();

    List<File> foundFiles = new ArrayList<>();
    for (String filename : ds.getIncludedFiles()) {
        foundFiles.add(new File(newBasedir, filename));
    }
    return foundFiles;
}
 
Example 5
Source File: CreateApplicationBundleMojo.java    From appbundle-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Scan a fileset and get a list of files which it contains.
 *
 * @param fileset
 * @return list of files contained within a fileset.
 * @throws FileNotFoundException
 */
private List<String> scanFileSet(File sourceDirectory, FileSet fileSet) {
    final String[] emptyStringArray = {};

    DirectoryScanner scanner = new DirectoryScanner();

    scanner.setBasedir(sourceDirectory);
    if (fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty()) {
        scanner.setIncludes(fileSet.getIncludes().toArray(emptyStringArray));
    } else {
        scanner.setIncludes(DEFAULT_INCLUDES);
    }

    if (fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty()) {
        scanner.setExcludes(fileSet.getExcludes().toArray(emptyStringArray));
    }

    if (fileSet.isUseDefaultExcludes()) {
        scanner.addDefaultExcludes();
    }

    scanner.scan();

    return Arrays.asList(scanner.getIncludedFiles());
}
 
Example 6
Source File: FormatMojo.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private List<File> scan(File directory) {
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(directory);
	scanner.setIncludes(hasLength(this.includes) ? this.includes : DEFAULT_INCLUDES);
	scanner.setExcludes(this.excludes);
	scanner.addDefaultExcludes();
	scanner.setCaseSensitive(false);
	scanner.setFollowSymlinks(false);
	scanner.scan();
	return Arrays.asList(scanner.getIncludedFiles()).stream().map(name -> new File(directory, name))
			.collect(Collectors.toList());
}
 
Example 7
Source File: TcasesMojoTest.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 8
Source File: ApiTestMojoTest.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 9
Source File: GitHub.java    From opoopress with Apache License 2.0 5 votes vote down vote up
/**
 * Get matching paths found in given base directory
 *
 * @param includes
 * @param excludes
 * @param baseDir
 * @return non-null but possibly empty array of string paths relative to the
 *         base directory
 */
public static String[] getMatchingPaths(final String[] includes,
		final String[] excludes, final String baseDir) {
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(baseDir);
	if (includes != null && includes.length > 0){
		scanner.setIncludes(includes);
	}
	if (excludes != null && excludes.length > 0){
		scanner.setExcludes(excludes);
	}
	scanner.scan();
	return scanner.getIncludedFiles();
}
 
Example 10
Source File: AbstractXmlMojo.java    From xml-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Scans a directory for files and returns a set of path names.
 */
protected String[] getFileNames( File pDir, String[] pIncludes, String[] pExcludes )
    throws MojoFailureException, MojoExecutionException
{
    if ( pDir == null )
    {
        throw new MojoFailureException( "A ValidationSet or TransformationSet"
            + " requires a nonempty 'dir' child element." );
    }
    final File dir = asAbsoluteFile( pDir );
    if ( !dir.isDirectory() )
    {
        throw new MojoExecutionException("The directory " + dir.getPath()
            + ", which is a base directory of a ValidationSet or TransformationSet, does not exist.");
    }
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir( dir );
    if ( pIncludes != null && pIncludes.length > 0 )
    {
        ds.setIncludes( pIncludes );
    }
    if ( pExcludes != null && pExcludes.length > 0 )
    {
        ds.setExcludes( pExcludes );
    }
    ds.scan();
    return ds.getIncludedFiles();
}
 
Example 11
Source File: ExecutionChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void executionResult(RunConfig config, ExecutionContext res, int resultCode) {

    if (NbmActionGoalProvider.NBMRELOAD.equals(config.getActionName()) && resultCode == 0) {
        DirectoryScanner scanner = new DirectoryScanner();
        NbMavenProject prj = project.getLookup().lookup(NbMavenProject.class);
        File basedir = new File(prj.getMavenProject().getBuild().getDirectory(), "nbm"); //NOI18N
        scanner.setBasedir(basedir);
        scanner.setIncludes(new String[]{
                    "**/modules/*.jar", //NOI18N
                    "**/modules/eager/*.jar", //NOI18N
                    "**/modules/autoload/*.jar" //NOI18N
                });
        scanner.scan();
        String[] incl = scanner.getIncludedFiles();
        if (incl != null && incl.length > 0) {
            if (incl[0].indexOf("eager") > -1 || incl[0].indexOf("autoload") > -1) { //NOI18N
                res.getInputOutput().getErr().println("NetBeans: Cannot reload 'autoload' or 'eager' modules.");
            }
            try {
                res.getInputOutput().getOut().println("NetBeans: Deploying NBM module in development IDE...");
                TestModuleDeployer.deployTestModule(FileUtil.normalizeFile(new File(basedir, incl[0])));
            } catch (IOException ex) {
                res.getInputOutput().getOut().println("NetBeans: Error redeploying NBM module in development IDE.");
                Logger.getLogger(ExecutionChecker.class.getName()).log(Level.INFO, "Error reloading netbeans module in development IDE.", ex); //NOI18N
            }
        } else {
            res.getInputOutput().getErr().println("NetBeans: Cannot find any built NetBeans Module artifacts for reload.");
        }

    }
}
 
Example 12
Source File: ReducerMojoTest.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 13
Source File: MainClassesCoSSkipper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean skip(RunConfig config, boolean includingTests, long timeStamp) {
    if (includingTests) {
        if (!RunUtils.hasApplicationCompileOnSaveEnabled(config) && RunUtils.hasTestCompileOnSaveEnabled(config)) {
            //in case when only tests are enabled for CoS, the main source root is not compiled on the fly.
            // we need to checkif something was changed there and if so, recompile manually.
            
            //TODO is there a way to figure if there is a modified java file in a simpler way?
            File dirFile = FileUtilities.convertStringToFile(config.getMavenProject().getBuild().getSourceDirectory());
            if (dirFile == null || !dirFile.exists()) { //#223461
                return false;
            }
            DirectoryScanner ds = new DirectoryScanner();
            ds.setBasedir(dirFile);
            //includes/excludes
            ds.setIncludes(new String[]{"**/*.java"});
            ds.addDefaultExcludes();
            ds.scan();
            String[] inclds = ds.getIncludedFiles();
            for (String inc : inclds) {
                File f = new File(dirFile, inc);
                if (f.lastModified() >= timeStamp) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 14
Source File: NativeSources.java    From maven-native with MIT License 4 votes vote down vote up
public List<File> getFiles()
{
    String[] filePaths = new String[0];

    if ( includes != null || excludes != null )
    {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir( this.directory );
        scanner.setIncludes( includes );
        scanner.setExcludes( excludes );
        scanner.addDefaultExcludes();

        scanner.scan();

        filePaths = scanner.getIncludedFiles();
    }

    List<File> files = new ArrayList<>( filePaths.length + this.fileNames.length );
    for ( int i = 0; i < filePaths.length; ++i )
    {
        files.add( new File( this.directory, filePaths[i] ) );
    }

    // remove duplicate files
    for ( int i = 0; i < this.fileNames.length; ++i )
    {
        File file = new File( this.directory, this.fileNames[i] );

        boolean found = false;

        for ( int k = 0; k < filePaths.length; ++k )
        {
            if ( files.get( k ).equals( file ) )
            {
                found = true;
                break;
            }
        }

        if ( !found )
        {
            files.add( file );
        }
    }

    return files;

}
 
Example 15
Source File: AggregateJsMojo.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void doExecute() throws Exception {
  // build scanner to find files to aggregate
  DirectoryScanner files = new DirectoryScanner();
  files.setBasedir(sourceDirectory);
  if (includes == null || includes.length == 0) {
    files.setIncludes(DEFAULT_INCLUDES);
  }
  else {
    files.setIncludes(includes);
  }
  files.setExcludes(excludes);
  files.addDefaultExcludes();

  // build the list of ordered classes to include
  ClassDefScanner scanner = new ClassDefScanner(getLog());
  scanner.setWarnings(warnings);
  if (namespace == null) {
    getLog().warn("Namespace is not configured; will be unable to detect and resolve MVC references");
  }
  else {
    scanner.setNamespace(namespace);
  }
  List<ClassDef> classes = scanner.scan(files);

  // aggregate all class sources
  getLog().info("Writing: " + outputFile);
  Writer output = new BufferedWriter(new FileWriter(outputFile));
  try {
    FileAppender appender;
    if (omit) {
      appender = new OmissionFileAppender(getLog(), output, omitFlags);
    }
    else {
      appender = new FileAppender(getLog(), output);
    }

    for (ClassDef def : classes) {
      appender.append(def.getSource());
    }
  }
  finally {
    output.close();
  }
}
 
Example 16
Source File: JCasGenMojoTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void test(String projectName, String... types) throws Exception {

    File projectSourceDirectory = getTestFile("src/test/resources/" + projectName);
    File projectDirectory = getTestFile("target/project-" + projectName + "-test");

    // Stage project to target folder
    FileUtils.copyDirectoryStructure(projectSourceDirectory, projectDirectory);
    
    File pomFile = new File(projectDirectory, "/pom.xml");
    assertNotNull(pomFile);
    assertTrue(pomFile.exists());

    // create the MavenProject from the pom.xml file
    MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
    ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
    assertNotNull(project);

    // copy resources
    File source = new File(projectDirectory, "src/main/resources");
    if (source.exists()) {
      FileUtils.copyDirectoryStructure(source, new File(project.getBuild().getOutputDirectory()));
    }
    
    // load the Mojo
    JCasGenMojo generate = (JCasGenMojo) this.lookupConfiguredMojo(project, "generate");
    assertNotNull(generate);

    // set the MavenProject on the Mojo (AbstractMojoTestCase does not do this by default)
    setVariableValueToObject(generate, "project", project);

    // execute the Mojo
    generate.execute();

    // check that the Java files have been generated
    File jCasGenDirectory = new File(project.getBasedir(), "target/generated-sources/jcasgen");
    
    // Record all the files that were generated
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(jCasGenDirectory);
    ds.setIncludes(new String[] { "**/*.java" });
    ds.scan();
    List<File> files = new ArrayList<>();
    for (String scannedFile : ds.getIncludedFiles()) {
      files.add(new File(ds.getBasedir(), scannedFile));
    }
    
    for (String type : types) {
      File wrapperFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + ".java");
      // no _type files in v3
//      File typeFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + "_Type.java");
      
      Assert.assertTrue(files.contains(wrapperFile));
      // no _type files in v3
//      Assert.assertTrue(files.contains(typeFile));
      
      files.remove(wrapperFile);
//      files.remove(typeFile);
    }
    
    // check that no extra files were generated
    Assert.assertTrue(files.isEmpty());

    // check that the generated sources are on the compile path
    Assert.assertTrue(project.getCompileSourceRoots().contains(jCasGenDirectory.getAbsolutePath()));
  }
 
Example 17
Source File: RequireEncoding.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
public void execute( EnforcerRuleHelper helper )
    throws EnforcerRuleException
{
    try
    {
        if ( StringUtils.isBlank( encoding ) )
        {
            encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" );
        }
        Log log = helper.getLog();

        Set< String > acceptedEncodings = new HashSet< String >( Arrays.asList( encoding ) );
        if ( encoding.equals( StandardCharsets.US_ASCII.name() ) )
        {
            log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" );
        }

        if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals( StandardCharsets.UTF_8.name() ) ) )
        {
            acceptedEncodings.add( StandardCharsets.US_ASCII.name() );
        }

        String basedir = (String) helper.evaluate( "${basedir}" );
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir( basedir );
        if ( StringUtils.isNotBlank( includes ) )
        {
            ds.setIncludes( includes.split( "[,\\|]" ) );
        }
        if ( StringUtils.isNotBlank( excludes ) )
        {
            ds.setExcludes( excludes.split( "[,\\|]" ) );
        }
        if ( useDefaultExcludes )
        {
            ds.addDefaultExcludes();
        }
        ds.scan();
        StringBuilder filesInMsg = new StringBuilder();
        for ( String file : ds.getIncludedFiles() )
        {
            String fileEncoding = getEncoding( encoding, new File( basedir, file ), log );
            if ( log.isDebugEnabled() )
            {
                log.debug( file + "==>" + fileEncoding );
            }
            if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) )
            {
                filesInMsg.append( file );
                filesInMsg.append( "==>" );
                filesInMsg.append( fileEncoding );
                filesInMsg.append( "\n" );
                if ( failFast )
                {
                    throw new EnforcerRuleException( filesInMsg.toString() );
                }
            }
        }
        if ( filesInMsg.length() > 0 )
        {
            throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg );
        }
    }
    catch ( IOException ex )
    {
        throw new EnforcerRuleException( "Reading Files", ex );
    }
    catch ( ExpressionEvaluationException e )
    {
        throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
    }
}
 
Example 18
Source File: ApiMojo.java    From tcases with MIT License 4 votes vote down vote up
public void execute() throws MojoExecutionException
{
try
  {
  // Gather API spec files
  DirectoryScanner inputScanner = new DirectoryScanner();
  Set<String> apiDefPatterns = getApiDefs();
  if( !apiDefPatterns.isEmpty())
    {
    // Use all specified API spec patterns.
    }
  else if( !StringUtils.isBlank( getProject()))
    {
    // Use API spec(s) for specified project name.
    apiDefPatterns.add( "**/" + getProject() + ".json");
    apiDefPatterns.add( "**/" + getProject() + ".yaml");
    apiDefPatterns.add( "**/" + getProject() + ".yml");
    }
  else if( !StringUtils.isBlank( getApiDef())) 
    {
    // Use specified API spec pattern.
    apiDefPatterns.add( getApiDef());
    }
  else
    {
    // Use default patterns
    apiDefPatterns.add( "**/*.json");
    apiDefPatterns.add( "**/*.yaml");
    apiDefPatterns.add( "**/*.yml");
    }
  inputScanner.setIncludes( apiDefPatterns.toArray( new String[0]));

  File inputRootDir = getInputDirFile();
  inputScanner.setBasedir( inputRootDir);
  inputScanner.scan();

  // Generate requested models for each API spec
  String[] apiDefs = inputScanner.getIncludedFiles();
  for( int i = 0; i < apiDefs.length; i++)
    {
    // Define input path for this API spec.
    String inputFile = apiDefs[i];
    File apiDef = new File( inputRootDir, inputFile);

    // Set generator options for this API spec.
    Options options = new Options();
    options.setApiSpec( apiDef);
    options.setContentType( getContentType());
    options.setOutDir( new File( getOutDirFile(), getPath( inputFile)));
    if( isJunit())
      {
      options.setTransformType( TransformType.JUNIT);
      }
    if( isHtml())
      {
      options.setTransformType( TransformType.HTML);
      }
    if( getTransformDef() != null)
      {
      options.setTransformType( TransformType.CUSTOM);
      options.setTransformParams( getTransformParams());
      }
    options.setTests( !isInputModels());
    options.setOnModellingCondition( "log".equals( getOnModellingCondition())? getOnCondition() : getOnModellingCondition());
    options.setReadOnlyEnforced( isReadOnlyEnforced());
    options.setWriteOnlyEnforced( isWriteOnlyEnforced());
    
    // Generate requested request test models for this API spec
    if( isRequestCases())
      {
      options.setRequestCases( true);
      options.setOnResolverCondition( getOnResolverCondition());
      options.setMaxTries( getMaxTries());
      options.setRandomSeed( getRandom());
      }
    else
      {
      options.setServerTest( true);
      options.setTransformDef( resolveTransformDefFile( apiDef, options.isServerTest()));
      options.setOutFile( resolveTransformOutFile( apiDef, options.isServerTest()));
      }
    ApiCommand.run( options);

    // Generate requested response test models for this API spec
    options.setServerTest( false);
    options.setTransformDef( resolveTransformDefFile( apiDef, options.isServerTest()));
    options.setOutFile( resolveTransformOutFile( apiDef, options.isServerTest()));
    ApiCommand.run( options);
    }
  }
catch( Exception e)
  {
  throw new MojoExecutionException( "Can't generate requested models", e);
  }
}
 
Example 19
Source File: ApiTestMojo.java    From tcases with MIT License 4 votes vote down vote up
public void execute() throws MojoExecutionException
{
try
  {
  // Gather API spec files
  DirectoryScanner inputScanner = new DirectoryScanner();
  Set<String> apiDefPatterns = getApiDefs();
  if( !apiDefPatterns.isEmpty())
    {
    // Use all specified API spec patterns.
    }
  else if( !StringUtils.isBlank( getProject()))
    {
    // Use API spec(s) for specified project name.
    apiDefPatterns.add( "**/" + getProject() + ".json");
    apiDefPatterns.add( "**/" + getProject() + ".yaml");
    apiDefPatterns.add( "**/" + getProject() + ".yml");
    }
  else if( !StringUtils.isBlank( getApiDef())) 
    {
    // Use specified API spec pattern.
    apiDefPatterns.add( getApiDef());
    }
  else
    {
    // Use default patterns
    apiDefPatterns.add( "**/*.json");
    apiDefPatterns.add( "**/*.yaml");
    apiDefPatterns.add( "**/*.yml");
    }
  inputScanner.setIncludes( apiDefPatterns.toArray( new String[0]));

  File inputRootDir = getInputDirFile();
  inputScanner.setBasedir( inputRootDir);
  inputScanner.scan();

  // Generate a test for each API spec
  String[] apiDefs = inputScanner.getIncludedFiles();
  for( int i = 0; i < apiDefs.length; i++)
    {
    // Define input path for this API spec.
    String inputFile = apiDefs[i];
    File apiDef = new File( inputRootDir, inputFile);

    // Set generator options for this API spec.
    Options options = new Options();
    options.setApiSpec( apiDef);
    options.setTestType( getTestType());
    options.setExecType( getExecType());
    options.setTestName( getTestName());
    options.setTestPackage( getTestPackage());
    options.setBaseClass( getBaseClass());
    options.setMocoTestConfig( getMocoTestConfigFile());
    options.setPaths( getPaths());
    options.setOperations( getOperations());
    options.setContentType( getContentType());
    options.setOutDir( new File( getOutDirFile(), getPath( inputFile)));
    options.setOnModellingCondition( getOnModellingCondition());
    options.setOnResolverCondition( getOnResolverCondition());
    options.setReadOnlyEnforced( isReadOnlyEnforced());
    options.setMaxTries( getMaxTries());
    options.setRandomSeed( getRandom());

    ApiTestCommand.run( options);
    }
  }
catch( Exception e)
  {
  throw new MojoExecutionException( "Can't generate requested tests", e);
  }
}
 
Example 20
Source File: BasePrepareSources.java    From gradle-golang-plugin with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void run()  throws  Exception {
    final ProgressLogger progress = startProgress("Prepare sources");

    final GolangSettings settings = getGolang();
    final BuildSettings build = getBuild();
    boolean atLeastOneCopied = false;
    if (!FALSE.equals(build.getUseTemporaryGopath())) {
        final Path gopath = build.getFirstGopath();
        progress.progress("Prepare GOPATH " + gopath + "...");
        LOGGER.info("Prepare GOPATH ({})...", gopath);
        final Path projectBasedir = settings.getProjectBasedir();
        final Path packagePath = settings.packagePathFor(gopath);
        final Path dependencyCachePath = getDependencies().getDependencyCache();
        prepareDependencyCacheIfNeeded(packagePath, dependencyCachePath);

        final DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(projectBasedir.toFile());
        scanner.setIncludes(build.getIncludes());
        scanner.setExcludes(build.getExcludes());
        scanner.setCaseSensitive(true);
        scanner.scan();
        for (final String file : scanner.getIncludedFiles()) {
            final Path sourceFile = projectBasedir.resolve(file);
            final Path targetFile = packagePath.resolve(file);
            if (!sourceFile.equals(dependencyCachePath)) {
                if (!exists(targetFile)
                    || size(sourceFile) != size(targetFile)
                    || !getLastModifiedTime(sourceFile).equals(getLastModifiedTime(targetFile))) {
                    atLeastOneCopied = true;
                    progress.progress("Prepare source file: " + file + "...");
                    LOGGER.debug("* {}", file);
                    ensureParentOf(targetFile);
                    try (final InputStream is = newInputStream(sourceFile)) {
                        try (final OutputStream os = newOutputStream(targetFile)) {
                            IOUtils.copy(is, os);
                        }
                    }
                    setLastModifiedTime(targetFile, getLastModifiedTime(sourceFile));
                }
            }
        }
        if (!atLeastOneCopied) {
            getState().setOutcome(UP_TO_DATE);
        }
    } else {
        getState().setOutcome(SKIPPED);
    }

    progress.completed();
}