Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:it.flosslab.mvc.presentation.action.anagrafica.AnagraficaAction.java

private ActionForward performSearch(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String tipo) {
    SoggettoDelegate soggettoDelegate = SoggettoDelegate.getInstance();
    List<SoggettoVO> soggetti = new ArrayList<SoggettoVO>();
    if ("F".equals(tipo)) {
        String prefixSurname = request.getParameter("q").toLowerCase();
        soggetti = soggettoDelegate.getListaPersonaFisica(1, prefixSurname, "", "");
    }/*w  ww.j  a va2  s .c o  m*/
    if ("G".equals(tipo)) {
        String denominazione = request.getParameter("q").toLowerCase();
        soggetti = soggettoDelegate.getListaPersonaGiuridica(1, denominazione, "");
    }
    try {
        OutputStream out = response.getOutputStream();
        response.setContentType("text/plain");
        IOUtils.write(this.createRenderedList(soggetti, tipo), out);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:ezbake.deployer.utilities.Utilities.java

public static void appendFilesInTarArchive(OutputStream output, byte[] currentArchive,
        Iterable<ArtifactDataEntry> filesToAdd) throws DeploymentException {
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    try (GZIPOutputStream gzs = new GZIPOutputStream(output)) {
        try (ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) {
            try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(currentArchive))) {
                try (TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzip)) {
                    TarArchiveEntry tarEntry = null;

                    while ((tarEntry = tarInputStream.getNextTarEntry()) != null) {
                        aos.putArchiveEntry(tarEntry);
                        IOUtils.copy(tarInputStream, aos);
                        aos.closeArchiveEntry();
                    }//from   w  w w  . ja  va2  s. c  o m
                }
            }

            for (ArtifactDataEntry entry : filesToAdd) {
                aos.putArchiveEntry(entry.getEntry());
                IOUtils.write(entry.getData(), aos);
                aos.closeArchiveEntry();
            }
        }
    } catch (ArchiveException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * ??/*from  w w  w. j a v a 2  s  .com*/
 * 
 * @param pubFile public file
 * @param priFile private file
 * @throws IOException IOException
 */
@SuppressWarnings("PMD.PrematureDeclaration")
protected void generater(File pubFile, File priFile) throws IOException {
    try {
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom secrand = new SecureRandom();
        keygen.initialize(KEY_SIZE, secrand);
        KeyPair keys = keygen.genKeyPair();
        PublicKey pubkey = keys.getPublic();
        PrivateKey prikey = keys.getPrivate();
        byte[] priKey = Base64.encodeBase64(prikey.getEncoded());
        byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded());
        if (pubFile.exists()) {
            throw new IOException(pubFile.getPath() + " is exist!");
        }
        if (priFile.exists()) {
            throw new IOException(priFile.getPath() + " is exist!");
        }
        OutputStream pubOutput = new FileOutputStream(pubFile);
        try {
            IOUtils.write(pubKey, pubOutput);
        } finally {
            IOUtils.closeQuietly(pubOutput);
        }
        OutputStream priOutput = new FileOutputStream(priFile);
        try {
            IOUtils.write(priKey, priOutput);
        } finally {
            IOUtils.closeQuietly(priOutput);
        }
    } catch (NoSuchAlgorithmException e) {
        log.error("?", e);
    }
}

From source file:ch.cyberduck.core.spectra.SpectraMultipleDeleteFeatureTest.java

@Test
public void testDeleteFile() throws Exception {
    final Host host = new Host(new SpectraProtocol() {
        @Override/*from   w w  w .  j a v a 2s.  c om*/
        public Scheme getScheme() {
            return Scheme.http;
        }
    }, System.getProperties().getProperty("spectra.hostname"),
            Integer.valueOf(System.getProperties().getProperty("spectra.port")),
            new Credentials(System.getProperties().getProperty("spectra.user"),
                    System.getProperties().getProperty("spectra.key")));
    final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(),
            new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("cyberduck", EnumSet.of(Path.Type.volume));
    final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final byte[] content = RandomUtils.nextBytes(1024);
    final HttpResponseOutputStream<StorageObject> out = new S3WriteFeature(session).write(test,
            new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.write(content, out);
    out.close();
    assertTrue(new S3FindFeature(session).find(test));
    new S3MultipleDeleteFeature(session).delete(Arrays.asList(test, test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    assertFalse(new S3FindFeature(session).find(test));
    session.close();
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/*from  w  ww.  j a  v a  2s .  c  o m*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from  www  .  ja  v  a2s  .  com
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#jenkins.war";
        configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir);
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();/*from ww w  .  j  a v  a 2  s  .  com*/
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:hudson.remoting.DefaultClassFilterTest.java

/**
 * Checks that the overrides are loaded when the property is provided and the file exists.
 *///from   w  w w.  j  a v a 2 s  .  c  o m
@Test
public void testDefaultsOverrideExists() throws Exception {
    List<String> badClasses = Arrays.asList("eric.Clapton", "john.winston.ono.Lennon", "jimmy.Page");
    File f = folder.newFile("overrides.txt");
    FileOutputStream fos = new FileOutputStream(f);
    try {
        for (String s : badClasses) {
            IOUtils.write(s, fos);
            IOUtils.write("\n", fos);
        }
    } finally {
        fos.close();
    }
    setOverrideProperty(f.getAbsolutePath());
    assertThat("Default blacklist should not be used", defaultBadClasses, everyItem(is(not(blacklisted()))));
    assertThat("Custom blacklist should be used", badClasses, everyItem(is(blacklisted())));
    assertThat("Custom blacklist is not allowing some classes", defaultOKClasses,
            everyItem(is(not(blacklisted()))));
}

From source file:com.greenpepper.report.FileReportGenerator.java

/** {@inheritDoc} */
public void closeReport(Report report) throws IOException, URISyntaxException {
    FileWriter out = null;//from   w  w  w . jav a2 s  .  com
    try {
        File reportFile = new File(reportsDirectory, outputNameOf(report));
        String documentUri = report.getDocumentUri();
        if (documentUri != null) {
            if (reportFile.equals(new File(new URI(documentUri)))) {
                reportFile = new File(reportFile.getAbsolutePath() + ".out");
            }
        }
        IOUtil.createDirectoryTree(reportFile.getParentFile());
        StringWriter strOut = new StringWriter();
        report.printTo(strOut);
        strOut.flush();
        out = new FileWriter(reportFile);
        String reportString = strOut.toString();
        LOGGER.trace("Final Report to be written :\n {}", reportString);
        IOUtils.write(reportString, out);
        out.flush();
    } finally {
        IOUtil.closeQuietly(out);
    }
}

From source file:com.cloudera.csd.tools.MetricDescriptorValidatorTool.java

@Override
public void run(CommandLine cmdLine, OutputStream out, OutputStream err) throws Exception {
    Preconditions.checkNotNull(cmdLine);
    Preconditions.checkNotNull(out);/*from   ww w  . j a  v a 2 s.  c o  m*/
    Preconditions.checkNotNull(err);

    Writer writer = new OutputStreamWriter(out, "UTF-8");
    try {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(DefaultValidatorConfiguration.class);
        @SuppressWarnings("unchecked")
        Parser<ServiceMonitoringDefinitionsDescriptor> parser = ctx.getBean("mdlParser", Parser.class);
        @SuppressWarnings("unchecked")
        DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> validator = ctx
                .getBean("serviceMonitoringDefinitionsDescriptorValidator", DescriptorValidator.class);
        ValidationRunner runner = new DescriptorRunner<ServiceMonitoringDefinitionsDescriptor>(parser,
                validator);
        if (!runner.run(cmdLine.getOptionValue(OPT_MDL.getLongOpt()), writer)) {
            throw new RuntimeException("Validation failed.");
        }
    } catch (Exception ex) {
        LOG.error("Could not run validation tool.", ex);
        IOUtils.write(ex.getMessage() + "\n", err);
        throw ex;
    } finally {
        writer.close();
    }
}