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.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {//ww  w  .  jav  a  2s.  c  o  m
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        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("_exception", "");
        j.put("_exceptionMessage", "");
    } 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("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } 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("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } 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("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } 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("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:com.jayway.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void file_uploading_works() throws IOException {
    File file = folder.newFile("something");
    IOUtils.write("Something21", new FileOutputStream(file));

    given().multiPart(file).when().post("/fileUpload").then().body("size", greaterThan(10)).body("name",
            equalTo("file"));
}

From source file:com.formkiq.core.controller.admin.AdminController.java

/**
 * Download Form.//  w w  w  .j  a  va2  s.  co  m
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @param folder {@link String}
 * @param uuid {@link String}
 * @throws IOException IOException
 */
@Transactional
@RequestMapping("/download")
public void download(final HttpServletRequest request, final HttpServletResponse response,
        @RequestParam(value = "folder", required = true) final String folder,
        @RequestParam(value = "uuid", required = true) final String uuid) throws IOException {

    byte[] data = this.folderservice.findFormData(folder, uuid).getLeft();

    response.setContentType("application/zip");
    response.setHeader("Content-disposition", "attachment; filename=" + uuid + ".zip");
    response.setContentLengthLong(data.length);
    IOUtils.write(data, response.getOutputStream());
}

From source file:com.github.brandtg.pantopod.crawler.FileBasedCrawlingEventHandler.java

@Override
protected void markError(URI url, int errorCode) throws IOException {
    File outputRoot = new File(outputDir, url.getHost() + File.separator + url.getPath());
    FileUtils.forceMkdir(outputRoot);//from   ww  w .j  ava2 s  .  c o  m
    File errFile = new File(outputRoot, ERR_FILE);
    if (!errFile.exists()) {
        try (OutputStream os = new FileOutputStream(errFile)) {
            IOUtils.write(String.valueOf(errorCode).getBytes(), os);
        }
    }
}

From source file:eu.ggnet.dwoss.util.FileJacket.java

/**
 * Creates a temporary File with the content of this DataFile, deletes on exit.
 * <p/>// w w  w  . ja  va  2 s. c  om
 * @return the file pointing to the temporary one.
 */
public File toTemporaryFile() {
    File f;
    try {
        f = File.createTempFile(head + "_", suffix);
        f.deleteOnExit();
    } catch (IOException ex) {
        throw new RuntimeException("Temporary File creation not done.", ex);
    }
    try (FileOutputStream os = new FileOutputStream(f)) {
        IOUtils.write(content, os);
    } catch (IOException ex) {
        throw new RuntimeException("Temporary File creation not done.", ex);
    }
    return f;
}

From source file:com.apress.prospringintegration.customadapters.inbound.eventdriven.DirectoryMonitorInboundFileEndpointTests.java

@Test
public void testReceivingFiles() throws Throwable {
    final Set<String> files = new ConcurrentSkipListSet<String>();
    integrationTestUtils.createConsumer(this.messageChannel, new MessageHandler() {
        @Override//from  ww w. j  a  va  2  s  . c  o  m
        public void handleMessage(Message<?> message) throws MessagingException {
            File file = (File) message.getPayload();
            String filePath = file.getPath();
            files.add(filePath);
        }
    });

    int cnt = 10;
    for (int i = 0; i < cnt; i++) {
        File out = new File(directoryToMonitor, i + ".txt");
        Writer w = new BufferedWriter(new FileWriter(out));
        IOUtils.write("test" + i, w);
        IOUtils.closeQuietly(w);
    }

    Thread.sleep(TimeUnit.SECONDS.toMillis(20));
    Assert.assertEquals(cnt, files.size());
}

From source file:com.google.codelab.networkmanager.CodelabUtil.java

/**
 * Overwrite Tasks in file with those given here.
 *//*from   w w  w. j  a  v  a2 s  . c o m*/
private static void saveTaskItemsToFile(Context context, List<TaskItem> taskItems) {
    String taskStr = taskItemsToString(taskItems);
    File file = new File(context.getFilesDir(), FILE_NAME);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.write(taskStr, fileOutputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.linkedin.pinot.core.data.readers.ThriftRecordReaderTest.java

@BeforeClass
public void setUp() throws IOException, TException {
    ThriftSampleData t1 = new ThriftSampleData();
    t1.setActive(true);//from  ww  w.  ja  va 2  s .c  o m
    t1.setCreated_at(1515541280L);
    t1.setId(1);
    t1.setName("name1");
    List<Short> t1Groups = new ArrayList<>(2);
    t1Groups.add((short) 1);
    t1Groups.add((short) 4);
    t1.setGroups(t1Groups);
    Map<String, Long> mapValues = new HashMap<>();
    mapValues.put("name1", 1L);
    t1.setMap_values(mapValues);
    Set<String> namesSet = new HashSet<>();
    namesSet.add("name1");
    t1.setSet_values(namesSet);

    ThriftSampleData t2 = new ThriftSampleData();
    t2.setActive(false);
    t2.setCreated_at(1515541290L);
    t2.setId(2);
    t2.setName("name2");
    List<Short> t2Groups = new ArrayList<>(2);
    t2Groups.add((short) 2);
    t2Groups.add((short) 3);
    t2.setGroups(t2Groups);
    List<ThriftSampleData> lists = new ArrayList<>(2);
    lists.add(t1);
    lists.add(t2);
    TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory());
    _tempFile = getSampleDataPath();
    FileWriter writer = new FileWriter(_tempFile);
    for (ThriftSampleData d : lists) {
        IOUtils.write(binarySerializer.serialize(d), writer);
    }
    writer.close();
}

From source file:com.cedarsoft.serialization.serializers.jackson.registry.FileBasedSerializedObjectsAccessTest.java

License:asdf

@Test
public void testExists() throws IOException {
    assertEquals(0, access.getIds().size());
    {// w w  w . j  a v  a2 s  .c  o  m
        OutputStream out = access.openOut("id");
        IOUtils.write("asdf".getBytes(), out);
        out.close();
    }

    try {
        access.openOut("id");
        fail("Where is the Exception");
    } catch (StillContainedException e) {
    }
}

From source file:com.moz.fiji.schema.tools.TestCreateTableTool.java

/**
 * Writes a table layout as a JSON descriptor in a temporary file.
 *
 * @param layoutDesc Table layout descriptor to write.
 * @return the temporary File where the layout has been written.
 * @throws Exception on error.//from   w ww. j  a v a2  s  .c o  m
 */
private File getTempLayoutFile(TableLayoutDesc layoutDesc) throws Exception {
    final File layoutFile = File.createTempFile(layoutDesc.getName(), ".json", getLocalTempDir());
    final OutputStream fos = new FileOutputStream(layoutFile);
    try {
        IOUtils.write(ToJson.toJsonString(layoutDesc), fos);
    } finally {
        fos.close();
    }
    return layoutFile;
}