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:fr.duminy.tools.jgit.JGitToolboxTest.java

private static String addAndCommitFile(Git git) throws IOException, GitAPIException {
    File gitDirectory = git.getRepository().getDirectory().getParentFile();
    String filename = "file" + COUNTER++;
    IOUtils.write(filename + " content", new FileOutputStream(new File(gitDirectory, filename)));
    git.add().addFilepattern(filename).call();
    RevCommit call = git.commit().setMessage("add " + filename).call();
    String sha1 = call.getName();
    LOGGER.info("{}: Added file {} (sha1: {})", gitDirectory.getName(), filename, sha1);
    return sha1;//from  w w w  .j  ava2 s. c  om
}

From source file:com.athena.peacock.engine.action.ConfigurationAction.java

@Override
public void perform() {
    Assert.notNull(fileName, "filename cannot be null.");
    Assert.notNull(properties, "properties cannot be null.");

    File file = new File(fileName);

    Assert.isTrue(file.exists(), fileName + " does not exist.");
    Assert.isTrue(file.isFile(), fileName + " is not a file.");

    logger.debug("[{}] file's configuration will be changed.", fileName);

    try {/*  w w  w  .  j  a v  a  2 s  . c  o m*/
        String fileContents = IOUtils.toString(file.toURI());

        for (Property property : properties) {
            logger.debug("\"${{}}\" will be changed to \"{}\".", property.getKey(),
                    property.getValue().replaceAll("\\\\", ""));
            fileContents = fileContents.replaceAll("\\$\\{" + property.getKey() + "\\}", property.getValue());
        }

        FileOutputStream fos = new FileOutputStream(file);
        IOUtils.write(fileContents, fos);
        IOUtils.closeQuietly(fos);
    } catch (IOException e) {
        logger.error("IOException has occurred.", e);
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseCreator.control = EasyMock.createStrictControl();

    TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class);
    TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class);

    try {/*from   w w  w .j a v  a2  s .  c o m*/
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider);

    try {
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider);

    LicenseCreator.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseCreator.publicKey = keyPair.getPublic();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream);
    TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray();
}

From source file:edu.mayo.cts2.framework.plugin.service.lexevs.bulk.AbstractBulkDownloadController.java

protected void writeException(HttpServletResponse response, String message, int errorCode) {
    response.setContentType("text/plain; charset=utf-8");
    response.setStatus(errorCode);//from   w w w. j av a2s  .c  om

    try {
        IOUtils.write(message, response.getOutputStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:gobblin.data.management.copy.recovery.RecoveryHelperTest.java

@Test
public void testPersistFile() throws Exception {

    String content = "contents";

    File stagingDir = Files.createTempDir();
    stagingDir.deleteOnExit();//from w ww . j  a va  2s  .c  om

    File file = new File(stagingDir, "file");
    OutputStream os = new FileOutputStream(file);
    IOUtils.write(content, os);
    os.close();

    Assert.assertEquals(stagingDir.listFiles().length, 1);

    State state = new State();
    state.setProp(RecoveryHelper.PERSIST_DIR_KEY, this.tmpDir.getAbsolutePath());
    state.setProp(ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR, "/publisher");

    File recoveryDir = new File(RecoveryHelper.getPersistDir(state).get().toUri().getPath());

    FileSystem fs = FileSystem.getLocal(new Configuration());

    CopyableFile copyableFile = CopyableFile.builder(fs, new FileStatus(0, false, 0, 0, 0, new Path("/file")),
            new Path("/dataset"), CopyConfiguration.builder(fs, state.getProperties())
                    .preserve(PreserveAttributes.fromMnemonicString("")).build())
            .build();

    CopySource.setWorkUnitGuid(state, Guid.fromHasGuid(copyableFile));

    RecoveryHelper recoveryHelper = new RecoveryHelper(FileSystem.getLocal(new Configuration()), state);

    recoveryHelper.persistFile(state, copyableFile, new Path(file.getAbsolutePath()));

    Assert.assertEquals(stagingDir.listFiles().length, 0);
    Assert.assertEquals(recoveryDir.listFiles().length, 1);

    File fileInRecovery = recoveryDir.listFiles()[0];
    Assert.assertEquals(IOUtils.readLines(new FileInputStream(fileInRecovery)).get(0), content);

    Optional<FileStatus> fileToRecover = recoveryHelper.findPersistedFile(state, copyableFile,
            Predicates.<FileStatus>alwaysTrue());
    Assert.assertTrue(fileToRecover.isPresent());
    Assert.assertEquals(fileToRecover.get().getPath().toUri().getPath(), fileInRecovery.getAbsolutePath());

    fileToRecover = recoveryHelper.findPersistedFile(state, copyableFile, Predicates.<FileStatus>alwaysFalse());
    Assert.assertFalse(fileToRecover.isPresent());

}

From source file:at.tfr.securefs.ui.CopyFilesTest.java

@Test
public void testCopyFilesByWalk() throws Exception {

    // Given: NO target directory yet!!, the source file
    final String data = "Hallo Echo";
    try (OutputStream os = cp.getEncrypter(fromFile)) {
        IOUtils.write(data, os);
    }//from w  w  w  .  j ava  2s  . c o  m
    Assert.assertFalse(Files.exists(toRoot.resolve(DATA_FILES)));
    Assert.assertFalse(Files.exists(targetToFile));

    // When: copy of fromRoot to toRoot
    ProcessFiles pf = new ProcessFilesBean(new MockSecureFsCache());
    CopyFilesServiceBean cfb = new CopyFilesServiceBean(config, cp, pf, new MockSecureFsCache(), async);
    cfb.setFromPathName(fromRoot.toString());
    cfb.setToPathName(toRoot.toString());
    cfb.setNewSecret(newSecret);
    cfb.runCopyFiles();

    // Then: a target file is created in same subpath like sourceFile:
    Assert.assertTrue("subpath is not created", Files.exists(toRoot.resolve(DATA_FILES)));
    Assert.assertTrue("target file not created", Files.exists(targetToFile));

    // Then: the content of target file is decryptable with newSecret 
    //    and equals content of source file
    byte[] buf = new byte[data.getBytes().length];
    try (InputStream is = cp.getDecrypter(targetToFile, newSecret)) {
        IOUtils.read(is, buf);
    }
    Assert.assertEquals("failed to decrypt data", data, String.valueOf(data));
}

From source file:com.ngdata.hbaseindexer.rest.IndexerDefinitionsMessageBodyWriter.java

@Override
public void writeTo(Collection<IndexerDefinition> indices, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
        OutputStream outputStream) throws IOException, WebApplicationException {
    ArrayNode array = JsonNodeFactory.instance.arrayNode();
    IndexerDefinitionJsonSerDeser converter = IndexerDefinitionJsonSerDeser.INSTANCE;

    for (IndexerDefinition index : indices) {
        array.add(converter.toJson(index));
    }/*www . jav a  2s.c  o  m*/

    ObjectMapper objectMapper = new ObjectMapper();
    IOUtils.write(objectMapper.writeValueAsBytes(array), outputStream);
}

From source file:com.migo.controller.SysGeneratorController.java

/**
 * ??/*ww  w . java 2 s  .co  m*/
 */
@SysLog("??")
@RequestMapping("/code")
@RequiresPermissions("sys:generator:code")
public void code(String tables, HttpServletResponse response) throws IOException {
    String[] tableNames = new String[] {};
    tableNames = JSON.parseArray(tables).toArray(tableNames);

    byte[] data = sysGeneratorService.generatorCode(tableNames);

    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"migo.zip\"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");

    IOUtils.write(data, response.getOutputStream());
}

From source file:com.streamsets.datacollector.http.TestLogServlet.java

@Before
public void setup() throws Exception {
    server = null;/*from w  w w . ja  v  a2s.c  o  m*/
    baseDir = createTestDir();
    String log4jConf = new File(baseDir, "log4j.properties").getAbsolutePath();
    File logFile = new File(baseDir, "x.log");
    Writer writer = new FileWriter(log4jConf);
    IOUtils.write(LogUtils.LOG4J_APPENDER_STREAMSETS_FILE_PROPERTY + "=" + logFile.getAbsolutePath(), writer);
    writer.close();
    Assert.assertTrue(new File(baseDir, "etc").mkdir());
    Assert.assertTrue(new File(baseDir, "data").mkdir());
    Assert.assertTrue(new File(baseDir, "log").mkdir());
    Assert.assertTrue(new File(baseDir, "web").mkdir());
    System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, baseDir + "/etc");
    System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, baseDir + "/data");
    System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR, baseDir + "/log");
    System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR, baseDir + "/web");
}

From source file:com.samsung.sjs.ABackendTest.java

/**
 * Prefix the specified JS file with some of the testing primitives we assume,
 * placing the output in tmpdir and returning the resulting File.
 *//*w  w  w.  jav  a2 s. c om*/
public File prefixJS(Path tmpdir, File js) throws IOException, FileNotFoundException {
    File result = File.createTempFile("___", ".js", tmpdir.toFile());
    OutputStream out = new FileOutputStream(result);
    IOUtils.write("function assert(cond) { if (!cond) { throw Error(); } }\n\n", out);
    IOUtils.write("function print(s) { console.log(s); }\n\n", out);
    IOUtils.write("function printInt(s) { console.log(s); }\n\n", out);
    IOUtils.write("function printString(s) { console.log(s); }\n\n", out);
    IOUtils.write("function printFloat(s) { console.log(s); }\n\n", out);
    IOUtils.write("function printFloat10(s) { console.log(s.toFixed(10)); }\n\n", out);
    IOUtils.write("function itofp(s) { return s; }\n\n", out);
    IOUtils.write("function string_of_int(x) { return x.toString(); }\n\n", out);
    IOUtils.write("var TyHint = {};\n\n", out);
    IOUtils.copy(new FileReader(js), out);
    return result;
}