Java Code Examples for org.codehaus.plexus.util.IOUtil

The following are top voted examples for showing how to use org.codehaus.plexus.util.IOUtil. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: MavenWhiteListQueryImpl.java   View source code 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 2
Project: incubator-netbeans   File: AccessQueryImpl.java   View source code 6 votes vote down vote up
private static List<Pattern> loadPublicPackagesPatterns(Project project) {
    List<Pattern> toRet = new ArrayList<Pattern>();
    String[] params = PluginPropertyUtils.getPluginPropertyList(project, 
            MavenNbModuleImpl.GROUPID_MOJO, MavenNbModuleImpl.NBM_PLUGIN, //NOI18N
            "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 3
Project: incubator-netbeans   File: AuxPropsImpl.java   View source code 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 4
Project: promagent   File: AgentJar.java   View source code 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 5
Project: apache-maven-shade-plugin   File: DefaultShader.java   View source code 6 votes vote down vote up
private void addJavaSource( Set<String> resources, JarOutputStream jos, String name, InputStream is,
                            List<Relocator> relocators, boolean consistentDates )
    throws IOException
{
    JarEntry jarEntry = new ConsistentJarEntry( name, consistentDates );
    jos.putNextEntry( jarEntry );

    String sourceContent = IOUtil.toString( new InputStreamReader( is, "UTF-8" ) );

    for ( Relocator relocator : relocators )
    {
        sourceContent = relocator.applyToSourceContent( sourceContent );
    }

    final Writer writer = new OutputStreamWriter( jos, "UTF-8" );
    IOUtil.copy( sourceContent, writer );
    writer.flush();

    resources.add( name );
}
 
Example 6
Project: apache-maven-shade-plugin   File: ComponentsXmlResourceTransformerTest.java   View source code 6 votes vote down vote up
public void testConfigurationMerging()
    throws Exception
{

    XMLUnit.setNormalizeWhitespace( true );

    InputStream resourceAsStream = getClass().getResourceAsStream( "/components-1.xml" );
    transformer.processResource( "components-1.xml", resourceAsStream,
                                 Collections.<Relocator> emptyList() );
    resourceAsStream.close();
    InputStream resourceAsStream1 = getClass().getResourceAsStream( "/components-2.xml" );
    transformer.processResource( "components-1.xml", resourceAsStream1,
                                 Collections.<Relocator> emptyList() );
    resourceAsStream1.close();
    final InputStream resourceAsStream2 = getClass().getResourceAsStream( "/components-expected.xml" );
    Diff diff = XMLUnit.compareXML(
        IOUtil.toString( resourceAsStream2, "UTF-8" ),
        IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ) );
    //assertEquals( IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ),
    //              IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ).replaceAll("\r\n", "\n") );
    resourceAsStream2.close();
    XMLAssert.assertXMLIdentical( diff, true );
}
 
Example 7
Project: maven-seimicrawler-plugin   File: WebappStructureSerializer.java   View source code 6 votes vote down vote up
/**
 * Reads the {@link WebappStructure} from the specified file.
 *
 * @param file the file containing the webapp structure
 * @return the webapp structure
 * @throws IOException if an error occurred while reading the structure
 */
public WebappStructure fromXml( File file )
    throws IOException
{
    Reader reader = null;

    try
    {
        reader = ReaderFactory.newXmlReader( file );
        return (WebappStructure) XSTREAM.fromXML( reader );
    }
    finally
    {
        IOUtil.close( reader );
    }
}
 
Example 8
Project: maven-seimicrawler-plugin   File: WebappStructureSerializer.java   View source code 6 votes vote down vote up
/**
 * Saves the {@link WebappStructure} to the specified file.
 *
 * @param webappStructure the structure to save
 * @param targetFile the file to use to save the structure
 * @throws IOException if an error occurred while saving the webapp structure
 */
public void toXml( WebappStructure webappStructure, File targetFile )
    throws IOException
{
    // CHECKSTYLE_OFF: LineLength
    Writer writer = null;
    try
    {
        if ( !targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs() )
        {
            throw new IOException( "Could not create parent [" + targetFile.getParentFile().getAbsolutePath() + "]" );
        }

        if ( !targetFile.exists() && !targetFile.createNewFile() )
        {
            throw new IOException( "Could not create file [" + targetFile.getAbsolutePath() + "]" );
        }
        writer = WriterFactory.newXmlWriter( targetFile );
        XSTREAM.toXML( webappStructure, writer );
    }
    finally
    {
        IOUtil.close( writer );
    }
    // CHECKSTYLE_ON: LineLength
}
 
Example 9
Project: beyondj   File: Platform.java   View source code 6 votes vote down vote up
private String interpolateBaseDirAndRepo( String content )
{
    StringReader sr = new StringReader( content );
    StringWriter result = new StringWriter();

    Map context = new HashMap();

    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
Project: beyondj   File: JavaServiceWrapperDaemonGenerator.java   View source code 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 11
Project: beyondj   File: JavaServiceWrapperDaemonGenerator.java   View source code 6 votes vote down vote up
private static void writeFile( File outputFile, InputStream inputStream )
    throws DaemonGeneratorException
{
    FileOutputStream out = null;

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

        IOUtil.copy( inputStream, out );
    }
    catch ( IOException e )
    {
        throw new DaemonGeneratorException( "Error writing output file: " + outputFile.getAbsolutePath(), e );
    }
    finally
    {
        IOUtil.close( inputStream );
        IOUtil.close( out );
    }
}
 
Example 12
Project: beyondj   File: AbstractDaemonGeneratorTest.java   View source code 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 13
Project: beyondj   File: FormattedPropertiesTest.java   View source code 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 14
Project: gwtcoverage-maven-plugin   File: SourcesListMojo.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void execute() throws MojoExecutionException {
    final Log log = getLog();

    File usedTargetFile = new File(targetFile.getAbsolutePath());
    log.info("creating source list file '" + usedTargetFile.getAbsolutePath() + "'");

    try {
        if (!usedTargetFile.getParentFile().exists() && !usedTargetFile.getParentFile().mkdirs())
            throw new MojoExecutionException("cannot create targetdir: " + usedTargetFile.getParentFile().getAbsolutePath());
        BufferedWriter writer = new BufferedWriter(new FileWriter(usedTargetFile));

        scanDirectories(project.getCompileSourceRoots(), writer);
        scanDirectories(project.getTestCompileSourceRoots(), writer);
        IOUtil.close(writer);
    } catch (IOException e) {
        throw new MojoExecutionException("IO-Error while generating source list file '" + usedTargetFile + "'", e);
    }
}
 
Example 15
Project: exec-maven-plugin   File: ExecMojo.java   View source code 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 16
Project: extra-enforcer-rules   File: RequireEncoding.java   View source code 6 votes vote down vote up
protected String getEncoding( String requiredEncoding, File file, Log log )
    throws IOException
{
    FileInputStream fis = null;
    try
    {
        fis = new FileInputStream( file );
        CharsetDetector detector = new CharsetDetector();
        detector.setDeclaredEncoding( requiredEncoding );
        detector.setText( new BufferedInputStream( fis ) );
        CharsetMatch[] charsets = detector.detectAll();
        if ( charsets == null )
        {
            return null;
        }
        else
        {
            return charsets[0].getName();
        }
    }
    finally
    {
        IOUtil.close( fis );
    }
}
 
Example 17
Project: maven-native   File: AbstractDependencyTest.java   View source code 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 18
Project: flatten-maven-plugin   File: FlattenMojo.java   View source code 6 votes vote down vote up
/**
 * Writes the given <code>data</code> to the given <code>file</code> using the specified <code>encoding</code>.
 *
 * @param data is the {@link String} to write.
 * @param file is the {@link File} to write to.
 * @param encoding is the encoding to use for writing the file.
 * @throws MojoExecutionException if anything goes wrong.
 */
protected void writeStringToFile( String data, File file, String encoding )
    throws MojoExecutionException
{

    OutputStream outStream = null;
    Writer writer = null;
    try
    {
        outStream = new FileOutputStream( file );
        writer = new OutputStreamWriter( outStream, encoding );
        writer.write( data );
    }
    catch ( IOException e )
    {
        throw new MojoExecutionException( "Failed to write to " + file, e );
    }
    finally
    {
        // resource-handling not perfectly solved but we do not want to require java 1.7
        // and this is not a server application.
        IOUtil.close( writer );
        IOUtil.close( outStream );
    }
}
 
Example 19
Project: minifier-maven-plugin   File: ProcessFilesTask.java   View source code 6 votes vote down vote up
/**
 * Merges a list of source files. Create missing parent directories if
 * needed.
 *
 * @param mergedFile output file resulting from the merged step
 * @throws IOException when the merge step fails
 */
protected void merge(File mergedFile) throws IOException {
    mergedFile.getParentFile().mkdirs();

    try (InputStream sequence = new SequenceInputStream(new SourceFilesEnumeration(log, files, verbose, charset));
            OutputStream out = new FileOutputStream(mergedFile);
            InputStreamReader sequenceReader = new InputStreamReader(sequence, charset);
            OutputStreamWriter outWriter = new OutputStreamWriter(out, charset)) {
        log.info("Creating the merged file [" + ((verbose) ? mergedFile.getPath() : mergedFile.getName()) + "].");

        IOUtil.copy(sequenceReader, outWriter, bufferSize);
    } catch (IOException e) {
        log.error("Failed to concatenate files.", e);
        throw e;
    }
}
 
Example 20
Project: minifier-maven-plugin   File: ProcessFilesTask.java   View source code 6 votes vote down vote up
/**
 * Logs compression gains.
 *
 * @param mergedFile input file resulting from the merged step
 * @param minifiedFile output file resulting from the minify step
 */
void logCompressionGains(File mergedFile, File minifiedFile) {
    try {
        File temp = File.createTempFile(minifiedFile.getName(), ".gz");

        try (InputStream in = new FileInputStream(minifiedFile);
                OutputStream out = new FileOutputStream(temp);
                GZIPOutputStream outGZIP = new GZIPOutputStream(out)) {
            IOUtil.copy(in, outGZIP, bufferSize);
        }

        log.info("Uncompressed size: " + mergedFile.length() + " bytes.");
        log.info("Compressed size: " + minifiedFile.length() + " bytes minified (" + temp.length()
                + " bytes gzipped).");

        temp.deleteOnExit();
    } catch (IOException e) {
        log.debug("Failed to calculate the gzipped file size.", e);
    }
}
 
Example 21
Project: testability-explorer   File: TestabilityMojoTest.java   View source code 6 votes vote down vote up
public void testPluginPomWorksAndOutputsHtmlReportAndXmlReport() throws Exception {
  mojo = lookupMojoFromPom("xmlTestability.xml");
  assertNotNull(mojo);
  mojo.execute();

  File outputDir = (File) getVariableValueFromObject(mojo, "outputDirectory");
  String resultFile = (String) getVariableValueFromObject(mojo, "resultfile");
  File targetDir = (File) getVariableValueFromObject(mojo, "targetDirectory");

  File results = new File(outputDir, resultFile + ".html");
  assertTrue("HTML report should exist: " + results.getAbsolutePath(), results.exists());
  String content = IOUtil.toString(new FileReader(results));
  assertTrue("HTML report content: " + content, content.contains("TestabilityExplorerMojo"));

  results = new File(targetDir, resultFile + ".xml");
  assertTrue("XML report should exist: " + results.getAbsolutePath(), results.exists());
  content = IOUtil.toString(new FileReader(results));
  assertTrue("XML report content: " + content, content.contains("TestabilityExplorerMojo"));
}
 
Example 22
Project: appassembler   File: Platform.java   View source code 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 23
Project: appassembler   File: JavaServiceWrapperDaemonGenerator.java   View source code 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 24
Project: appassembler   File: JavaServiceWrapperDaemonGenerator.java   View source code 6 votes vote down vote up
private static void writeFile( File outputFile, InputStream inputStream )
    throws DaemonGeneratorException
{
    FileOutputStream out = null;

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

        IOUtil.copy( inputStream, out );
    }
    catch ( IOException e )
    {
        throw new DaemonGeneratorException( "Error writing output file: " + outputFile.getAbsolutePath(), e );
    }
    finally
    {
        IOUtil.close( inputStream );
        IOUtil.close( out );
    }
}
 
Example 25
Project: appassembler   File: AbstractDaemonGeneratorTest.java   View source code 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 26
Project: appassembler   File: FormattedPropertiesTest.java   View source code 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 27
Project: maven-external-version   File: FileStrategy.java   View source code 6 votes vote down vote up
@Override
public String getVersion( MavenProject mavenProject )
    throws ExternalVersionException
{
    String versionString = null;

    File versionFile = new File( mavenProject.getBasedir(), versionFilePath );
    BufferedReader reader = null;
    try
    {
        reader = new BufferedReader( new FileReader( versionFile ) );
        // just return the first line of the file, any other format is NOT supported.
        versionString = reader.readLine();
    }
    catch ( IOException e )
    {
        throw new ExternalVersionException( "Failed to read version file: [" + versionFile.getAbsolutePath() + "]",
                                            e );
    }
    finally
    {
        IOUtil.close( reader );
    }

    return versionString;
}
 
Example 28
Project: jdepend-maven-plugin   File: JDependMojoTest.java   View source code 6 votes vote down vote up
public void testJDependReportContent()
    throws IOException
{
    File generatedReport = new File( basedir, "target/jdepend-report.xml" );
    File classDirectory = new File( basedir, "target/classes" );

    String[] args = new String[3];

    args[0] = "-file";
    args[1] = generatedReport.getCanonicalPath();
    args[2] = classDirectory.getCanonicalPath();

    JDepend.main( args );
    ;
    assertTrue( "Generated report xml from " + generatedReport + " is not equal to expected output " + reportXML,
                IOUtil.contentEquals( new FileInputStream( generatedReport ), new FileInputStream( reportXML ) ) );
}
 
Example 29
Project: keytool   File: ResourceFixtures.java   View source code 6 votes vote down vote up
protected void copyURLToFile( URL url, File dest )
    throws IOException
{
    FileUtils.mkdir( dest.getParentFile().getAbsolutePath() );
    InputStream inputStream = url.openStream();
    try
    {
        OutputStream outputStream = new FileOutputStream( dest );
        try
        {
            IOUtil.copy( inputStream, outputStream );
        }
        finally
        {
            IOUtil.close( outputStream );
        }
    }
    finally
    {
        IOUtil.close( inputStream );
    }
}
 
Example 30
Project: maven-shade-plugin   File: DefaultShader.java   View source code 6 votes vote down vote up
private void addJavaSource(Set<String> resources, JarOutputStream jos, String name, InputStream is,
    List<Relocator> relocators)
    throws IOException {
  jos.putNextEntry(new JarEntry(name));

  String sourceContent = IOUtil.toString(new InputStreamReader(is, "UTF-8"));

  for (Relocator relocator : relocators) {
    sourceContent = relocator.applyToSourceContent(sourceContent);
  }

  OutputStreamWriter writer = new OutputStreamWriter(jos, "UTF-8");
  IOUtil.copy(sourceContent, writer);
  writer.flush();
  resources.add(name);
}
 
Example 31
Project: maven-shade-plugin   File: ClassDependencies.java   View source code 6 votes vote down vote up
private void readServiceEntry(String name, InputStream inputStream) throws IOException {
  if (!isIncluded(name)) {
    return;
  }
  String typeName = toClassFilePath(name.replace(SERVICES_ENTRY_PREFIX, ""));

  if (typeName.isEmpty()) {
    return;
  }

  boolean forcedInclusion = isSpecificallyIncluded(name);
  if (forcedInclusion) {
    included.add(typeName);
  }

  String content = IOUtil.toString(inputStream, Charsets.UTF_8.name());
  for (String providerType : SERVICES_SPLITTER.split(content)) {
    String providerName = toClassFilePath(providerType);
    services.put(typeName, providerName);

    if (forcedInclusion) {
      included.add(providerName);
    }
  }
}
 
Example 32
Project: maven-shade-plugin   File: ComponentsXmlResourceTransformerTest.java   View source code 6 votes vote down vote up
public void testConfigurationMerging()
    throws Exception
{

    XMLUnit.setNormalizeWhitespace( true );

    transformer.processResource( "components-1.xml", getClass().getResourceAsStream( "/components-1.xml" ),
                                 Collections.<Relocator> emptyList() );
    transformer.processResource( "components-1.xml", getClass().getResourceAsStream( "/components-2.xml" ),
                                 Collections.<Relocator> emptyList() );
    Diff diff = XMLUnit.compareXML(
        IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ),
        IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ) );
    //assertEquals( IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ),
    //              IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ).replaceAll("\r\n", "\n") );
    XMLAssert.assertXMLIdentical( diff, true );
}
 
Example 33
Project: saguaro   File: LicenseUtil.java   View source code 6 votes vote down vote up
public static void download(LicenseInfo licenseInfo, File outputDir) throws IOException {
    File path = new File(outputDir, "raw/" + licenseInfo.getKey() + ".txt");
    path.getParentFile().mkdirs();
    URL url = new URL(licenseInfo.getUrl());

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new BufferedInputStream(url.openConnection().getInputStream());
        out = new BufferedOutputStream(new FileOutputStream(path));

        IOUtil.copy(in, out);
    } finally {
        if (in != null) in.close();
        if (out != null) out.close();
    }
}
 
Example 34
Project: D3Launcher   File: PackBuilder.java   View source code 6 votes vote down vote up
public void copy() throws IOException
{
    for (Dependency mod : mods)
    {
        FileUtils.copyFileToDirectory(MavenHelper.getFile(mod), modsFolder);
    }
    for (Dependency config : configs)
    {
        File configFile = MavenHelper.getFile(config);
        if (config.getType().equals("zip"))
        {
            ZipFile zipFile = new ZipFile(configFile);
            Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
            while (enumeration.hasMoreElements())
            {
                ZipEntry zipEntry = enumeration.nextElement();
                LOGGER.debug(zipEntry.getName());
                if (zipEntry.isDirectory())
                    //noinspection ResultOfMethodCallIgnored
                    new File(packData.getInstanceFolder(side), zipEntry.getName()).mkdir();
                else IOUtil.copy(zipFile.getInputStream(zipEntry), new FileWriter(new File(packData.getInstanceFolder(side), zipEntry.getName())));
            }
        }
        else FileUtils.copyFileToDirectory(configFile, packData.getInstanceFolder(side));
    }
}
 
Example 35
Project: keytool-maven-plugin   File: ResourceFixtures.java   View source code 6 votes vote down vote up
protected void copyURLToFile( URL url, File dest )
    throws IOException
{
    FileUtils.mkdir( dest.getParentFile().getAbsolutePath() );
    InputStream inputStream = url.openStream();
    try
    {
        OutputStream outputStream = new FileOutputStream( dest );
        try
        {
            IOUtil.copy( inputStream, outputStream );
        }
        finally
        {
            IOUtil.close( outputStream );
        }
    }
    finally
    {
        IOUtil.close( inputStream );
    }
}
 
Example 36
Project: hydromatic-resource   File: ResourceMojo.java   View source code 6 votes vote down vote up
@Override protected void generate() throws Exception {
  File pd = new File(outputDirectory, packageName.replaceAll("\\.", "/"));
  if (getLog().isDebugEnabled()) {
    getLog().info("Creating directory " + pd);
  }
  pd.mkdirs();

  InputStream in = null;
  try {
    in = ResourceMojo.class.getResourceAsStream(
            "/net/hydromatic/resource/Resources.java");
    String template = IOUtil.toString(in, "UTF-8");
    template = template.replace("package net.hydromatic.resource;",
        "package " + packageName + ";");
    saveResult(new File(pd, "Resources.java"), template);
  } finally {
    if (in != null) {
      in.close();
    }
  }
}
 
Example 37
Project: mvn-fluid-cd   File: JenkinsDefaultMaven.java   View source code 6 votes vote down vote up
private String getMavenVersion()
{
    Properties props = new Properties();

    InputStream is = getClass().getResourceAsStream( "/META-INF/maven/org.apache.maven/maven-core/pom.properties" );
    if ( is != null )
    {
        try
        {
            props.load( is );
        }
        catch ( IOException e )
        {
            logger.debug( "Failed to read Maven version", e );
        }
        IOUtil.close( is );
    }

    return props.getProperty( "version", "unknown-version" );
}
 
Example 38
Project: pomutils   File: PersistentVersionSelector.java   View source code 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 39
Project: pomutils   File: PersistentVersionSelector.java   View source code 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 40
Project: codefather   File: TemplateCollector.java   View source code 6 votes vote down vote up
private Properties tryToReadConfig(File dir, String tname) {
    String fname = tname + ".properties";
    File f = new File(dir, fname);
    if (!f.exists()) {
        throw new CodeFatherException( "no-properties-file","Not found : "+dir.getAbsolutePath()+"/"+fname);
    }
    Properties prop = new Properties();
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(f);
        prop.load(fin);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Failed to read properties "+dir.getAbsolutePath()+fname);
    } finally {
        IOUtil.close(fin);
    }
    return prop;
}