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, String encoding) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the specified character encoding.

Usage

From source file:ch.ifocusit.livingdoc.plugin.baseMojo.AbstractDocsGeneratorMojo.java

/**
 * Simple write content to a file./*from w w w  . j  a v  a  2 s.  co m*/
 *
 * @param newContent : file content
 * @param output     : destination file
 * @throws MojoExecutionException
 */
protected void write(final String newContent, final File output) throws MojoExecutionException {
    try {
        output.getParentFile().mkdirs();
        IOUtils.write(newContent, new FileOutputStream(output), Charset.defaultCharset());
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Unable to write output file '%s' !", output), e);
    }
}

From source file:com.acmutv.ontoqa.tool.io.IOManager.java

/**
 * Write on a resource./*from ww  w.  j  a v  a2 s .com*/
 * @param resource the resource to write on.
 * @param  string the string to write.
 * @throws IOException when resource cannot be read.
 */
public static void writeResource(String resource, String string) throws IOException {
    try (final OutputStream out = getOutputStream(resource)) {
        IOUtils.write(string, out, Charset.defaultCharset());
    }
}

From source file:com.igormaznitsa.nbmindmap.nb.refactoring.MindMapLink.java

public void writeUTF8Text(final String text) throws IOException {
    final FileObject foj = getFile();
    final FileLock flock = lock(foj);
    try {//from w w  w.  j av a  2  s. co  m
        final OutputStream out = foj.getOutputStream(flock);
        try {
            IOUtils.write(text, out, "UTF-8");
        } finally {
            IOUtils.closeQuietly(out);
        }
    } finally {
        flock.releaseLock();
    }

    final DataObject doj = DataObject.find(foj);
    if (doj != null && doj instanceof MMDDataObject) {
        LOGGER.info("Notify about change primary file");
        ((MMDDataObject) doj).firePrimaryFileChanged();
    }
}

From source file:com.athena.peacock.common.core.action.FileWriteAction.java

@Override
public String perform() {
    String result = fileName;//from  www .j a va  2  s  . c om

    try {
        String separator = File.separator;

        fileName = fileName.replaceAll("\\\\", separator);

        String path = fileName.substring(0, fileName.lastIndexOf(separator));
        String name = fileName.substring(fileName.lastIndexOf(separator) + 1);

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream fos = new FileOutputStream(new File(path, name));

        if (StringUtils.isNotEmpty(permission)) {
            Files.setPosixFilePermissions(Paths.get(fileName), PosixFilePermissions.fromString(permission));
        }

        IOUtils.write(contents, fos, "UTF-8");
        IOUtils.closeQuietly(fos);

        result += " saved.\n";
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException has occurred. : ", e);
        result += " does not saved.\n";
    } catch (IOException e) {
        logger.error("IOException has occurred. : ", e);
        result += " does not saved.\n";
    }

    return result;
}

From source file:com.rpeactual.json2xml.JSON2XML.java

public void xml2xsd(String xmlPath, String pathToSaveXSD) throws XmlException, IOException {
    Inst2XsdOptions inst2XsdOptions = new Inst2XsdOptions();
    inst2XsdOptions.setDesign(Inst2XsdOptions.DESIGN_RUSSIAN_DOLL);

    File[] xmlFiles = new File[1];
    xmlFiles[0] = new File(xmlPath);

    XmlObject[] xmlInstance = new XmlObject[1];
    xmlInstance[0] = XmlObject.Factory.parse(xmlFiles[0]);

    SchemaDocument[] schemaDocuments = Inst2Xsd.inst2xsd(xmlInstance, inst2XsdOptions);
    if (schemaDocuments != null && schemaDocuments.length > 0) {
        SchemaDocument schema = schemaDocuments[0];
        String schemaStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
        if (!schema.toString().startsWith(schemaStr)) {
            schemaStr += schema.toString();
        } else {/*from   w w w . ja v a 2  s.  co  m*/
            schemaStr = schema.toString();
        }

        IOUtils.write(schemaStr, new FileOutputStream(pathToSaveXSD), UTF_8);
    }
}

From source file:ch.cyberduck.core.s3.S3SingleUploadServiceTest.java

@Test
public void testUpload() throws Exception {
    final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("s3.key"),
                    System.getProperties().getProperty("s3.secret"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final S3SingleUploadService service = new S3SingleUploadService(session,
            new S3WriteFeature(session, new S3DisabledMultipartService()));
    final Path container = new Path("test-us-east-1-cyberduck",
            EnumSet.of(Path.Type.directory, Path.Type.volume));
    final String name = UUID.randomUUID().toString() + ".txt";
    final Path test = new Path(container, name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final String random = new RandomStringGenerator.Builder().build().generate(1000);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(random, out, Charset.defaultCharset());
    out.close();/* w w  w.  j a v  a 2s.  c om*/
    final TransferStatus status = new TransferStatus();
    status.setLength(random.getBytes().length);
    status.setMime("text/plain");
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
            new DisabledStreamListener(), status, new DisabledLoginCallback());
    assertTrue(new S3FindFeature(session).find(test));
    final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test);
    assertEquals(random.getBytes().length, attributes.getSize());
    final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session))
            .getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertEquals("text/plain", metadata.get("Content-Type"));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:com.gargoylesoftware.htmlunit.util.DebuggingWebConnectionTest.java

/**
 * Ensures that Content-Encoding headers are removed when JavaScript is uncompressed.
 * (was causing java.io.IOException: Not in GZIP format as of HtmlUnit-2.10).
 * @throws Exception if the test fails/*from w  w  w.  j  a v  a2 s  . c o  m*/
 */
@Test
public void gzip() throws Exception {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
    IOUtils.write("alert(1)", gzipOutputStream, "UTF-8");
    gzipOutputStream.close();

    final MockWebConnection mockConnection = new MockWebConnection();
    final List<NameValuePair> responseHeaders = Arrays.asList(new NameValuePair("Content-Encoding", "gzip"));
    mockConnection.setResponse(getDefaultUrl(), baos.toByteArray(), 200, "OK", "application/javascript",
            responseHeaders);

    final String dirName = "test-" + getClass().getSimpleName();
    try (final DebuggingWebConnection dwc = new DebuggingWebConnection(mockConnection, dirName)) {

        final WebRequest request = new WebRequest(getDefaultUrl());
        final WebResponse response = dwc.getResponse(request); // was throwing here
        assertNull(response.getResponseHeaderValue("Content-Encoding"));

        FileUtils.deleteDirectory(dwc.getReportFolder());
    }
}

From source file:com.github.xlstosql.SqlGenerator.java

private void readTables() {
    result = new StringBuilder();
    try {// w ww .j  a v  a  2 s.  c  om
        for (String fileName : files) {
            Workbook workbook = Workbook.getWorkbook(new File(fileName));
            List<String> sheetNames = new ArrayList<String>();
            for (Sheet sheet : workbook.getSheets()) {
                sheetNames.add(sheet.getName());
                headers = sheet.getRow(0);
                for (int indexRow = 1; indexRow < sheet.getRows(); indexRow += 1) {
                    sheetName = sheet.getName();
                    appendHeaders();
                    Cell[] datas = sheet.getRow(indexRow);
                    if (datas != null && datas.length > 0) {
                        result.append(translateValue(0, cellToString(datas[0])));
                    }
                    for (int indexCell = 1; indexCell < headers.length; indexCell += 1) {
                        if (isValidDictHeader(headers[indexCell].getContents())) {
                            result.append(", " + translateValue(indexCell, cellToString(datas[indexCell])));
                        }
                    }
                    if (isDict()) {
                        Calendar today = Calendar.getInstance();
                        Calendar from = (Calendar) today.clone();
                        Calendar to = (Calendar) today.clone();
                        from.add(Calendar.DATE, -1000);
                        to.add(Calendar.DATE, 1000);
                        result.append(", '" + sheetName.substring(5) + "', 1, " + toSqlFormat(from) + ", "
                                + toSqlFormat(to) + ", " + toSqlFormat(today));
                    }
                    result.append(")\n");
                }
            }
            workbook.close();
            IOUtils.write(result.toString(), new FileOutputStream(outSql), "cp1251");
            getLog().log(Level.INFO, "read " + fileName.replaceFirst(".*/(.*)", "$1") + " - " + sheetNames);
        }
    } catch (Exception ex) {
        getLog().log(Level.WARNING, ex.getMessage(), ex);
    }
}

From source file:ch.cyberduck.core.s3.S3ThresholdUploadServiceTest.java

@Test
public void testUploadSinglePartEuCentral() throws Exception {
    final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("s3.key"),
                    System.getProperties().getProperty("s3.secret"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final S3ThresholdUploadService service = new S3ThresholdUploadService(session, 5 * 1024L);
    final Path container = new Path("test-eu-central-1-cyberduck",
            EnumSet.of(Path.Type.directory, Path.Type.volume));
    final String name = UUID.randomUUID().toString();
    final Path test = new Path(container, name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final String random = new RandomStringGenerator.Builder().build().generate(1000);
    IOUtils.write(random, local.getOutputStream(false), Charset.defaultCharset());
    final TransferStatus status = new TransferStatus();
    status.setLength((long) random.getBytes().length);
    status.setMime("text/plain");
    status.setStorageClass(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY);
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
            new DisabledStreamListener(), status, new DisabledLoginCallback());
    assertEquals((long) random.getBytes().length, status.getOffset(), 0L);
    assertTrue(status.isComplete());//from w w  w.java  2 s.  c o m
    assertTrue(new S3FindFeature(session).find(test));
    final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test);
    assertEquals(random.getBytes().length, attributes.getSize());
    assertEquals(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, new S3StorageClassFeature(session).getClass(test));
    final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session))
            .getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertEquals("text/plain", metadata.get("Content-Type"));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:net.mindengine.galen.GalenMain.java

public void performConfig() throws IOException {
    File file = new File("config");

    if (!file.exists()) {
        file.createNewFile();/*w w  w  .  j  ava 2s .  c  o m*/
        FileOutputStream fos = new FileOutputStream(file);

        StringWriter writer = new StringWriter();
        IOUtils.copy(getClass().getResourceAsStream("/config-template.conf"), writer, "UTF-8");
        IOUtils.write(writer.toString(), fos, "UTF-8");
        fos.flush();
        fos.close();
        System.out.println("Created config file");
    } else {
        System.out.println("Config file already exists");
    }
}