org.codehaus.plexus.util.IOUtil Java Examples

The following examples show how to use org.codehaus.plexus.util.IOUtil. 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: FormattedPropertiesTest.java    From appassembler with MIT License 6 votes vote down vote up
private void saveAndCompare( String expectedResource )
    throws IOException
{
    StringOutputStream string = new StringOutputStream();
    formattedProperties.save( string );

    StringOutputStream expected = new StringOutputStream();
    InputStream asStream = getClass().getResourceAsStream( expectedResource );
    try
    {
        IOUtil.copy( asStream, expected );
    }
    finally
    {
        IOUtil.close( asStream );
    }

    String unified = StringUtils.unifyLineSeparators( expected.toString() );
    assertEquals( unified, string.toString() );
}
 
Example #2
Source File: BasicSupport.java    From ci.maven with Apache License 2.0 6 votes vote down vote up
private boolean hasSameLicense(Artifact license) throws MojoExecutionException, IOException {
    boolean sameLicense = false;
    if (license != null) {
        InputStream licenseInfo = getZipEntry(license.getFile(), "wlp/lafiles/LI_en");
        if (licenseInfo == null) {
            log.warn(MessageFormat.format(messages.getString("warn.install.license"), license.getId()));
            return sameLicense;
        } 
        
        File lic = new File(assemblyInstallDirectory, "wlp/lafiles/LI_en");
        if (lic.exists()) {  
            FileInputStream installedLicenseInfo = new FileInputStream(lic);
            sameLicense = IOUtil.contentEquals(licenseInfo, installedLicenseInfo);
            licenseInfo.close();
            installedLicenseInfo.close();
        }
    }
    return sameLicense;
}
 
Example #3
Source File: CapsuleMojo.java    From capsule-maven-plugin with MIT License 6 votes vote down vote up
private File createExecCopyProcess(final File jar, final String prefix, final String extension) throws IOException {
	final File x = new File(jar.getPath().replace(".jar", extension));
	if (x.exists()) {
		debug("EXISTS - " + x.getName());
		return x;
	}

	FileOutputStream out = null;
	FileInputStream in = null;
	try {
		out = new FileOutputStream(x);
		in = new FileInputStream(jar);
		out.write((prefix).getBytes("ASCII"));
		Files.copy(jar.toPath(), out);
		out.flush();
		//			Runtime.getRuntime().exec("chmod +x " + x.getAbsolutePath());
		final boolean execResult = x.setExecutable(true, false);
		if (!execResult)
			warn("Failed to mark file executable - " + x.getAbsolutePath());
	} finally {
		IOUtil.close(in);
		IOUtil.close(out);
	}
	return x;
}
 
Example #4
Source File: PersistentVersionSelector.java    From pomutils with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the selection state to {@link #persistentFile}.
 */
private void writeState(SelectionState selectionState) throws IOException {
	FileWriter writer = null; 
	
	try {
		writer = new FileWriter(persistentFile);
		Properties properties = selectionState.toProperties();
		properties.store(
				writer,
				String.format("Used by the 'pomutils' merge driver to store version selections%n"
					+ "within the same invocation of git merge%n"
					+ "(to avoid repeatedly prompting the user to select a version).%n"
					+ "Selected versions will only be reused for 2 minutes.%n"
					+ "It is safe to delete this file between git merge invocations%n"
					+ "(which will cause the user to be prompted again).%n"));
	} finally {
		IOUtil.close(writer);
	}
}
 
Example #5
Source File: PersistentVersionSelector.java    From pomutils with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the selection state from {@link #persistentFile}.
 */
private SelectionState readState() throws IOException {
	if (!persistentFile.canRead()) {
		return null;
	}
	
	if (persistentFile.lastModified() < System.currentTimeMillis() - TIMEOUT) {
		return null;
	}
	
	FileReader reader = null; 
	
	try {
		reader = new FileReader(persistentFile);
		Properties properties = new Properties();
		properties.load(reader);
		
		return SelectionState.fromProperties(properties);
	} finally {
		IOUtil.close(reader);
	}
}
 
Example #6
Source File: LongOutputTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@After
public void tearDown() throws Exception {
    afterTest();
    readThreadActive.set(false);
    if (ctx != null) {
        ctx.terminateSession();
    }
    for (Thread thread : threads) {
        thread.join(5000);
        if (thread.isAlive()) {
            thread.interrupt();
        }
        waitFor(() -> !thread.isAlive(), 10000);
    }
    threads.removeAll(threads);
    IOUtil.close(consoleInput);
    IOUtil.close(consoleWriter);
    IOUtil.close(consoleOutput);
    IOUtil.close(consoleReader);

    // return back original value for jboss.cli.config property
    WildFlySecurityManager.setPropertyPrivileged("jboss.cli.config", originalCliConfig);
}
 
Example #7
Source File: AbstractDaemonGeneratorTest.java    From appassembler with MIT License 6 votes vote down vote up
private static String getAppAssemblerBooterVersion()
    throws IOException, XmlPullParserException
{
    if ( appassemblerVersion == null )
    {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        FileReader fileReader = new FileReader( getTestFile( "pom.xml" ) );
        try
        {
            appassemblerVersion = reader.read( fileReader ).getParent().getVersion();
        }
        finally
        {
            IOUtil.close( fileReader );
        }
    }
    return appassemblerVersion;
}
 
Example #8
Source File: JavaServiceWrapperDaemonGenerator.java    From appassembler with MIT License 6 votes vote down vote up
private static void writeFile( File outputFile, Reader reader )
    throws DaemonGeneratorException
{
    FileWriter out = null;

    try
    {
        outputFile.getParentFile().mkdirs();
        out = new FileWriter( outputFile );

        IOUtil.copy( reader, out );
    }
    catch ( IOException e )
    {
        throw new DaemonGeneratorException( "Error writing output file: " + outputFile.getAbsolutePath(), e );
    }
    finally
    {
        IOUtil.close( reader );
        IOUtil.close( out );
    }
}
 
Example #9
Source File: Platform.java    From appassembler with MIT License 6 votes vote down vote up
private String interpolateBaseDirAndRepo( String content )
{
    StringReader sr = new StringReader( content );
    StringWriter result = new StringWriter();

    Map<Object, Object> context = new HashMap<Object, Object>();

    context.put( "BASEDIR", StringUtils.quoteAndEscape( getBasedir(), '"' ) );
    context.put( "REPO", StringUtils.quoteAndEscape( getRepo(), '"' ) );
    InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader( sr, context, "@", "@" );
    try
    {
        IOUtil.copy( interpolationFilterReader, result );
    }
    catch ( IOException e )
    {
        // shouldn't happen...
    }
    return result.toString();
}
 
Example #10
Source File: AbstractDependencyTest.java    From maven-native with MIT License 6 votes vote down vote up
protected void writeFile( String filePath, String content )
    throws IOException
{
    FileOutputStream fs = new FileOutputStream( filePath );
    try
    {
        IOUtil.copy( content, fs );
    }
    finally
    {
        if ( fs != null )
        {
            IOUtil.close( fs );
        }
    }
}
 
Example #11
Source File: ExecMojo.java    From exec-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void createArgFile( String filePath, List<String> lines )
    throws IOException
{
    final String EOL = System.getProperty( "line.separator", "\\n" );

    FileWriter writer = null;
    try
    {
        writer = new FileWriter( filePath );
        for ( String line : lines )
        {
            writer.append( line ).append( EOL );
        }

    }
    finally
    {
        IOUtil.close( writer );
    }
}
 
Example #12
Source File: AgentJar.java    From promagent with Apache License 2.0 6 votes vote down vote up
void extractJar(File jar, ManifestTransformer manifestTransformer) throws MojoExecutionException {
    try (JarFile jarFile = new JarFile(jar)) {
        for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements(); ) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (manifestTransformer.canTransform(jarEntry)) {
                jarEntry = manifestTransformer.transform(jarEntry);
            }
            if (!jarEntry.isDirectory() && !content.contains(jarEntry.getName())) {
                content.add(jarEntry.getName());
                makeDirsRecursively(jarEntry.getName());
                try (InputStream in = getInputStream(jarEntry, jarFile, manifestTransformer)) {
                    jarOutputStream.putNextEntry(jarEntry);
                    IOUtil.copy(in, jarOutputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Error adding " + jar.getName() + " to target JAR: " + e.getMessage(), e);
    }
}
 
Example #13
Source File: AuxPropsImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private FileObject copyToCacheDir(InputStream in) throws IOException {
    FileObject cacheDir = cacheDir();
    FileObject file = cacheDir.getFileObject("checkstyle-checker.xml");
    if (file == null) {
        file = cacheDir.createData("checkstyle-checker", "xml");
    }
    InputStream inst = in;
    OutputStream outst = null;
    try {
        outst = file.getOutputStream();
        FileUtil.copy(in, outst);
    } finally {
        IOUtil.close(inst);
        IOUtil.close(outst);
    }
    return file;
}
 
Example #14
Source File: AccessQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<Pattern> loadPublicPackagesPatterns(Project project) {
    List<Pattern> toRet = new ArrayList<Pattern>();
    String[] params = PluginBackwardPropertyUtils.getPluginPropertyList(project,
            "publicPackages", "publicPackage", "manifest"); //NOI18N
    if (params != null) {
        toRet = prepareMavenPublicPackagesPatterns(params);
    } else {
        FileObject obj = project.getProjectDirectory().getFileObject(MANIFEST_PATH);
        if (obj != null) {
            InputStream in = null;
            try {
                in = obj.getInputStream();
                Manifest man = new Manifest();
                man.read(in);
                String value = man.getMainAttributes().getValue(ATTR_PUBLIC_PACKAGE);
                toRet = prepareManifestPublicPackagesPatterns(value);
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            } finally {
                IOUtil.close(in);
            }
        }
    }
    return toRet;
}
 
Example #15
Source File: MavenWhiteListQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Manifest getManifest(FileObject root) {
    FileObject manifestFo = root.getFileObject("META-INF/MANIFEST.MF");
    if (manifestFo != null) {
        InputStream is = null;
        try {
            is = manifestFo.getInputStream();
            return new Manifest(is);
        } catch (IOException ex) {
            //Exceptions.printStackTrace(ex);
        } finally {
            IOUtil.close(is);
        }
    }
    return null;

}
 
Example #16
Source File: AgentJar.java    From promagent with Apache License 2.0 5 votes vote down vote up
void addFile(File srcFile, String targetFileName, Directory targetDir) throws MojoExecutionException {
    String destPath = targetDir.getName() + targetFileName;
    if (content.contains(destPath)) {
        return;
    }
    makeDirsRecursively(destPath);
    content.add(destPath);
    try (InputStream in = new FileInputStream(srcFile)) {
        jarOutputStream.putNextEntry(new JarEntry(destPath));
        IOUtil.copy(in, jarOutputStream);
    } catch (IOException e) {
        throw new MojoExecutionException("Error adding " + srcFile.getName() + " to target JAR: " + e.getMessage(), e);
    }
}
 
Example #17
Source File: Mojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
JarOutputStream addToJar(final String name, final InputStream input, final JarOutputStream jar) throws IOException {
	try {
		debug("\t[Added to Jar]: " + name);
		jar.putNextEntry(new ZipEntry(name));
		IOUtil.copy(input, jar);
		jar.closeEntry();
	} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
	IOUtil.close(input);
	return jar;
}
 
Example #18
Source File: MavenNbModuleImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Xpp3Dom getModuleDom() throws UnsupportedEncodingException, IOException, XmlPullParserException {
    //TODO convert to FileOBject and have the IO stream from there..
    File file = getModuleXmlLocation();
    if (!file.exists()) {
        return null;
    }
    FileInputStream is = new FileInputStream(file);
    Reader reader = new InputStreamReader(is, "UTF-8"); //NOI18N
    try {
        return Xpp3DomBuilder.build(reader);
    } finally {
        IOUtil.close(reader);
    }
}
 
Example #19
Source File: AddIfExistsToEpisodeSchemaBindingsTest.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void transformationResourceIsAccessible() {
	InputStream is = RawXJC2Mojo.class
			.getResourceAsStream(RawXJC2Mojo.ADD_IF_EXISTS_TO_EPISODE_SCHEMA_BINDINGS_TRANSFORMATION_RESOURCE_NAME);
	Assert.assertNotNull(is);
	IOUtil.close(is);
}
 
Example #20
Source File: RawXJC2Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void addIfExistsToEpisodeSchemaBindings() throws MojoExecutionException {
	if (!getEpisode() || !isAddIfExistsToEpisodeSchemaBindings()) {
		return;
	}
	final File episodeFile = getEpisodeFile();
	if (!episodeFile.canWrite()) {
		getLog().warn(MessageFormat
				.format("Episode file [{0}] is not writable, could not add if-exists attributes.", episodeFile));
		return;
	}
	InputStream is = null;
	try {
		final TransformerFactory transformerFactory = TransformerFactory.newInstance();
		is = getClass().getResourceAsStream(ADD_IF_EXISTS_TO_EPISODE_SCHEMA_BINDINGS_TRANSFORMATION_RESOURCE_NAME);
		final Transformer addIfExistsToEpisodeSchemaBindingsTransformer = transformerFactory
				.newTransformer(new StreamSource(is));
		final DOMResult result = new DOMResult();
		addIfExistsToEpisodeSchemaBindingsTransformer.transform(new StreamSource(episodeFile), result);
		final DOMSource source = new DOMSource(result.getNode());
		final Transformer identityTransformer = transformerFactory.newTransformer();
		identityTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
		identityTransformer.transform(source, new StreamResult(episodeFile));
		getLog().info(MessageFormat.format("Episode file [{0}] was augmented with if-exists=\"true\" attributes.",
				episodeFile));
	} catch (TransformerException e) {
		throw new MojoExecutionException(MessageFormat.format(
				"Error augmenting the episode file [{0}] with if-exists=\"true\" attributes. Transformation failed with an unexpected error.",
				episodeFile), e);
	} finally {
		IOUtil.close(is);
	}
}
 
Example #21
Source File: XsdGeneratorHelper.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Document from parsing the XML within the provided xmlFile.
 *
 * @param xmlFile The XML file to be parsed.
 * @return The Document corresponding to the xmlFile.
 */
private static Document parseXmlToDocument(final File xmlFile) {
    Document result = null;
    Reader reader = null;
    try {
        reader = new FileReader(xmlFile);
        result = parseXmlStream(reader);
    } catch (FileNotFoundException e) {
        // This should never happen...
    } finally {
        IOUtil.close(reader);
    }

    return result;
}
 
Example #22
Source File: SimpleNamespaceResolver.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new SimpleNamespaceResolver which collects namespace data
 * from the provided XML file.
 *
 * @param xmlFile The XML file from which to collect namespace data, should not be null.
 */
public SimpleNamespaceResolver(final File xmlFile) {
    this.sourceFilename = xmlFile.getName();

    Reader reader = null;
    try {
        reader = new FileReader(xmlFile);
        initialize(reader);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("File [" + xmlFile + "] could not be found.");
    } finally {
        IOUtil.close(reader);
    }
}
 
Example #23
Source File: DockerFileUtilTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private File copyToTempDir(String resource) throws IOException {
    File dir = Files.createTempDirectory("d-m-p").toFile();
    File ret = new File(dir, "Dockerfile");
    try (FileOutputStream os = new FileOutputStream(ret)) {
        IOUtil.copy(getClass().getResourceAsStream(resource), os);
    }
    return ret;
}
 
Example #24
Source File: ApplicationComposerZipMojo.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void addFile(final JarOutputStream os, final File source, final String key) throws IOException {
    if (source.isDirectory()) {
        os.putNextEntry(new JarEntry(key));
        os.closeEntry();
    } else {
        os.putNextEntry(new JarEntry(key));
        final FileInputStream input = new FileInputStream(source);
        os.write(IOUtil.toByteArray(input));
        input.close();
        os.closeEntry();
    }
}
 
Example #25
Source File: AbstractDaemonGeneratorTest.java    From appassembler with MIT License 5 votes vote down vote up
protected File createFilteredFile( String file )
    throws IOException, FileNotFoundException, DaemonGeneratorException, XmlPullParserException
{
    String version = getAppAssemblerBooterVersion();
    Properties context = new Properties();
    context.setProperty( "appassembler.version", version );

    File tempPom = File.createTempFile( "appassembler", "tmp" );
    tempPom.deleteOnExit();

    InterpolationFilterReader reader =
        new InterpolationFilterReader( new FileReader( getTestFile( file ) ), context, "@", "@" );
    FileWriter out = null;

    try
    {
        out = new FileWriter( tempPom );

        IOUtil.copy( reader, out );
    }
    catch ( IOException e )
    {
        throw new DaemonGeneratorException( "Error writing output file: " + tempPom.getAbsolutePath(), e );
    }
    finally
    {
        IOUtil.close( reader );
        IOUtil.close( out );
    }
    return tempPom;
}
 
Example #26
Source File: DocumentationMojoTest.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Test
public void documentAdoc() throws MojoFailureException, MojoExecutionException, IOException {
    final File out = new File("target/DocumentationMojoTest/output.adoc");
    new DocumentationMojo() {{
        classes = new File("target/test-classes/org/apache/batchee/tools/maven/");
        output = out;
    }}.execute();
    final FileInputStream fis = new FileInputStream(out);
    assertEquals(
        "= myChildComponent\n" +
        "\n" +
        "a child comp\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|config2|2\n" +
        "|configByDefault|this is an important config\n" +
        "|expl|this one is less important\n" +
        "|===\n" +
        "\n" +
        "= myComponent\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|configByDefault|this is an important config\n" +
        "|expl|this one is less important\n" +
        "|===\n" +
        "\n" +
        "= org.apache.batchee.tools.maven.batchlet.SimpleBatchlet\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|fail|-\n" +
        "|sleep|-\n" +
        "|===\n" +
        "\n", IOUtil.toString(fis));
    fis.close();
}
 
Example #27
Source File: DocumentationMojoTest.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Test
public void documentMd() throws MojoFailureException, MojoExecutionException, IOException {
    final File out = new File("target/DocumentationMojoTest/output.adoc");
    new DocumentationMojo() {{
        classes = new File("target/test-classes/org/apache/batchee/tools/maven/");
        output = out;
        formatter = "md";
    }}.execute();
    final FileInputStream fis = new FileInputStream(out);
    assertEquals(
        "# myChildComponent\n" +
        "\n" +
        "a child comp\n" +
        "\n" +
        "* `config2`: 2\n" +
        "* `configByDefault`: this is an important config\n" +
        "* `expl`: this one is less important\n" +
        "\n" +
        "# myComponent\n" +
        "\n" +
        "* `configByDefault`: this is an important config\n" +
        "* `expl`: this one is less important\n" +
        "\n" +
        "# org.apache.batchee.tools.maven.batchlet.SimpleBatchlet\n" +
        "\n" +
        "* `fail`\n" +
        "* `sleep`\n" +
        "\n", IOUtil.toString(fis));
    fis.close();
}
 
Example #28
Source File: CapsuleMojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private void addMavenCapletClasses(final JarOutputStream jar) throws IOException {
	if (resolveApp || resolveCompileDep || resolveRuntimeDep || resolveProvidedDep || resolveSystemDep || resolveTestDep) {

		// get capsule maven classes
		final JarInputStream capsuleJarInputStream = new JarInputStream(new FileInputStream(resolveCapsuleMaven()));

		JarEntry entry;
		while ((entry = capsuleJarInputStream.getNextJarEntry()) != null) {
			if (entry.getName().contains("capsule") || entry.getName().equals(DEFAULT_CAPSULE_MAVEN_CLASS)) {
				addToJar(entry.getName(), new ByteArrayInputStream(IOUtil.toByteArray(capsuleJarInputStream)), jar);
			}
		}
		info("\t[Maven Caplet] Embedded Maven Caplet classes v" + capsuleMavenVersion + " (so capsule can resolve at launch)");
	}
}
 
Example #29
Source File: AppassemblerBooter.java    From appassembler with MIT License 5 votes vote down vote up
private static String interpolateBaseDirAndRepo( String content )
{
    StringReader sr = new StringReader( content );
    StringWriter result = new StringWriter();

    Map<Object, Object> context = new HashMap<Object, Object>();

    final String baseDir = System.getProperty( "basedir", System.getProperty( "app.home" ) );
    if ( baseDir != null && baseDir.length() > 0) {
        context.put( "BASEDIR", StringUtils.quoteAndEscape(baseDir, '"') );
    }

    final String repo = System.getProperty( "app.repo" );
    if ( repo != null && repo.length() > 0 ) {
        context.put("REPO", StringUtils.quoteAndEscape(repo, '"'));
    }

    InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader( sr, context, "@", "@" );
    try
    {
        IOUtil.copy( interpolationFilterReader, result );
    }
    catch ( IOException e )
    {
        // shouldn't happen...
    }
    return result.toString();
}
 
Example #30
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a file into a String.
 *
 * @param outFile The file to read.
 * @return String The content of the file.
 * @throws java.io.IOException when things go wrong.
 */
public static StringBuilder readXmlFile( File outFile )
    throws IOException
{
    try( Reader reader = ReaderFactory.newXmlReader( outFile ) )
    {
        return new StringBuilder( IOUtil.toString( reader ) );
    }
}