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:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 *///from   w  ww.  j a  v a2s . c  o  m
public synchronized boolean createKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#createKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    boolean isComplete = false;
    OutputStream publicStream = null;
    OutputStream privateStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            if (!(keyDirectory.mkdirs())) {
                throw new KeyManagementException(
                        "Configured key directory does not exist and unable to create it");
            }
        }

        keyDirectory.setExecutable(true, true);

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm());
        keyGenerator.initialize(keyConfig.getKeySize(), random);
        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (keyPair != null) {
            File privateFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);
            File publicFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (!(privateFile.createNewFile())) {
                throw new IOException("Failed to store private key file");
            }

            if (!(publicFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            privateFile.setWritable(true, true);
            publicFile.setWritable(true, true);

            privateStream = new FileOutputStream(privateFile);
            publicStream = new FileOutputStream(publicFile);

            IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream);
            IOUtils.write(keyPair.getPublic().getEncoded(), publicStream);

            // assume success, as we'll get an IOException if the write failed
            isComplete = true;
        } else {
            throw new KeyManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (publicStream != null) {
            IOUtils.closeQuietly(publicStream);
        }

        if (privateStream != null) {
            IOUtils.closeQuietly(privateStream);
        }
    }

    return isComplete;
}

From source file:com.jayway.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void allows_settings_default_control_name_using_instance_configuration() throws IOException {
    File file = folder.newFile("filename.txt");
    IOUtils.write("Something21", new FileOutputStream(file));

    given().config(config().multiPartConfig(multiPartConfig().with().defaultControlName("something")))
            .multiPart(file).when().post("/fileUploadWithControlNameEqualToSomething").then()
            .body("size", greaterThan(10)).body("name", equalTo("something"))
            .body("originalName", equalTo("filename.txt"));
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestTextSpoolDirSource.java

@Test
public void testGbkEncodedFile() throws Exception {
    SpoolDirSource source = createSource("GBK");
    SourceRunner runner = new SourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane").build();
    runner.runInit();//from   w  w w.  ja  v  a2 s  . c  o  m
    try {
        // Write out a gbk-encoded file.
        File f = new File(createTestDir(), "test_gbk.log");
        Writer writer = new OutputStreamWriter(new FileOutputStream(f), "GBK");
        IOUtils.write(UTF_STRING, writer);
        writer.close();

        // Read back the file to verify its content is gbk-encoded.
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
        Assert.assertEquals(GBK_STRING, reader.readLine());
        reader.close();

        BatchMaker batchMaker = SourceRunner.createTestBatchMaker("lane");
        Assert.assertEquals("-1", source.produce(f, "0", 10, batchMaker));
        StageRunner.Output output = SourceRunner.getOutput(batchMaker);
        List<Record> records = output.getRecords().get("lane");
        Assert.assertNotNull(records);
        Assert.assertEquals(1, records.size());
        Assert.assertEquals(UTF_STRING.substring(0, 10),
                records.get(0).get().getValueAsMap().get("text").getValueAsString());
        Assert.assertTrue(records.get(0).has("/truncated"));
    } finally {
        runner.runDestroy();
    }
}

From source file:io.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void allows_settings_default_control_name_using_instance_configuration() throws IOException {
    File file = folder.newFile("filename.txt");
    IOUtils.write("Something21", new FileOutputStream(file));

    RestAssuredMockMvc.given()/*  w  w  w.  j  ava 2 s  .  c o  m*/
            .config(RestAssuredMockMvcConfig.config()
                    .multiPartConfig(multiPartConfig().with().defaultControlName("something")))
            .multiPart(file).when().post("/fileUploadWithControlNameEqualToSomething").then()
            .body("size", greaterThan(10)).body("name", equalTo("something"))
            .body("originalName", equalTo("filename.txt"));
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirSourceOnErrorHandling.java

private SpoolDirSource createSourceIOEx() throws Exception {
    String dir = createTestDir();
    File file1 = new File(dir, "file-0.json").getAbsoluteFile();
    Writer writer = new FileWriter(file1);
    IOUtils.write("[1,", writer);
    writer.close();//from  w ww .j  a va2s. c  om
    File file2 = new File(dir, "file-1.json").getAbsoluteFile();
    writer = new FileWriter(file2);
    IOUtils.write("[2]", writer);
    writer.close();

    SpoolDirConfigBean conf = new SpoolDirConfigBean();
    conf.dataFormat = DataFormat.JSON;
    conf.spoolDir = dir;
    conf.batchSize = 10;
    conf.overrunLimit = 100;
    conf.poolingTimeoutSecs = 1;
    conf.filePattern = "file-[0-9].json";
    conf.maxSpoolFiles = 10;
    conf.initialFileToProcess = null;
    conf.dataFormatConfig.compression = Compression.NONE;
    conf.dataFormatConfig.filePatternInArchive = "*";
    conf.errorArchiveDir = null;
    conf.postProcessing = PostProcessingOptions.ARCHIVE;
    conf.archiveDir = dir;
    conf.retentionTimeMins = 10;
    conf.dataFormatConfig.jsonContent = JsonMode.ARRAY_OBJECTS;
    conf.dataFormatConfig.jsonMaxObjectLen = 100;
    conf.dataFormatConfig.onParseError = OnParseError.ERROR;
    conf.dataFormatConfig.maxStackTraceLines = 0;

    return new SpoolDirSource(conf);
}

From source file:gov.nih.nci.caintegrator.external.caarray.CaArrayFacadeTest.java

/**
 * Sets up objects necessary for unit testing.
 * @throws Exception on error/*from w  w  w.  j  ava 2s. co m*/
 */
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    caArrayFacade = new CaArrayFacadeImpl();

    dataService = mock(DataService.class);
    when(dataService.getDataSet(any(DataSetRequest.class))).thenAnswer(new Answer<DataSet>() {
        @SuppressWarnings("unused")
        @Override
        public DataSet answer(InvocationOnMock invocation) throws Throwable {
            DataSetRequest r = (DataSetRequest) invocation.getArguments()[0];
            DataSet result = new DataSet();
            result.getDesignElements().add(probeSet1);
            result.getDesignElements().add(probeSet2);
            for (CaArrayEntityReference ref : r.getHybridizations()) {
                ArrayDesign design = new ArrayDesign();
                design.setName("test design");
                Hybridization hybridization = new Hybridization();
                hybridization.setArrayDesign(design);

                HybridizationData data = new HybridizationData();
                data.setHybridization(hybridization);
                result.getDatas().add(data);
                FloatColumn column = new FloatColumn();
                column.setValues(new float[] { 1.1f, 2.2f });
                data.getDataColumns().add(column);
            }
            return result;
        }
    });
    when(dataService.streamFileContents(any(CaArrayEntityReference.class), anyBoolean()))
            .thenAnswer(new Answer<FileStreamableContents>() {

                @Override
                public FileStreamableContents answer(InvocationOnMock invocation) throws Throwable {
                    StringBuffer dataFile = new StringBuffer();
                    dataFile.append("ID\tChromosome\tPhysical.Position\tlogratio\n");
                    dataFile.append("A_probeSet1\t1\t123456\t0.05\n");
                    dataFile.append("DarkCorner\t1\t56789\t-0.0034\n");
                    dataFile.append("*\n");
                    dataFile.append("A_probeSet2\t1\t98765\t-0.1234\n");

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    GZIPOutputStream gzos = new GZIPOutputStream(baos);
                    IOUtils.write(dataFile.toString().getBytes(), gzos);

                    byte[] gzippedBytes = baos.toByteArray();
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(gzippedBytes);
                    FileStreamableContents contents = new FileStreamableContents();
                    contents.setContentStream(new DirectRemoteInputStream(byteArrayInputStream, false));
                    return contents;
                }
            });

    searchService = mock(SearchService.class);
    when(searchService.searchForExperiments(any(ExperimentSearchCriteria.class), any(LimitOffset.class)))
            .thenAnswer(new Answer<SearchResult<Experiment>>() {

                @Override
                public SearchResult<Experiment> answer(InvocationOnMock invocation) throws Throwable {
                    SearchResult<Experiment> result = new SearchResult<Experiment>();
                    ExperimentSearchCriteria crit = (ExperimentSearchCriteria) invocation.getArguments()[0];
                    if (!StringUtils.equals("no-experiment", crit.getPublicIdentifier())) {
                        Experiment experiment = new Experiment();
                        experiment.setPublicIdentifier(crit.getPublicIdentifier());
                        experiment.setId(crit.getPublicIdentifier());
                        experiment.setLastDataModificationDate(DateUtils.addDays(new Date(), -1));
                        result.getResults().add(experiment);
                    }
                    return result;
                }
            });
    when(searchService.searchForBiomaterials(any(BiomaterialSearchCriteria.class), any(LimitOffset.class)))
            .thenAnswer(new Answer<SearchResult<Biomaterial>>() {
                @Override
                public SearchResult<Biomaterial> answer(InvocationOnMock invocation) throws Throwable {
                    Biomaterial sample = new Biomaterial();
                    sample.setName("sample");
                    sample.setLastModifiedDataTime(DateUtils.addDays(new Date(), -1));
                    SearchResult<Biomaterial> result = new SearchResult<Biomaterial>();
                    result.getResults().add(sample);
                    result.setMaxAllowedResults(-1);
                    return result;
                }
            });
    when(searchService.searchForFiles(any(FileSearchCriteria.class), any(LimitOffset.class)))
            .then(new Answer<SearchResult<File>>() {
                @Override
                public SearchResult<File> answer(InvocationOnMock invocation) throws Throwable {
                    SearchResult<File> result = new SearchResult<File>();
                    File file = new File();
                    file.setMetadata(new FileMetadata());
                    file.getMetadata().setName("filename");
                    result.getResults().add(file);
                    return result;
                }
            });
    when(searchService.searchForHybridizations(any(HybridizationSearchCriteria.class), any(LimitOffset.class)))
            .thenAnswer(new Answer<SearchResult<Hybridization>>() {
                @Override
                public SearchResult<Hybridization> answer(InvocationOnMock invocation) throws Throwable {
                    ArrayDesign design = new ArrayDesign();
                    design.setName("test design");

                    Hybridization hybridization = new Hybridization();
                    hybridization.setArrayDesign(design);

                    SearchResult<Hybridization> result = new SearchResult<Hybridization>();
                    result.getResults().add(hybridization);
                    return result;
                }
            });
    when(searchService.searchByExample(any(ExampleSearchCriteria.class), any(LimitOffset.class)))
            .then(new Answer<SearchResult<AbstractCaArrayEntity>>() {
                @Override
                public SearchResult<AbstractCaArrayEntity> answer(InvocationOnMock invocation)
                        throws Throwable {
                    ExampleSearchCriteria<AbstractCaArrayEntity> crit = (ExampleSearchCriteria<AbstractCaArrayEntity>) invocation
                            .getArguments()[0];
                    SearchResult<AbstractCaArrayEntity> result = new SearchResult<AbstractCaArrayEntity>();
                    result.getResults().add(crit.getExample());
                    return result;
                }
            });
    when(searchService.searchForQuantitationTypes(any(QuantitationTypeSearchCriteria.class)))
            .thenAnswer(new Answer<List<QuantitationType>>() {
                @Override
                public List<QuantitationType> answer(InvocationOnMock invocation) throws Throwable {
                    List<QuantitationType> results = new ArrayList<QuantitationType>();
                    QuantitationType quantitationType = new QuantitationType();
                    quantitationType.setName("DataMatrixCopyNumber.Log2Ratio");
                    results.add(quantitationType);
                    return results;
                }
            });

    CaArrayServiceFactory factory = mock(CaArrayServiceFactory.class);
    when(factory.createDataService(any(ServerConnectionProfile.class))).thenReturn(dataService);
    when(factory.createSearchService(any(ServerConnectionProfile.class))).thenReturn(searchService);
    caArrayFacade.setServiceFactory(factory);

    CaIntegrator2Dao dao = mock(CaIntegrator2Dao.class);
    when(dao.getPlatform(anyString())).thenReturn(createTestPlatform());
    caArrayFacade.setDao(dao);
}

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testRefsConfigs() throws IOException {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());/*  w ww  .  j  a  va 2s .co m*/
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "hello.txt"));
    IOUtils.write("secret", writer);
    writer.close();
    Configuration conf = new Configuration();

    String home = System.getenv("HOME");

    conf.set("a", "@hello.txt@");
    conf.set("aa", "${file(\"hello.txt\")}");
    conf.set("aaa", "${file('hello.txt')}");
    conf.set("b", "$HOME$");
    conf.set("bb", "${env(\"HOME\")}");
    conf.set("bbb", "${env('HOME')}");
    conf.set("x", "X");
    Assert.assertEquals("secret", conf.get("a", null));
    Assert.assertEquals("secret", conf.get("aa", null));
    Assert.assertEquals("secret", conf.get("aaa", null));
    Assert.assertEquals(home, conf.get("b", null));
    Assert.assertEquals(home, conf.get("bb", null));
    Assert.assertEquals(home, conf.get("bbb", null));
    Assert.assertEquals("X", conf.get("x", null));

    Configuration uconf = conf.getUnresolvedConfiguration();
    Assert.assertEquals("@hello.txt@", uconf.get("a", null));
    Assert.assertEquals("${file(\"hello.txt\")}", uconf.get("aa", null));
    Assert.assertEquals("${file('hello.txt')}", uconf.get("aaa", null));
    Assert.assertEquals("$HOME$", uconf.get("b", null));
    Assert.assertEquals("${env(\"HOME\")}", uconf.get("bb", null));
    Assert.assertEquals("${env('HOME')}", uconf.get("bbb", null));
    Assert.assertEquals("X", uconf.get("x", null));

    writer = new FileWriter(new File(dir, "config.properties"));
    conf.save(writer);
    writer.close();

    conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    uconf = conf.getUnresolvedConfiguration();
    Assert.assertEquals("@hello.txt@", uconf.get("a", null));
    Assert.assertEquals("${file(\"hello.txt\")}", uconf.get("aa", null));
    Assert.assertEquals("${file('hello.txt')}", uconf.get("aaa", null));
    Assert.assertEquals("$HOME$", uconf.get("b", null));
    Assert.assertEquals("${env(\"HOME\")}", uconf.get("bb", null));
    Assert.assertEquals("${env('HOME')}", uconf.get("bbb", null));
    Assert.assertEquals("X", uconf.get("x", null));
}

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

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/*from www .jav  a 2  s .  co m*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        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 webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#jenkins.war";
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        configurator.setTargetJenkinsHomeBaseDir("/some/silly/random/homeDir");

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

        // 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 {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

private static byte[] hash(String data) throws Exception {
    DigestCalculator calc = createDigestCalculator(ALGORITHM);
    IOUtils.write(data, calc.getOutputStream());

    return calc.getDigest();
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleOpenShiftWebAppTarBall() throws IOException, ArchiveException {
    ByteArrayInputStream bis = new ByteArrayInputStream(createSampleAppTarBall(ArtifactType.WebApp).array());
    CompressorInputStream cis = new GzipCompressorInputStream(bis);
    ArchiveInputStream ais = new TarArchiveInputStream(cis);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bis.available() + 2048);
    CompressorOutputStream cos = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(cos);

    ArchiveEntry nextEntry;/*w  ww. ja va  2  s . co  m*/
    while ((nextEntry = ais.getNextEntry()) != null) {
        aos.putArchiveEntry(nextEntry);
        IOUtils.copy(ais, aos);
        aos.closeArchiveEntry();
    }
    ais.close();
    cis.close();
    bis.close();

    TarArchiveEntry entry = new TarArchiveEntry(
            Paths.get(".openshift", CONFIG_DIRECTORY, "/standalone.xml").toFile());
    byte[] xmlData = SAMPLE_STANDALONE_DATA.getBytes();
    entry.setSize(xmlData.length);
    aos.putArchiveEntry(entry);
    IOUtils.write(xmlData, aos);
    aos.closeArchiveEntry();

    aos.finish();
    cos.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}