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.enonic.cms.server.service.webdav.DavResourceImpl.java

/**
 * Spool resource./*from  w w w  .  j ava 2 s.  co  m*/
 */
private void spoolResource(OutputContext context) throws IOException {
    final long length = this.file.getSize();
    final long modTime = this.file.getLastModified().getMillis();

    context.setContentLength(length);
    context.setModificationTime(modTime);
    context.setContentType(MimeTypeResolver.getInstance().getMimeType(this.file.getName().getName()));
    context.setETag("\"" + length + "-" + modTime + "\"");

    final FileResourceData data = this.factory.getFileResourceService().getResourceData(this.file.getName());
    if ((data != null) && context.hasStream()) {
        IOUtils.write(data.getAsBytes(), context.getOutputStream());
    }
}

From source file:ch.cyberduck.core.b2.B2ReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path test = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    new B2TouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);//w  w  w  .  j  ava2  s .  c o m
    IOUtils.write(content, out);
    out.close();
    new B2SingleUploadService(new B2WriteFeature(session)).upload(test, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length), new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new B2ReadFeature(session).read(test, status.length(content.length - 100),
            new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.redhat.acceptance.AbstractStepsBase.java

public File writeFile(File file, String contents) throws IOException {
    log.debug("creating file [" + file.getPath() + "] with content ["
            + (contents.length() > 50 ? contents.substring(0, 50) + "..." : contents) + "]");
    file.getParentFile().mkdirs();/*from ww w  . j ava 2  s.  c om*/
    IOUtils.write(contents.getBytes(), new FileOutputStream(file));
    return file.getCanonicalFile();
}

From source file:com.openkm.util.impexp.RepositoryExporter.java

/**
 * Performs a recursive repository content export with metadata
 *///from  w  w w  .  ja v  a 2  s .  com
private static ImpExpStats exportDocumentsHelper(String token, String fldPath, File fs, boolean metadata,
        boolean history, Writer out, InfoDecorator deco)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, IOException,
        DatabaseException, ParseException, NoSuchGroupException, MessagingException {
    log.debug("exportDocumentsHelper({}, {}, {}, {}, {}, {}, {})",
            new Object[] { token, fldPath, fs, metadata, history, out, deco });
    ImpExpStats stats = new ImpExpStats();
    DocumentModule dm = ModuleManager.getDocumentModule();
    FolderModule fm = ModuleManager.getFolderModule();
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Gson gson = new Gson();
    String path = null;
    File fsPath = null;

    if (firstTime) {
        path = fs.getPath();
        fsPath = new File(path);
        firstTime = false;
    } else {
        String dirName = PathUtils.decodeEntities(PathUtils.getName(fldPath));

        // Repository path needs to be "corrected" under Windoze
        path = fs.getPath() + File.separator + dirName.replace(':', '_');
        fsPath = new File(path);
        fsPath.mkdirs();
        FileLogger.info(BASE_NAME, "Created folder ''{0}''", fsPath.getPath());

        if (out != null) {
            out.write(deco.print(fldPath, 0, null));
            out.flush();
        }
    }

    for (Iterator<Mail> it = mm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Mail mailChild = it.next();
        String mailName = PathUtils.decodeEntities(PathUtils.getName(mailChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + mailName.replace(':', '_');
        ImpExpStats mailStats = exportMail(token, mailChild.getPath(), path + ".eml", metadata, out, deco);

        // Stats
        stats.setSize(stats.getSize() + mailStats.getSize());
        stats.setMails(stats.getMails() + mailStats.getMails());
    }

    for (Iterator<Document> it = dm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Document docChild = it.next();
        String fileName = PathUtils.decodeEntities(PathUtils.getName(docChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + fileName.replace(':', '_');
        ImpExpStats docStats = exportDocument(token, docChild.getPath(), path, metadata, history, out, deco);

        // Stats
        stats.setSize(stats.getSize() + docStats.getSize());
        stats.setDocuments(stats.getDocuments() + docStats.getDocuments());
    }

    for (Iterator<Folder> it = fm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Folder fldChild = it.next();
        ImpExpStats tmp = exportDocumentsHelper(token, fldChild.getPath(), fsPath, metadata, history, out,
                deco);
        String dirName = PathUtils.decodeEntities(PathUtils.getName(fldChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + dirName.replace(':', '_');

        // Metadata
        if (metadata) {
            FolderMetadata fmd = ma.getMetadata(fldChild);
            String json = gson.toJson(fmd);
            FileOutputStream fos = new FileOutputStream(path + Config.EXPORT_METADATA_EXT);
            IOUtils.write(json, fos);
            fos.close();
        }

        // Stats
        stats.setSize(stats.getSize() + tmp.getSize());
        stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
        stats.setFolders(stats.getFolders() + tmp.getFolders() + 1);
        stats.setOk(stats.isOk() && tmp.isOk());
    }

    log.debug("exportDocumentsHelper: {}", stats);
    return stats;
}

From source file:com.litwan.yanel.impl.resources.svg.SvgEditResource.java

public void execute() throws UsecaseException {
    final String content = getEditorContent();
    final Resource resToEdit = getResToEdit();
    if (log.isDebugEnabled())
        log.debug("saving content: " + content);
    if (ResourceAttributeHelper.hasAttributeImplemented(resToEdit, "Modifiable", "2")) {
        try {// w  w w  . j  a va 2 s  .c  o  m
            OutputStream os = ((ModifiableV2) resToEdit).getOutputStream();
            IOUtils.write(content, os);
            addInfoMessage("Succesfully saved resource " + resToEdit.getPath() + ". ");
            if (isResToEditVersionableV2()) {
                VersionableV2 versionable = (VersionableV2) resToEdit;
                try {
                    versionable.checkin("Updated with svg-edit");
                    addInfoMessage("Succesfully checked in resource " + resToEdit.getPath() + ". ");
                } catch (Exception e) {
                    String msg = "Could not check in resource: " + resToEdit.getPath() + " " + e.getMessage()
                            + ". ";
                    log.error(msg, e);
                    addError(msg);
                    throw new UsecaseException(msg, e);
                }
            }
        } catch (Exception e) {
            log.error("Exception: " + e);
            throw new UsecaseException(e.getMessage(), e);
        }
    } else {
        addError("Could not save the document. ");
    }
    setParameter(PARAMETER_CONTINUE_PATH, PathUtil.backToRealm(getPath()) + getEditPath().substring(1)); // allow jelly template to show link to new event
}

From source file:Enrichissement.GraphViz.java

/**
 * Writes the graph's image in a file./*from w w w.ja v  a 2s .co  m*/
 * @param img   A byte array containing the image of the graph.
 * @param to    A File object to where we want to write.
 * @return Success: 1, Failure: -1
 */
public int writeGraphToFile(byte[] img, File to) {
    try {
        FileOutputStream stream = new FileOutputStream(to);
        IOUtils.write(img, stream);
    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    }
    //      try {
    //         FileOutputStream fos = new FileOutputStream(to);
    //         fos.write(img);
    //         fos.close();
    //      } catch (java.io.IOException ioe) { return -1; }
    return 1;
}

From source file:com.norconex.commons.lang.io.CachedOutputStream.java

@SuppressWarnings("resource")
private void cacheToFile() throws IOException {
    fileCache = File.createTempFile("CachedOutputStream-", "-temp", cacheDirectory);
    fileCache.deleteOnExit();/* w  ww .ja va2  s . c o m*/
    LOG.debug("Reached max cache size. Swapping to file: " + fileCache);
    RandomAccessFile f = new RandomAccessFile(fileCache, "rw");
    FileChannel channel = f.getChannel();
    fileOutputStream = Channels.newOutputStream(channel);

    IOUtils.write(memOutputStream.toByteArray(), fileOutputStream);
    memOutputStream = null;
}

From source file:com.thoughtworks.go.server.domain.JobInstanceLogTest.java

@Test
public void shouldFindIndexPageFromTestOutputGivenNunitTestOutput() throws Exception {

    final File testOutput = new File(rootFolder, TestArtifactPlan.TEST_OUTPUT_FOLDER);
    testOutput.mkdirs();/*from w w  w  .j  av  a2 s. co m*/
    IOUtils.write("Test", new FileOutputStream(new File(testOutput, "index.html")));
    HashMap map = new HashMap();
    map.put("artifactfolder", rootFolder);
    jobInstanceLog = new JobInstanceLog(null, map);
    assertThat(jobInstanceLog.getTestIndexPage().getName(), is("index.html"));
    FileUtil.deleteFolder(rootFolder);
}

From source file:ch.cyberduck.core.udt.UDTProxyConfiguratorTest.java

@Test(expected = QuotaException.class)
public void testUploadQuotaFailure() throws Exception {
    final Host host = new Host(new S3Protocol(), "s3.amazonaws.com", new Credentials(
            System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")));
    final UDTProxyConfigurator proxy = new UDTProxyConfigurator(
            new S3LocationFeature.S3Region("ap-northeast-1"), new LocalhostProxyProvider() {
                @Override/*from   w  ww.  ja va 2  s.  c  o m*/
                public List<Header> headers() {
                    final List<Header> headers = new ArrayList<Header>();
                    headers.add(new Header("X-Qloudsonic-Voucher", "-u9zTIKCXHTWPO9WA4fBsIaQ5SjEH5von"));
                    return headers;
                }
            }, new DefaultX509TrustManager() {
                @Override
                public void checkServerTrusted(final X509Certificate[] certs, final String cipher)
                        throws CertificateException {

                }
            }, new DefaultX509KeyManager());
    final S3Session tunneled = new S3Session(host);
    proxy.configure(tunneled);
    assertNotNull(tunneled.open(new DisabledHostKeyCallback()));
    assertTrue(tunneled.isConnected());

    final TransferStatus status = new TransferStatus();
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = "test".getBytes("UTF-8");
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();
    status.setLength(content.length);
    final Path test = new Path(new Path("container", EnumSet.of(Path.Type.volume)),
            UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final Upload upload = new S3SingleUploadService(tunneled,
            new S3WriteFeature(tunneled, new S3DisabledMultipartService()));
    try {
        upload.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
                new DisabledStreamListener(), status, new DisabledConnectionCallback());
    } catch (QuotaException e) {
        assertEquals(
                "Voucher -u9zTIKCXHTWPO9WA4fBsIaQ5SjEH5von not found. Request Error. Please contact your web hosting service provider for assistance.",
                e.getDetail());
        throw e;
    }
}

From source file:com.scaleunlimited.cascading.FlowMonitor.java

@SuppressWarnings("rawtypes")
public boolean run(Enum... counters) throws Throwable {
    if (_htmlDir == null) {
        _htmlDir = getDefaultLogDir(_flow.getConfig());
    }//from   w  w w  . j a  v  a2s  . c  om

    _flowException = null;
    FlowListener catchExceptions = new FlowListener() {

        @Override
        public void onCompleted(Flow flow) {
        }

        @Override
        public void onStarting(Flow flow) {
        }

        @Override
        public void onStopping(Flow flow) {
        }

        @Override
        public boolean onThrowable(Flow flow, Throwable t) {
            _flowException = t;
            return true;
        }
    };

    _flow.addListener(catchExceptions);
    _flow.start();

    FlowStats stats;
    Set<String> loggingStatus = new HashSet<String>();
    loggingStatus.add(Status.RUNNING.name());
    loggingStatus.add(Status.SUCCESSFUL.name());
    loggingStatus.add(Status.STOPPED.name());
    loggingStatus.add(Status.FAILED.name());

    do {
        stats = _flow.getFlowStats();
        List<FlowStepStats> stepStats = stats.getFlowStepStats();
        for (FlowStepStats stepStat : stepStats) {
            String stepId = stepStat.getID();
            StepEntry stepEntry = findStepById(stepId);
            Status oldStatus = stepEntry.getStatus();
            Status newStatus = stepStat.getStatus();
            if (oldStatus != newStatus) {
                stepEntry.setStartTime(stepStat.getStartTime());
                stepEntry.setStatus(stepStat.getStatus());
            }
            if (loggingStatus.contains(newStatus.name())) {
                if (stepStat.isFinished()) {
                    stepEntry.setDuration(stepStat.getDuration());
                } else if (stepStat.isRunning()) {
                    stepEntry.setDuration(System.currentTimeMillis() - stepEntry.getStartTime());
                } else {
                    // Duration isn't known
                    stepEntry.setDuration(0);
                }

                stepEntry.addTimeEntry(makeTimeEntry(stepEntry, stepStat, counters), _timeEntriesPerStep);
            }
        }

        // Now we can build our resulting table
        StringBuilder topTemplate = new StringBuilder(_htmlTopTemplate);
        replace(topTemplate, "%flowname%", StringEscapeUtils.escapeHtml(_flow.getName()));

        for (StepEntry stepEntry : _stepEntries) {
            StringBuilder stepTemplate = new StringBuilder(_htmlStepTemplate);
            replaceHtml(stepTemplate, "%stepname%", stepEntry.getName());
            replaceHtml(stepTemplate, "%stepstatus%", "" + stepEntry.getStatus());
            replaceHtml(stepTemplate, "%stepstart%", new Date(stepEntry.getStartTime()).toString());
            replaceHtml(stepTemplate, "%stepduration%", "" + (stepEntry.getDuration() / 1000));

            replace(stepTemplate, "%counternames%", getTableHeader(stepEntry.getStep(), counters));

            // Now we need to build rows of data, for steps that are running or have finished.
            if (stepEntry.getStatus() != Status.PENDING) {
                for (TimeEntry row : stepEntry.getTimerEntries()) {
                    StringBuilder rowTemplate = new StringBuilder(_htmlRowTemplate);
                    replaceHtml(rowTemplate, "%timeoffset%", "" + (row.getTimeDelta() / 1000));
                    replace(rowTemplate, "%countervalues%", getCounterValues(row.getCounterValues()));
                    insert(stepTemplate, "%steprows%", rowTemplate.toString());
                }
            }

            // Get rid of position marker we used during inserts.
            replace(stepTemplate, "%steprows%", "");

            insert(topTemplate, "%steps%", stepTemplate.toString());
        }

        // Get rid of position marker we used during inserts.
        replace(topTemplate, "%steps%", "");

        // We've got the template ready to go, create the file.
        File htmlFile = new File(_htmlDir, FILENAME);
        FileWriterWithEncoding fw = new FileWriterWithEncoding(htmlFile, "UTF-8");
        IOUtils.write(topTemplate.toString(), fw);
        fw.close();

        Thread.sleep(_updateInterval);

    } while (!stats.isFinished());

    // Create a copy of the file as an archive, once we're done.
    File htmlFile = new File(_htmlDir, FILENAME);
    File archiveFile = new File(_htmlDir, String.format("%s-%s", _flow.getName(), FILENAME));
    archiveFile.delete();

    if (!htmlFile.exists() || archiveFile.exists()) {
        LOGGER.warn("Unable to create archive of file " + htmlFile.getAbsolutePath());
    } else {
        try {
            String content = IOUtils.toString(new FileReader(htmlFile));
            FileWriterWithEncoding fw = new FileWriterWithEncoding(archiveFile, "UTF-8");
            IOUtils.write(content, fw);
            fw.close();
        } catch (Exception e) {
            LOGGER.warn("Unable to create archive of file " + htmlFile.getAbsolutePath(), e);
        }
    }

    if (stats.isFailed() && (_flowException != null)) {
        throw _flowException;
    }

    return stats.isSuccessful();
}