Write the default .rc template file to a temporary file and return it
@return a File pointing to the temporary file
@throws MojoExecutionException if there is an IOException
519145
private File writeVersionInfoTemplateToTempFile() throws MojoExecutionException
    {
        try 
        {
            final File versionInfoSrc = File.createTempFile( "msbuild-maven-plugin_" + MOJO_NAME, null );
    
            InputStream is = getClass().getResourceAsStream( DEFAULT_VERSION_INFO_TEMPLATE );
            FileOutputStream dest = new FileOutputStream( versionInfoSrc );
            byte[] buffer = new byte[1024];
            int read = -1;
            while ( ( read = is.read( buffer ) ) != -1 )
            {
                dest.write( buffer, 0, read );
            }
            dest.close();
            
            return versionInfoSrc;
        } 
        catch ( IOException ioe )
        {
            String msg = "Failed to create temporary version file";
            getLog().error( msg, ioe );
            throw new MojoExecutionException( msg, ioe );
        }
    }
301853
public JavaFile generate() {
    MethodSpec privateConstructor = MethodSpec.constructorBuilder()
        .addModifiers(Modifier.PRIVATE)
        .build();

    TypeSpec.Builder casesClassBuilder = TypeSpec.classBuilder(className)
        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
        .addMethod(privateConstructor)
        .addMethods(methods);

    for (String javadoc : javadocs) {
      casesClassBuilder.addJavadoc(javadoc);
    }

    TypeSpec casesClass = casesClassBuilder.build();

    JavaFile.Builder javaFileBuilder = JavaFile.builder(packageName, casesClass);

    if (fileComment != null) {
      javaFileBuilder.addFileComment(fileComment);
    }

    javaFileBuilder.addFileComment("\nGenerated by Motif. Do Not Edit!\n");

    JavaFile javaFile = javaFileBuilder.build();
    return javaFile;
  }
858530
public static FileChannel createTempFile(String prefix, String suffix) throws IOException {
        return createTempFile(TMPDIR, prefix, suffix);
    }
953872
private void createVcProjFile(final Project antProject, final Library library)
      throws MojoExecutionException, MojoFailureException {

    // configure task
    final CCTask task = new CCTask();
    task.setProject(antProject);
    task.setDebug(true);

    // subsystem (console)
    final SubsystemEnum subSystem = new SubsystemEnum();
    subSystem.setValue(library.getSubSystem());
    task.setSubsystem(subSystem);

    // outtype
    final OutputTypeEnum outTypeEnum = new OutputTypeEnum();
    final String type = library.getType();
    outTypeEnum.setValue(type);
    task.setOuttype(outTypeEnum);

    // stdc++
    task.setLinkCPP(library.linkCPP());

    // TODO: this should match the standard NAR location defined by layout
    // similar to Nar Compile
    // outDir
    File outDir = new File(getTargetDirectory(), "bin");
    outDir = new File(outDir, getAOL().toString());
    outDir.mkdirs();

    // outFile
    final File outFile = new File(outDir, getOutput(getAOL(), type));

    getLog().debug("NAR - output: '" + outFile + "'");
    task.setOutfile(outFile);

    // object directory
    File objDir = new File(getTargetDirectory(), "obj");
    objDir = new File(objDir, getAOL().toString());
    objDir.mkdirs();
    task.setObjdir(objDir);

    // failOnError, libtool
    task.setFailonerror(failOnError(getAOL()));
    task.setLibtool(useLibtool(getAOL()));

    // runtime
    final RuntimeType runtimeType = new RuntimeType();
    runtimeType.setValue(getRuntime(getAOL()));
    task.setRuntime(runtimeType);

    // add C++ compiler
    final CompilerDef cpp = getCpp().getCompiler(Compiler.MAIN, null);
    if (cpp != null) {
      task.addConfiguredCompiler(cpp);
    }

    // add VCPROJ_MOJO def (see UnitTestDriverImpl.cpp generated by Krusoe
    // plugin)
    final DefineSet defineSet = new DefineSet();
    final DefineArgument defineArgument = new DefineArgument();
    defineArgument.setName("VCPROJ_MOJO");
    defineSet.addDefine(defineArgument);
    cpp.addConfiguredDefineset(defineSet);

    // add javah include path
    final File jniDirectory = getJavah().getJniDirectory();
    if (jniDirectory.exists()) {
      task.createIncludePath().setPath(jniDirectory.getPath());
    }

    // add java include paths
    getJava().addIncludePaths(task, Library.EXECUTABLE);

    getMsvc().configureCCTask(task);

    final List<NarArtifact> dependencies = getNarArtifacts();
    // add dependency include paths
    for (final Object element : dependencies) {
      // FIXME, handle multiple includes from one NAR
      final NarArtifact narDependency = (NarArtifact) element;
      final String binding = narDependency.getNarInfo().getBinding(getAOL(), Library.STATIC);
      getLog().debug("Looking for " + narDependency + " found binding " + binding);
      if (!binding.equals(Library.JNI)) {
        final File unpackDirectory = getUnpackDirectory();
        final File include = getLayout().getIncludeDirectory(unpackDirectory, narDependency.getArtifactId(),
            narDependency.getBaseVersion());
        getLog().debug("Looking for directory: " + include);
        if (include.exists()) {
          task.createIncludePath().setPath(include.getPath());
        } else {
          getLog().warn(String.format("Unable to locate %1$s lib include path '%2$s'", binding, include));
        }
      }
    }

    // add linker
    final LinkerDef linkerDefinition = getLinker().getLinker(this, task, getOS(), getAOL().getKey() + ".linker.",
        type, null);
    task.addConfiguredLinker(linkerDefinition);

    // add dependency libraries
    // FIXME: what about PLUGIN and STATIC, depending on STATIC, should we
    // not add all libraries, see NARPLUGIN-96
    if (type.equals(Library.SHARED) || type.equals(Library.JNI) || type.equals(Library.EXECUTABLE)) {

      final List depLibOrder = getDependencyLibOrder();
      List depLibs = dependencies;

      // reorder the libraries that come from the nar dependencies
      // to comply with the order specified by the user
      if (depLibOrder != null && !depLibOrder.isEmpty()) {

        final List tmp = new LinkedList();

        for (final Object aDepLibOrder : depLibOrder) {

          final String depToOrderName = (String) aDepLibOrder;

          for (final Iterator j = depLibs.iterator(); j.hasNext(); ) {

            final NarArtifact dep = (NarArtifact) j.next();
            final String depName = dep.getGroupId() + ":" + dep.getArtifactId();

            if (depName.equals(depToOrderName)) {

              tmp.add(dep);
              j.remove();
            }
          }
        }

        tmp.addAll(depLibs);
        depLibs = tmp;
      }

      for (final Object depLib : depLibs) {

        final NarArtifact dependency = (NarArtifact) depLib;

        // FIXME no handling of "local"

        // FIXME, no way to override this at this stage
        final String binding = dependency.getNarInfo().getBinding(getAOL(), Library.STATIC);
        getLog().debug("Using Binding: " + binding);
        AOL aol = getAOL();
        aol = dependency.getNarInfo().getAOL(getAOL());
        getLog().debug("Using Library AOL: " + aol.toString());

        if (!binding.equals(Library.JNI) && !binding.equals(Library.NONE) && !binding.equals(Library.EXECUTABLE)) {
          final File unpackDirectory = getUnpackDirectory();
          final File dir = getLayout()
              .getLibDirectory(unpackDirectory, dependency.getArtifactId(), dependency.getBaseVersion(), aol.toString(),
                  binding);
          getLog().debug("Looking for Library Directory: " + dir);
          if (dir.exists()) {
            final LibrarySet libSet = new LibrarySet();
            libSet.setProject(antProject);

            // FIXME, no way to override
            final String libs = dependency.getNarInfo().getLibs(getAOL());
            if (libs != null && !libs.equals("")) {
              getLog().debug("Using LIBS = " + libs);
              libSet.setLibs(new CUtil.StringArrayBuilder(libs));
              libSet.setDir(dir);
              task.addLibset(libSet);
            }
          } else {
            getLog().debug("Library Directory " + dir + " does NOT exist.");
          }

          // FIXME, look again at this, for multiple dependencies we
          // may need to remove duplicates
          final String options = dependency.getNarInfo().getOptions(getAOL());
          if (options != null && !options.equals("")) {
            getLog().debug("Using OPTIONS = " + options);
            final LinkerArgument arg = new LinkerArgument();
            arg.setValue(options);
            linkerDefinition.addConfiguredLinkerArg(arg);
          }

          final String sysLibs = dependency.getNarInfo().getSysLibs(getAOL());

          if (sysLibs != null && !sysLibs.equals("")) {
            getLog().debug("Using SYSLIBS = " + sysLibs);
            final SystemLibrarySet sysLibSet = new SystemLibrarySet();
            sysLibSet.setProject(antProject);

            sysLibSet.setLibs(new CUtil.StringArrayBuilder(sysLibs));

            task.addSyslibset(sysLibSet);
          }
        }
      }

      // Add JVM to linker
      getJava().addRuntime(task, getJavaHome(getAOL()), getOS(), getAOL().getKey() + "java.");

      // DS: generate project file
      getLog().debug("NAR: Writing project file...");
      final ProjectWriterEnum projectWriterEnum = new ProjectWriterEnum();
      projectWriterEnum.setValue("msvc8");
      final ProjectDef projectDef = new ProjectDef();
      projectDef.setType(projectWriterEnum);
      String filename = null;
      try {
        final File outputDir = new File(getTargetDirectory(), "vcproj");
        if (!outputDir.exists()) {
          final boolean succeeded = outputDir.mkdir();
          if (!succeeded) {
            throw new MojoExecutionException("Unable to create directory: " + outputDir);
          }
        }
        filename = outputDir + "/" + getMavenProject().getArtifactId();
        final File projFile = new File(filename);
        projectDef.setOutfile(projFile.getCanonicalFile());
      } catch (final IOException e) {
        throw new MojoExecutionException("Unable to create file: " + filename, e);
      }
      task.addProject(projectDef);
      task.setProjectsOnly(true);

      // we always want an EXE for debugging
      task.setOuttype(new OutputTypeEnum());

      // execute
      try {
        task.execute();
        getLog().info("Wrote project file: " + filename + ".vcproj");
      } catch (final BuildException e) {
        throw new MojoExecutionException("NAR: Compile failed", e);
      }
    }
  }
621186
public static File writeObjectToTempFile(Object o, String filename)
  throws IOException {
    File file = File.createTempFile(filename, ".tmp");
    file.deleteOnExit();
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
        new GZIPOutputStream(new FileOutputStream(file))));
    oos.writeObject(o);
    oos.close();
    return file;
  }
1288056
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
      Set<File> thriftFiles = findThriftFiles();

      final File outputDirectory = getOutputDirectory();
      ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());

      Set<String> compileRoots = new HashSet<String>();
      compileRoots.add("scrooge");

      if (thriftFiles.isEmpty()) {
        getLog().info("No thrift files to compile.");
      } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {
        getLog().info("Generated thrift files up to date, skipping compile.");
        attachFiles(compileRoots);
      } else {
        outputDirectory.mkdirs();

        // Quick fix to fix issues with two mvn installs in a row (ie no clean)
        cleanDirectory(outputDirectory);

        getLog().info(format("compiling thrift files %s with Scrooge", thriftFiles));
        synchronized(lock) {
          ScroogeRunner runner = new ScroogeRunner();
          Map<String, String> thriftNamespaceMap = new HashMap<String, String>();
          for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {
            thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());
          }

          // Include thrifts from resource as well.
          Set<File> includes = thriftIncludes;
          includes.add(getResourcesOutputDirectory());

          // Include thrift root
          final File thriftSourceRoot = getThriftSourceRoot();
          if (thriftSourceRoot != null && thriftSourceRoot.exists()) {
            includes.add(thriftSourceRoot);
          }

          runner.compile(
                  getLog(),
                  includeOutputDirectoryNamespace ? new File(outputDirectory, "scrooge") : outputDirectory,
                  thriftFiles,
                  includes,
                  thriftNamespaceMap,
                  language,
                  thriftOpts);
        }
        attachFiles(compileRoots);
      }
    } catch (IOException e) {
      throw new MojoExecutionException("An IO error occurred", e);
    }
  }
758489
public static File createTempDir() throws IllegalStateException
   {
      File baseDir = getTempDirectory();
      try
      {
         return Files.createTempDirectory(baseDir.toPath(), "tmpdir").toFile();
      }
      catch (IOException e)
      {
         throw new IllegalStateException("Error while creating temporary directory", e);
      }
   }
1030191
public static File writeScriptTempfile(
            final Framework framework,
            final Reader source,
            final LineEndingStyle style
    )
            throws IOException
    {
        return writeScriptTempfile(framework, null, null, source, style);
    }
707774
private File getTemplateFile(String filename) throws IOException {
        File templateFile=null;
        final String resource = TEMPLATE_RESOURCES_PATH + "/" + filename;
        InputStream is = Setup.class.getClassLoader().getResourceAsStream(resource);
        if (null == is) {
            throw new RuntimeException("Unable to load required template: " + resource);
        }
        templateFile = File.createTempFile("temp", filename);
        templateFile.deleteOnExit();
        try {
            return copyToNativeLineEndings(is, templateFile);
        } finally {
            is.close();
        }
    }
1185963
public static final File createTempDir() throws IOException
   {
      File dir = File.createTempFile("mpxj", "tmp");
      delete(dir);
      mkdirs(dir);
      return dir;
   }
790073
public static File createTempFile(final Framework framework) throws IOException {
        String fileExt = ".tmp";
        if ("windows".equalsIgnoreCase(framework.createFrameworkNode().getOsFamily())) {
            fileExt = ".tmp.bat";
        }
        final File dispatch = File.createTempFile("dispatch", fileExt, new File(framework.getProperty(
                "framework.tmp.dir")));
        registerTempFile(dispatch);
        return dispatch;
    }
213608
public TempFile createTempFile() throws IOException {
		TempFile tempFile = new TempFile(prefix, suffix, directory);
		synchronized(tempFiles) {
			tempFiles.add(new WeakReference<>(tempFile));
		}
		return tempFile;
	}
815400
private void createCodeFormatter() throws MojoExecutionException {
        Map<String, String> javaFormattingOptions = getFormattingOptions(this.configFile);
        if (javaFormattingOptions != null) {
            this.javaFormatter.init(javaFormattingOptions, this);
        }
        Map<String, String> jsFormattingOptions = getFormattingOptions(this.configJsFile);
        if (jsFormattingOptions != null) {
            this.jsFormatter.init(jsFormattingOptions, this);
        }
        if (configHtmlFile != null) {
            this.htmlFormatter.init(getOptionsFromPropertiesFile(configHtmlFile), this);
        }
        if (configXmlFile != null) {
            Map<String, String> xmlFormattingOptions = getOptionsFromPropertiesFile(configXmlFile);
            xmlFormattingOptions.put("lineending", this.lineEnding.getChars());
            this.xmlFormatter.init(xmlFormattingOptions, this);
        }
        if (configJsonFile != null) {
            Map<String, String> jsonFormattingOptions = getOptionsFromPropertiesFile(configJsonFile);
            jsonFormattingOptions.put("lineending", this.lineEnding.getChars());
            this.jsonFormatter.init(jsonFormattingOptions, this);
        }
        if (configCssFile != null) {
            this.cssFormatter.init(getOptionsFromPropertiesFile(configCssFile), this);
        }
        // stop the process if not config files where found
        if (javaFormattingOptions == null && jsFormattingOptions == null && configHtmlFile == null
                && configXmlFile == null && configCssFile == null) {
            throw new MojoExecutionException(
                    "You must provide a Java, Javascript, HTML, XML, JSON, or CSS configuration file.");
        }
    }
213230
@Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (this.skipFormatting) {
            getLog().info("Formatting is skipped");
            return;
        }

        long startClock = System.currentTimeMillis();

        if (StringUtils.isEmpty(this.encoding)) {
            this.encoding = ReaderFactory.FILE_ENCODING;
            getLog().warn("File encoding has not been set, using platform encoding (" + this.encoding
                    + ") to format source files, i.e. build is platform dependent!");
        } else {
            if (!Charset.isSupported(this.encoding)) {
                throw new MojoExecutionException("Encoding '" + this.encoding + "' is not supported");
            }
            getLog().info("Using '" + this.encoding + "' encoding to format source files.");
        }

        List<File> files = new ArrayList<>();
        if (this.directories != null) {
            for (File directory : this.directories) {
                if (directory.exists() && directory.isDirectory()) {
                    files.addAll(addCollectionFiles(directory));
                }
            }
        } else {
            // Using defaults of source main and test dirs
            if (this.sourceDirectory != null && this.sourceDirectory.exists() && this.sourceDirectory.isDirectory()) {
                files.addAll(addCollectionFiles(this.sourceDirectory));
            }
            if (this.testSourceDirectory != null && this.testSourceDirectory.exists()
                    && this.testSourceDirectory.isDirectory()) {
                files.addAll(addCollectionFiles(this.testSourceDirectory));
            }
        }

        int numberOfFiles = files.size();
        Log log = getLog();
        log.info("Number of files to be formatted: " + numberOfFiles);

        if (numberOfFiles > 0) {
            createCodeFormatter();
            ResultCollector rc = new ResultCollector();
            Properties hashCache = readFileHashCacheFile();

            String basedirPath = getBasedirPath();
            for (int i = 0, n = files.size(); i < n; i++) {
                File file = files.get(i);
                if (file.exists()) {
                    if (file.canWrite()) {
                        formatFile(file, rc, hashCache, basedirPath);
                    } else {
                        rc.readOnlyCount++;
                    }
                } else {
                    rc.failCount++;
                }
            }

            storeFileHashCache(hashCache);

            long endClock = System.currentTimeMillis();

            log.info("Successfully formatted:          " + rc.successCount + FILE_S);
            log.info("Fail to format:                  " + rc.failCount + FILE_S);
            log.info("Skipped:                         " + rc.skippedCount + FILE_S);
            log.info("Read only skipped:               " + rc.readOnlyCount + FILE_S);
            log.info("Approximate time taken:          " + ((endClock - startClock) / 1000) + "s");
        }
    }
438792
private List<String> copyResources(File targetDirectory, List<FileSet> fileSets) throws MojoExecutionException {
        ArrayList<String> addedFiles = new ArrayList<String>();
        for (FileSet fileSet : fileSets) {
            // Get the absolute base directory for the FileSet
            File sourceDirectory = new File(fileSet.getDirectory());

            if (!sourceDirectory.isAbsolute()) {
                sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
            }

            if (!sourceDirectory.exists()) {
                // If the requested directory does not exist, log it and carry on
                getLog().warn("Specified source directory " + sourceDirectory.getPath() + " does not exist.");
                continue;
            }

            List<String> includedFiles = scanFileSet(sourceDirectory, fileSet);
            addedFiles.addAll(includedFiles);

            getLog().info("Copying " + includedFiles.size() + " additional resource" + (includedFiles.size() > 1 ? "s" : ""));

            for (String destination : includedFiles) {
                File source = new File(sourceDirectory, destination);
                File destinationFile = new File(targetDirectory, destination);

                // Make sure that the directory we are copying into exists
                destinationFile.getParentFile().mkdirs();

                try {
                    FileUtils.copyFile(source, destinationFile);
                    destinationFile.setExecutable(fileSet.isExecutable(),false);

                } catch (IOException e) {
                    throw new MojoExecutionException("Error copying additional resource " + source, e);
                }
            }
        }
        return addedFiles;
    }
85234
public TempDir createTempDir(String originalName) throws IOException {
        if (!open.get()) {
            throw VFSMessages.MESSAGES.tempFileProviderClosed();
        }
        final String name = createTempName(originalName + "-", "");
        final File f = new File(providerRoot, name);
        for (int i = 0; i < RETRIES; i++) {
            if (f.mkdirs()) {
                return new TempDir(this, f);
            }
        }
        throw VFSMessages.MESSAGES.couldNotCreateDirectory(originalName,RETRIES);
    }
1255183
protected InputStream initInput(final File file)
        throws MojoExecutionException {
        InputStream stream = null;
        try {
            if (file.isDirectory()) {
                throw new MojoExecutionException("File "
                    + file.getAbsolutePath()
                    + " is directory!");
            }
            if (!file.exists()) {
                throw new MojoExecutionException("File "
                    + file.getAbsolutePath()
                    + " does not exist!");
            }
            stream = new FileInputStream(file);
            //append to outfile here
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Could not find file: "
                + file.getAbsolutePath(), e);
        }
        return stream;
    }