Java Code Examples for org.codehaus.plexus.util.FileUtils#fileWrite()

The following examples show how to use org.codehaus.plexus.util.FileUtils#fileWrite() . 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: AbstractCommunityEnvFactory.java    From maven-native with MIT License 6 votes vote down vote up
private File createEnvWrapperFile(File vsInstallDir, String platform)
        throws IOException
{

    File tmpFile = File.createTempFile( "msenv", ".bat" );

    StringBuffer buffer = new StringBuffer();
    buffer.append( "@echo off\r\n" );
    buffer.append( "call \"" ).append( vsInstallDir ).append( "\"" )
            .append( "\\VC\\Auxiliary\\Build\\vcvarsall.bat " + platform + "\r\n" );
    buffer.append( "echo " + EnvStreamConsumer.START_PARSING_INDICATOR ).append( "\r\n" );
    buffer.append( "set\r\n" );
    FileUtils.fileWrite( tmpFile.getAbsolutePath(), buffer.toString() );

    return tmpFile;
}
 
Example 2
Source File: AbstractMSVCEnvFactory.java    From maven-native with MIT License 6 votes vote down vote up
private File createEnvWrapperFile( File vsInstallDir, String platform )
    throws IOException
{

    File tmpFile = File.createTempFile( "msenv", ".bat" );

    StringBuffer buffer = new StringBuffer();
    buffer.append( "@echo off\r\n" );
    buffer.append( "call \"" ).append( vsInstallDir ).append( "\"" )
            .append( "\\VC\\vcvarsall.bat " + platform + "\n\r" );
    buffer.append( "echo " + EnvStreamConsumer.START_PARSING_INDICATOR ).append( "\r\n" );
    buffer.append( "set\n\r" );

    FileUtils.fileWrite( tmpFile.getAbsolutePath(), buffer.toString() );

    return tmpFile;
}
 
Example 3
Source File: BuildFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void mavenGoalWhenPackageJsonContainsDependencies_onlyFrameworkHandledDependencyIsTouched()
        throws Exception {
    JsonObject json = TestUtils.getInitalPackageJson();
    JsonObject dependencies = Json.createObject();
    // Add dependencies foo-bar and bar-foo
    dependencies.put("foo", "bar");
    dependencies.put("bar", "foo");
    // Make foo framework handled
    json.getObject("vaadin").getObject("dependencies").put("foo", "bar");
    json.put("dependencies", dependencies);
    FileUtils.fileWrite(packageJson, "UTF-8", json.toJson());

    mojo.execute();
    JsonObject packageJsonObject = getPackageJson(packageJson);
    dependencies = packageJsonObject.getObject("dependencies");

    assertContainsPackage(dependencies, "@vaadin/vaadin-button",
            "@vaadin/vaadin-element-mixin");

    Assert.assertFalse("Foo should have been removed",
            dependencies.hasKey("foo"));
    Assert.assertTrue("Bar should remain", dependencies.hasKey("bar"));
}
 
Example 4
Source File: JavaServiceWrapperDaemonGenerator.java    From appassembler with MIT License 6 votes vote down vote up
private void insertPreWrapperConf( File wrapperConf, File preWrapperConf )
    throws DaemonGeneratorException
{
    try
    {
        StringBuilder buffer = new StringBuilder();
        buffer.append( FileUtils.fileRead( preWrapperConf ) );
        buffer.append( "\n" );
        buffer.append( FileUtils.fileRead( wrapperConf ) );
        FileUtils.fileWrite( wrapperConf, buffer.toString() );
    }
    catch ( IOException e )
    {
        throw new DaemonGeneratorException( "Unable to merge pre wrapper config file." );
    }
}
 
Example 5
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void failLocalChangeItTest()
    throws Exception
{
    File projDir = resources.getBasedir( "failed-local-change" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File basedir = result.getBasedir();
    File foo = new File( basedir, "foo.txt" );
    FileUtils.fileWrite( foo, "hello" );
    FileUtils.copyDirectoryStructure( new File( basedir, "dotSvnDir" ), new File( basedir, ".svn" ) );
    result = mavenExec.execute( "verify" );
    result.assertLogText( "BUILD FAILURE" );
    result.assertLogText( "because you have local modifications" );
}
 
Example 6
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void gitBasicItMBUILDNUM66Test()
    throws Exception
{
    File projDir = resources.getBasedir( "git-basic-it-MBUILDNUM-66" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File basedir = result.getBasedir();
    File foo = new File( basedir, "foo.txt" );
    FileUtils.fileWrite( foo, "hello" );
    FileUtils.copyDirectoryStructure( new File( basedir, "dotGitDir" ), new File( basedir, ".git" ) );
    result = mavenExec.execute( "verify" );
    result.assertLogText( "Storing buildScmBranch: master" );
    File testDir = result.getBasedir();
    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "ee58acb27b6636a497c1185f80cd15f76134113f", scmRev );

}
 
Example 7
Source File: POM.java    From pomutils with Apache License 2.0 6 votes vote down vote up
/**
 * Saves the pom, if it was changed.
 */
public void savePom() throws IOException, XMLStreamException {
	if (!changed) {
		return;
	}

	if (this.projectVersion != null) {
		changed |= PomHelper.setProjectVersion(pom, this.projectVersion);
	}

	if (this.parentVersion != null) {
		changed |= PomHelper.setProjectParentVersion(pom, this.parentVersion);
	}

	if (this.scmTag != null) {
		changed |= PomHelper.setProjectValue(pom, "/project/scm/tag", this.scmTag);
	}

	if (!changed) {
		return;
	}

	FileUtils.fileWrite(pomFile.getAbsolutePath(), pom.asStringBuilder().toString());
}
 
Example 8
Source File: JaxbUtil.java    From DevToolBox with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 将对象转成xml并存储到xml
 *
 * @param ss
 * @param file
 */
public static void saveToXML(Object ss, String file) {
    try {
        String content = convertToXml(ss, CHARSET_UTF8);
        FileUtils.mkdir(DIR);
        FileUtils.fileWrite(file, content);
    } catch (Exception ex) {
        LOGGER.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example 9
Source File: FileSystem.java    From directory-watcher with Apache License 2.0 5 votes vote down vote up
public void playActions() throws Exception {
  for (FileSystemAction action : actions) {
    if (action.kind == ENTRY_CREATE && action.content != null) {
      FileUtils.fileWrite(action.path.toFile(), action.content);
    } else if (action.kind == ENTRY_MODIFY) {
      FileUtils.fileAppend(action.path.toFile().getAbsolutePath(), action.content);
      action.path.toFile().setLastModified(new Date().getTime());
    } else if (action.kind == ENTRY_DELETE) {
      action.path.toFile().delete();
    } else {
      switch (action.myType) {
        case WAIT:
          try {
            Thread.sleep(action.millis);
          } catch (InterruptedException e) {
          }
          break;
        case MKDIR:
          if (!action.path.toFile().exists()) {
            action.path.toFile().mkdirs();
          }
          break;
        case COUNTABLE:
        case NOOP:
          break;
      }
    }
  }
}
 
Example 10
Source File: AbstractFormatterTest.java    From formatter-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected void doTestFormat(Map<String, String> options, Formatter formatter, String fileUnderTest,
        String expectedSha512, LineEnding lineEnding) throws IOException {

    // Set original file and file to use for test
    File originalSourceFile = new File("src/test/resources/", fileUnderTest);
    File sourceFile = new File(TEST_OUTPUT_DIR, fileUnderTest);

    // Copy file to new location
    Files.copy(originalSourceFile, sourceFile);

    // Read file to be formatted
    String originalCode = FileUtils.fileRead(sourceFile, StandardCharsets.UTF_8.name());

    // Format the file and make sure formatting worked
    formatter.init(options, new TestConfigurationSource(TEST_OUTPUT_DIR));
    String formattedCode = formatter.formatFile(sourceFile, originalCode, lineEnding);
    assertNotNull(formattedCode);
    assertNotEquals(originalCode, formattedCode);

    // Write the file we formatte4d
    FileUtils.fileWrite(sourceFile, StandardCharsets.UTF_8.name(), formattedCode);

    // We are hashing this as set in stone in case for some reason our source file changes unexpectedly.
    byte[] sha512 = Files.asByteSource(sourceFile).hash(Hashing.sha512()).asBytes();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < sha512.length; i++) {
        sb.append(Integer.toString((sha512[i] & 0xff) + 0x100, 16).substring(1));
    }

    assertEquals(expectedSha512, sb.toString());
}
 
Example 11
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_keepDependencies_when_packageJsonExists()
        throws Exception {
    JsonObject json = TestUtils.getInitalPackageJson();
    json.put("dependencies", Json.createObject());
    json.getObject("dependencies").put("foo", "bar");
    FileUtils.fileWrite(packageJson, json.toJson());
    mojo.execute();
    assertPackageJsonContent();

    JsonObject packageJsonObject = getPackageJson(packageJson);
    assertContainsPackage(packageJsonObject.getObject("dependencies"),
            "foo");
}
 
Example 12
Source File: BuildFrontendMojoTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
    MavenProject project = Mockito.mock(MavenProject.class);
    Mockito.when(project.getRuntimeClasspathElements())
            .thenReturn(getClassPath());

    tokenFile = new File(temporaryFolder.getRoot(),
            VAADIN_SERVLET_RESOURCES + TOKEN_FILE);

    File npmFolder = temporaryFolder.getRoot();
    generatedFolder = new File(npmFolder, DEFAULT_GENERATED_DIR);
    importsFile = new File(generatedFolder, IMPORTS_NAME);
    nodeModulesPath = new File(npmFolder, NODE_MODULES);
    flowResourcesFolder = new File(npmFolder, DEAULT_FLOW_RESOURCES_FOLDER);
    File frontendDirectory = new File(npmFolder, DEFAULT_FRONTEND_DIR);

    packageJson = new File(npmFolder, PACKAGE_JSON).getAbsolutePath();
    webpackConfig = new File(npmFolder, WEBPACK_CONFIG).getAbsolutePath();

    projectFrontendResourcesDirectory = new File(npmFolder,
            "flow_resources");

    defaultJavaSource = new File(".", "src/test/java");
    openApiJsonFile = new File(npmFolder,
            "target/generated-resources/openapi.json").getAbsolutePath();
    generatedTsFolder = new File(npmFolder, "frontend/generated");

    Assert.assertTrue("Failed to create a test project resources",
            projectFrontendResourcesDirectory.mkdirs());
    Assert.assertTrue("Failed to create a test project file",
            new File(projectFrontendResourcesDirectory,
                    TEST_PROJECT_RESOURCE_JS).createNewFile());

    ReflectionUtils.setVariableValueInObject(mojo,
            "frontendResourcesDirectory",
            projectFrontendResourcesDirectory);

    ReflectionUtils.setVariableValueInObject(mojo, "project", project);
    ReflectionUtils.setVariableValueInObject(mojo, "generatedFolder",
            generatedFolder);
    ReflectionUtils.setVariableValueInObject(mojo, "frontendDirectory",
            frontendDirectory);
    ReflectionUtils.setVariableValueInObject(mojo,
            "generateEmbeddableWebComponents", false);
    ReflectionUtils.setVariableValueInObject(mojo, "npmFolder", npmFolder);
    ReflectionUtils.setVariableValueInObject(mojo, "generateBundle", false);
    ReflectionUtils.setVariableValueInObject(mojo, "runNpmInstall", false);
    ReflectionUtils.setVariableValueInObject(mojo, "optimizeBundle", true);

    ReflectionUtils.setVariableValueInObject(mojo, "openApiJsonFile",
            new File(npmFolder, "target/generated-resources/openapi.json"));
    ReflectionUtils.setVariableValueInObject(mojo, "applicationProperties",
            new File(npmFolder,
                    "src/main/resources/application.properties"));
    ReflectionUtils.setVariableValueInObject(mojo, "javaSourceFolder",
            defaultJavaSource);
    ReflectionUtils.setVariableValueInObject(mojo, "generatedTsFolder",
            generatedTsFolder);
    ReflectionUtils.setVariableValueInObject(mojo, "nodeVersion",
            FrontendTools.DEFAULT_NODE_VERSION);
    ReflectionUtils.setVariableValueInObject(mojo, "nodeDownloadRoot",
            NodeInstaller.DEFAULT_NODEJS_DOWNLOAD_ROOT);

    flowResourcesFolder.mkdirs();
    generatedFolder.mkdirs();

    setProject(mojo, npmFolder);

    // Install all imports used in the tests on node_modules so as we don't
    // need to run `npm install`
    createExpectedImports(frontendDirectory, nodeModulesPath);
    FileUtils.fileWrite(packageJson, "UTF-8",
            TestUtils.getInitalPackageJson().toJson());
}
 
Example 13
Source File: AntTaskUtils.java    From was-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void execute(WebSphereModel model, PlexusConfiguration target, MavenProject project,
                           MavenProjectHelper projectHelper, List<Artifact> pluginArtifact, Log logger)
    throws IOException, MojoExecutionException {
  // The fileName should probably use the plugin executionId instead of the targetName
  boolean useDefaultTargetName = false;
  String antTargetName = target.getAttribute("name");
  if (null == antTargetName) {
    antTargetName = DEFAULT_ANT_TARGET_NAME;
    useDefaultTargetName = true;
  }
  StringBuilder fileName = new StringBuilder(50);
  fileName.append("build");
  if (StringUtils.isNotBlank(model.getHost())) {
    fileName.append("-").append(model.getHost());
  }
  if (StringUtils.isNotBlank(model.getApplicationName())) {
    fileName.append("-").append(model.getApplicationName());
  }
  fileName.append("-").append(antTargetName).append("-").append(CommandUtils.getTimestampString()).append(".xml");
  File buildFile = getBuildFile(project, fileName.toString());

  if (model.isVerbose()) {
    logger.info("ant fileName: " + fileName);
  }

  if (buildFile.exists()) {
    logger.info("[SKIPPED] already executed");
    return;
  }

  StringWriter writer = new StringWriter();
  AntXmlPlexusConfigurationWriter xmlWriter = new AntXmlPlexusConfigurationWriter();
  xmlWriter.write(target, writer);

  StringBuffer antXML = writer.getBuffer();

  if (useDefaultTargetName) {
    stringReplace(antXML, "<target", "<target name=\"" + antTargetName + "\"");
  }

  final String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
  antXML.insert(0, xmlHeader);
  final String projectOpen = "<project name=\"" + Constants.PLUGIN_ID + "\" default=\"" + antTargetName + "\">\n";
  int index = antXML.indexOf("<target");
  antXML.insert(index, projectOpen);

  final String projectClose = "\n</project>";
  antXML.append(projectClose);

  buildFile.getParentFile().mkdirs();
  FileUtils.fileWrite(buildFile.getAbsolutePath(), "UTF-8", antXML.toString());

  Project antProject = generateAntProject(model, buildFile, project, projectHelper, pluginArtifact, logger);
  antProject.executeTarget(antTargetName);
}
 
Example 14
Source File: BasicSupport.java    From ci.maven with Apache License 2.0 4 votes vote down vote up
protected void installFromFile() throws Exception {
    // Check if there is a different/newer archive or missing marker to trigger assembly install
    File installMarker = new File(installDirectory, ".installed");

    if (!refresh) {
        if (!installMarker.exists()) {
            refresh = true;
        } else if (assemblyArchive.lastModified() > installMarker.lastModified()) {
            log.debug(MessageFormat.format(messages.getString("debug.detect.assembly.archive"), ""));
            refresh = true;
        } else if(!assemblyArchive.getCanonicalPath().equals(FileUtils.fileRead(installMarker))) {
            refresh = true;
        }
    } else {
        log.debug(MessageFormat.format(messages.getString("debug.request.refresh"), ""));
    }

    String userDirectoryPath = userDirectory.getCanonicalPath();
    if (refresh && installDirectory.exists() && installDirectory.isDirectory()) {
        log.info(MessageFormat.format(messages.getString("info.uninstalling.server.home"), installDirectory));
        // Delete everything in the install directory except usr directory
        for(File f : installDirectory.listFiles()) {
            if(!(f.isDirectory() && f.getCanonicalPath().equals(userDirectoryPath))) {
                FileUtils.forceDelete(f);
            }
        }
    }

    // Install the assembly
    if (!installMarker.exists()) {
        log.info("Installing assembly...");

        FileUtils.forceMkdir(installDirectory);

        Expand unzip = (Expand) ant.createTask("unzip");

        unzip.setSrc(assemblyArchive);
        unzip.setDest(assemblyInstallDirectory.getCanonicalFile());
        unzip.execute();

        // Make scripts executable, since Java unzip ignores perms
        Chmod chmod = (Chmod) ant.createTask("chmod");
        chmod.setPerm("ugo+rx");
        chmod.setDir(installDirectory);
        chmod.setIncludes("bin/*");
        chmod.setExcludes("bin/*.bat");
        chmod.execute();

        // delete installMarker first in case it was packaged with the assembly
        installMarker.delete();
        installMarker.createNewFile();
        
        // Write the assembly archive path so we can determine whether to install a different assembly in future invocations
        FileUtils.fileWrite(installMarker, assemblyArchive.getCanonicalPath());
    } else {
        log.info(MessageFormat.format(messages.getString("info.reuse.installed.assembly"), ""));
    }
}
 
Example 15
Source File: DockerFileBuilder.java    From docker-maven-plugin with Apache License 2.0 2 votes vote down vote up
/**
 * Create a DockerFile in the given directory
 * @param  destDir directory where to store the dockerfile
 * @return the full path to the docker file
 * @throws IOException if writing fails
 */
public File write(File destDir) throws IOException {
    File target = new File(destDir,"Dockerfile");
    FileUtils.fileWrite(target, content());
    return target;
}