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:de.smartics.maven.alias.MavenAliasMojo.java

private void writeScript(final File scriptFolder, final String id, final String script)
        throws MojoExecutionException {
    final File scriptFile = new File(scriptFolder, id);
    try {/*from   w ww.j ava 2  s. c om*/
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(scriptFile));
        try {
            IOUtils.write(script, out);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (final Exception e) {
        throw new MojoExecutionException("Cannot write script to '" + scriptFile.getAbsolutePath() + "'.", e);
    }
}

From source file:ch.cyberduck.core.Profile.java

/**
 * Write temporary file with data// w  ww  .  j  av  a2  s . com
 *
 * @param icon Base64 encoded image information
 * @return Path to file
 */
private Local write(final String icon) {
    if (StringUtils.isBlank(icon)) {
        return null;
    }
    final byte[] favicon = Base64.decodeBase64(icon);
    final Local file = TemporaryFileServiceFactory.get()
            .create(String.format("%s.ico", new AlphanumericRandomStringService().random()));
    try {
        new DefaultLocalTouchFeature().touch(file);
        final OutputStream out = file.getOutputStream(false);
        try {
            IOUtils.write(favicon, out);
        } finally {
            IOUtils.closeQuietly(out);
        }
        return file;
    } catch (IOException | AccessDeniedException e) {
        log.error("Error writing temporary file", e);
    }
    return null;
}

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

@Test
public void testReadInterrupt() 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"))));
    final LoginConnectionService service = new LoginConnectionService(new DisabledLoginCallback(),
            new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener());
    service.connect(session, PathCache.empty(), new DisabledCancelCallback());
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final byte[] content = RandomUtils.nextBytes(923);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);//ww w . j  a va 2 s  . c o  m
    status.setChecksum(new SHA1ChecksumCompute().compute(new ByteArrayInputStream(content), status));
    final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file, status,
            new DisabledConnectionCallback());
    IOUtils.write(content, out);
    out.close();
    {
        // Unknown length in status
        // Read a single byte
        final InputStream in = new B2ReadFeature(session).read(file, new TransferStatus(),
                new DisabledConnectionCallback());
        assertNotNull(in.read());
        in.close();
    }
    {
        final InputStream in = new B2ReadFeature(session).read(file, new TransferStatus(),
                new DisabledConnectionCallback());
        assertNotNull(in);
        in.close();
    }
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.intuit.tank.service.impl.v1.project.ProjectServiceV1.java

/**
 * @{inheritDoc//from   w  ww . j a v  a 2  s.com
 */
@Override
public StreamingOutput getTestScriptForProject(Integer projectId) {
    ProjectDao dao = new ProjectDao();
    Project p = dao.findById(projectId);
    if (p == null) {
        throw new RuntimeException("Cannot find Project with id of " + projectId);
    }
    Workload workload = p.getWorkloads().get(0);
    workload = new WorkloadDao().loadScriptsForWorkload(workload);
    final String scriptString = WorkloadScriptUtil.getScriptForWorkload(workload,
            workload.getJobConfiguration());
    return new StreamingOutput() {
        public void write(OutputStream outputStream) {
            // Get the object of DataInputStream
            try {
                IOUtils.write(scriptString, outputStream);
            } catch (IOException e) {
                LOG.error("Error streaming file: " + e.toString(), e);
                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
            } finally {
            }
        }
    };
}

From source file:ch.cyberduck.core.irods.IRODSReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(
            new HashSet<>(Collections.singleton(new IRODSProtocol())));
    final Profile profile = new ProfilePlistReader(factory)
            .read(new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
    final Host host = new Host(profile, profile.getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("irods.key"),
                    System.getProperties().getProperty("irods.secret")));
    final IRODSSession session = new IRODSSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    new IRODSTouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(2048);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);/*from w  ww  .j a  v a2  s  .c om*/
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<Integer>(new IRODSWriteFeature(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 IRODSReadFeature(session).read(test, status, 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 IRODSDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.smartitengineering.event.hub.common.ChannelJsonProvider.java

public void writeTo(Channel t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    if (isWriteable(type, genericType, annotations, mediaType)) {
        IOUtils.write(getJsonString(t), entityStream);
    }/*from w  w  w . ja  va 2  s . com*/
}

From source file:ch.cyberduck.core.dav.DAVReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final DAVSession session = new DAVSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    session.getFeature(Touch.class).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);// w  w  w . j a va2  s.  c  o  m
    IOUtils.write(content, out);
    out.close();
    new DAVUploadFeature(new DAVWriteFeature(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 DAVReadFeature(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 DAVDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:net.sf.jsog.spring.StringJsogHttpMessageConverter.java

@Override
public void write(JSOG jsog, MediaType type, HttpOutputMessage output)
        throws IOException, HttpMessageNotWritableException {

    // If the outputContentType doesn't specify a charset, we need to set it
    Charset encoding = outputContentType.getCharSet();
    if (encoding != null) {
        output.getHeaders().setContentType(outputContentType);
    } else {// w  ww  .j av a  2s. c o  m
        encoding = this.encoding;

        output.getHeaders().setContentType(
                new MediaType(outputContentType.getType(), outputContentType.getSubtype(), encoding));
    }

    // Transform the JSOG to a byte array encoded in the proper encoding
    byte[] text = jsog.toString().getBytes(encoding);

    // Set the content length
    output.getHeaders().setContentLength(text.length);
    IOUtils.write(text, output.getBody());
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private void outputSignedOfficeOpenXMLDocument(byte[] signatureData)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    LOG.debug("output signed Office OpenXML document");
    OutputStream signedOOXMLOutputStream = getSignedOfficeOpenXMLDocumentOutputStream();
    if (null == signedOOXMLOutputStream) {
        throw new NullPointerException("signedOOXMLOutputStream is null");
    }/* w  w  w  .  j  a v  a2  s  . co  m*/

    String signatureZipEntryName = "_xmlsignatures/sig-" + UUID.randomUUID().toString() + ".xml";
    LOG.debug("signature ZIP entry name: " + signatureZipEntryName);
    /*
     * Copy the original OOXML content to the signed OOXML package. During
     * copying some files need to changed.
     */
    ZipOutputStream zipOutputStream = copyOOXMLContent(signatureZipEntryName, signedOOXMLOutputStream);

    /*
     * Add the OOXML XML signature file to the OOXML package.
     */
    ZipEntry zipEntry = new ZipEntry(signatureZipEntryName);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:edu.harvard.i2b2.fhir.FhirUtil.java

public static String getValidatorErrorMessageForProfile(String input, String profile) {
    String msg = "";
    logger.trace("running validator for input:" + input);
    try {/*  ww  w  .  j  a va 2  s  .c  o  m*/
        if (v == null)
            init();

        File temp = File.createTempFile("tempFileForValidator", ".tmp");
        FileOutputStream outTemp = new FileOutputStream(temp);
        IOUtils.write(input, outTemp);
        outTemp.close();
        logger.trace("tmp file:" + new Scanner(temp).useDelimiter("\\Z").next());// temp.getAbsolutePath());

        v.setSource(temp.getPath());
        v.setProfile(profile);
        logger.trace("source" + v.getSource() + " \n profile:" + profile);
        v.process();

        temp.delete();
        return v.getOutcome().toString();

    } catch (Exception e) {
        msg = e.getMessage();
        logger.error(e.getMessage(), e);
    }
    return msg;

}