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:net.grinder.AgentUpdateHandler.java

/**
 * Update agent based on the current message.
 *
 * @param message message to be sent//w w w.  j  a v a 2 s . c  o m
 */
public void update(AgentUpdateGrinderMessage message) throws CommunicationException {
    if (message.getOffset() != offset) {
        throw new CommunicationException("Expected " + offset + " offset," + " but " + message.getOffset()
                + " was sent. " + ToStringBuilder.reflectionToString(message));
    }
    try {
        IOUtils.write(message.getBinary(), agentOutputStream);
        offset = message.getNext();
    } catch (IOException e) {
        throw new CommunicationException("Error while writing binary", e);
    }
    if (message.getNext() == 0) {
        IOUtils.closeQuietly(agentOutputStream);
        decompressDownloadPackage();
        // Then just exist to run the agent update process.
        System.exit(0);
    }
}

From source file:com.openkm.util.ImageUtils.java

/**
 * Rotate an image.//from w ww . j a va 2s  .  co  m
 * 
 * @param img Image to rotate.
 * @param angle Rotation angle.
 * @return the image rotated.
 */
public static byte[] rotate(byte[] img, double angle) throws RuntimeException {
    log.debug("rotate({}, {})", new Object[] { img.length, angle });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileOutputStream fos = null;
    FileInputStream fis = null;
    byte[] ret = new byte[] {};
    File tmpFileIn = null;

    try {
        // Save to disk
        tmpFileIn = FileUtils.createTempFileFromMime(MimeTypeConfig.MIME_PNG);
        fos = new FileOutputStream(tmpFileIn);
        IOUtils.write(img, fos);
        IOUtils.closeQuietly(fos);

        // Rotate
        rotate(tmpFileIn, tmpFileIn, angle);

        // Read from disk
        fis = new FileInputStream(tmpFileIn);
        IOUtils.copy(fis, baos);
        IOUtils.closeQuietly(fis);
        ret = baos.toByteArray();
    } catch (DatabaseException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(tmpFileIn);
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(fis);
    }

    log.debug("crop: {}", ret.length);
    return ret;
}

From source file:dk.itst.oiosaml.sp.IntegrationTests.java

@Before
public final void setUpServer() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    tmpdir.mkdir();//from   w  w w  . j av  a  2s . com
    FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP"));
    FileUtils.forceMkdir(new File(tmpdir, "metadata/SP"));

    credential = TestHelper.getCredential();
    EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential);
    FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos);
    fos.close();

    EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil
            .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml"));
    fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos);
    fos.close();

    spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS);
    idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor);

    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml"));
    IOUtils.write(
            "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>",
            fos);
    fos.close();

    Properties props = new Properties();
    props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore");
    props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password");
    props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml");
    props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(),
            new Certificate[] { TestHelper.getCertificate(credential) });
    OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore"));
    ks.store(bos, "password".toCharArray());
    bos.close();

    props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2");
    props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true");
    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties"));
    props.store(fos, "Generated");
    fos.close();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    handler = new RedirectRefreshHandler();
    client.setRefreshHandler(handler);
}

From source file:de.fau.cs.osr.hddiff.perfsuite.util.SerializationUtils.java

public File storeWomCompactTemp(PageRevDiffNode prdn, Revision rev, DiffNode node) throws Exception {
    File file = File.createTempFile(makeCompactPrefix(prdn, rev), ".xml", tempDir);
    file.deleteOnExit();//from   w  w w . java 2s . co m
    try (FileOutputStream output = new FileOutputStream(file)) {
        byte[] bytes = serializer.serialize(getOwnerDocument((Wom3Node) node.getNativeNode()),
                WomSerializer.SerializationFormat.XML, true, false);
        IOUtils.write(bytes, output);
        return file;
    }
}

From source file:com.gloriouseggroll.LastFMAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;/*from   w  ww. ja  v  a  2s .c o  m*/
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "("
                + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:com.linkedin.r2.filter.compression.stream.TestStreamingCompression.java

@Test
public void testGzipCompressor()
        throws IOException, InterruptedException, CompressionException, ExecutionException {
    StreamingCompressor compressor = new GzipCompressor(_executor);
    final byte[] origin = new byte[BUF_SIZE];
    Arrays.fill(origin, (byte) 'b');

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    IOUtils.write(origin, gzip);
    gzip.close();/*from w  w  w  .  j a  v  a2s  .  co  m*/
    byte[] compressed = out.toByteArray();

    testCompress(compressor, origin, compressed);
    testDecompress(compressor, origin, compressed);
    testCompressThenDecompress(compressor, origin);
}

From source file:com.github.pemapmodder.pocketminegui.utils.Utils.java

private static File installWindowsPHP(File home, InstallProgressReporter progress) {
    progress.report(0.0);// w w w .ja  va 2s . c  om
    try {
        String link = System.getProperty("os.arch").contains("64")
                ? "https://bintray.com/artifact/download/pocketmine/PocketMine/PHP_7.0.3_x64_Windows.tar.gz"
                : "https://bintray.com/artifact/download/pocketmine/PocketMine/PHP_7.0.3_x86_Windows.tar.gz";
        URL url = new URL(link);
        InputStream gz = url.openStream();
        GzipCompressorInputStream tar = new GzipCompressorInputStream(gz);
        TarArchiveInputStream is = new TarArchiveInputStream(tar);
        TarArchiveEntry entry;
        while ((entry = is.getNextTarEntry()) != null) {
            if (!entry.isDirectory()) {
                String name = entry.getName();
                byte[] buffer = new byte[(int) entry.getSize()];
                IOUtils.read(is, buffer);
                File real = new File(home, name);
                real.getParentFile().mkdirs();
                IOUtils.write(buffer, new FileOutputStream(real));
            }
        }
        File output = new File(home, "bin/php/php.exe");
        progress.completed(output);
        return output;
    } catch (IOException e) {
        e.printStackTrace();
        progress.errored();
        return null;
    }
}

From source file:com.github.camellabs.iot.gateway.GpsCloudletSyncTest.java

@Test
public void shouldSendGpsCoordinatesToTheGeofencingCloudlet() throws InterruptedException, IOException {
    // Given/*from www.  j  a  v  a  2  s.  c  o m*/
    URL countOperationUri = new URL(
            "http://localhost:" + geofencingApiPort + "/api/document/count/GpsCoordinates");
    await().atMost(5, MINUTES).until(() -> {
        try {
            countOperationUri.openStream();
            return true;
        } catch (Exception ex) {
            LOG.debug("Can't connect to the geofencing cloudlet:", ex);
            return false;
        }
    });
    String gpsCoordinates = "{\"timestamp\": 123456789, \"lat\": 10.0, \"lng\": 20.0}";
    IOUtils.write(gpsCoordinates, new FileOutputStream(new File(gpsCoordinatesStore, "foo")));
    await().atMost(5, MINUTES).until(() -> {
        try {
            String countString = IOUtils.toString(countOperationUri);
            return Integer.parseInt(countString) == 1;
        } catch (Exception ex) {
            LOG.debug("Can't connect to the geofencing cloudlet:", ex);
            return false;
        }
    });

    // Then
    assertEquals(1, mongoClient.getDB(dbName).getCollection("GpsCoordinates").count());
    DBObject coordinates = mongoClient.getDB(dbName).getCollection("GpsCoordinates").findOne();
    assertEquals(10d, (Double) coordinates.get("latitude"), 0.0);
    assertEquals(20d, (Double) coordinates.get("longitude"), 0.0);
}

From source file:ch.cyberduck.core.onedrive.OneDriveReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final Path drive = new OneDriveHomeFinderFeature(session).find();
    final Path test = new Path(drive, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    new OneDriveTouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"),
            new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);//from   ww w.  j  a  va 2  s  .  c o m
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<Void>(new OneDriveWriteFeature(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 OneDriveReadFeature read = new OneDriveReadFeature(session);
    assertTrue(read.offset(test));
    final InputStream in = read.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 OneDriveDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:fi.tut.fast.MulticastProducer.java

public void process(Exchange exchange) throws Exception {

    InputStream is = exchange.getIn().getBody(InputStream.class);

    byte[] buf = IOUtils.toByteArray(is);
    DatagramPacket out = new DatagramPacket(buf, buf.length, endpoint.getMulticastGroup(),
            endpoint.getMulticastAddress().getPort());

    try {// w  ww. java  2  s  .c  o  m
        s.send(out);
        LOG.debug("Packet Sent...");
        StringWriter writer = new StringWriter();
        IOUtils.write(buf, writer);
        LOG.debug(writer.toString());
    } catch (SocketException ex) {
        LOG.error("Socket Closed before DatagramPacket could be sent.", ex);
    } catch (IOException ex) {
        LOG.error("Socket Closed before DatagramPacket could be sent.", ex);
    }

}