Example usage for org.apache.commons.io IOUtils copy

List of usage examples for org.apache.commons.io IOUtils copy

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils copy.

Prototype

public static void copy(Reader input, OutputStream output) throws IOException 

Source Link

Document

Copy chars from a Reader to bytes on an OutputStream using the default character encoding of the platform, and calling flush.

Usage

From source file:com.googlesource.gerrit.plugins.github.velocity.VelocityStaticServlet.java

private static byte[] readResource(final Resource p) throws IOException {
    final InputStream in = p.getResourceLoader().getResourceStream(p.getName());
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    try {/*from w  w  w  .ja v a  2 s  .c o m*/
        IOUtils.copy(in, byteOut);
    } finally {
        in.close();
        byteOut.close();
    }

    return byteOut.toByteArray();
}

From source file:edu.cornell.library.scholars.webapp.controller.api.distribute.file.FileDistributor.java

@Override
public void writeOutput(OutputStream output) throws DataDistributorException {
    Path home = ApplicationUtils.instance().getHomeDirectory().getPath();
    Path datafile = home.resolve(datapath);
    log.debug("data file is at: " + datapath);
    try (InputStream input = Files.newInputStream(datafile)) {
        IOUtils.copy(input, output);
    } catch (IOException e) {
        throw new ActionFailedException(e);
    }//from   www  . j  a va2s.co  m
}

From source file:de.uzk.hki.da.at.ATUseCaseIngestDeltaContract.java

@Test
public void test() throws IOException, InterruptedException, RepositoryException {

    Object o = ath.ingest(ORIG_NAME + "1", DEFAULT_CONTAINER_EXTENSION, ORIG_NAME);

    InputStream is = repositoryFacade.retrieveFile(o.getIdentifier(),
            preservationSystem.getOpenCollectionName(), JPG_STREAM_ID);
    assertNotNull(is);// w  w w.j  ava  2 s.  com
    IOUtils.copy(is, new FileOutputStream(OUTPUT_JPG_1));

    Thread.sleep(_1_MINUTE); // to prevent the repnames to match the ones of the previous package

    o = ath.ingest(ORIG_NAME + "2", DEFAULT_CONTAINER_EXTENSION, ORIG_NAME);

    InputStream is2 = repositoryFacade.retrieveFile(o.getIdentifier(),
            preservationSystem.getOpenCollectionName(), JPG_STREAM_ID);
    assertNotNull(is2);
    IOUtils.copy(is2, new FileOutputStream(OUTPUT_JPG_2));

    Thread.sleep(_1_MINUTE); // to prevent the repnames to match the ones of the previous package

    o = ath.ingest(ORIG_NAME + "3", DEFAULT_CONTAINER_EXTENSION, ORIG_NAME);

    InputStream is3 = repositoryFacade.retrieveFile(o.getIdentifier(),
            preservationSystem.getOpenCollectionName(), JPG_STREAM_ID);

    assertNull(is3);
}

From source file:com.cloudbees.diff.UnifiedDiff.java

private static void copyStreamsCloseAll(Writer writer, Reader reader) throws IOException {
    IOUtils.copy(reader, writer);
    writer.close();/*from   www . j a  v a2 s.  com*/
    reader.close();
}

From source file:com.webpagebytes.cms.controllers.ExportImportController.java

public void importContent(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    File tempFile = null;/*from   w  w  w .j  av a 2s  .c o m*/
    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (!item.isFormField() && item.getFieldName().equals("file")) {
                InputStream is = item.openStream();
                tempFile = File.createTempFile("wpbImport", null);
                FileOutputStream fos = new FileOutputStream(tempFile);
                IOUtils.copy(is, fos);
                fos.close();

                adminStorage.stopNotifications();
                deleteAll();

                // because the zip file entries cannot be predicted we needto import in two step1
                // step 1 when we create the resource records
                // step 2 when we import the files, pages, modules and articles content
                InputStream is1 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep1(is1);
                is1.close();

                InputStream is2 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep2(is2);
                is2.close();

                org.json.JSONObject returnJson = new org.json.JSONObject();
                returnJson.put(DATA, "");
                httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);
            }
        }
    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANNOT_IMPORT_PROJECT);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    } finally {
        if (tempFile != null) {
            if (!tempFile.delete()) {
                tempFile.deleteOnExit();
            }
        }

        adminStorage.startNotifications();
    }
}

From source file:com.arykow.autotools.generator.App.java

private void generate() throws Exception {
    File directory = new File(projectDirectory);
    if (!directory.isDirectory()) {
        throw new RuntimeException();
    }// w  w w.j a  v a  2s .c om
    File output = new File(directory, projectName);
    if (output.exists()) {
        if (projectForced) {
            if (!output.isDirectory()) {
                throw new RuntimeException();
            }
        } else {
            throw new RuntimeException();
        }
    } else if (!output.mkdir()) {
        throw new RuntimeException();
    }

    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    if (src != null) {
        URL jar = src.getLocation();
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        while (true) {
            ZipEntry e = zip.getNextEntry();
            if (e == null)
                break;
            if (!e.isDirectory() && e.getName().startsWith(String.format("%s", templateName))) {
                // generate(output, e);

                StringWriter writer = new StringWriter();
                IOUtils.copy(zip, writer);
                String content = writer.toString();

                Map<String, String> expressions = new HashMap<String, String>();
                expressions.put("author", "Karim DRIDI");
                expressions.put("name_undescore", projectName);
                expressions.put("license", "<Place your desired license here.>");
                expressions.put("name", projectName);
                expressions.put("version", "1.0");
                expressions.put("copyright", "Your copyright notice");
                expressions.put("description", "Hello World in C++,");

                for (Map.Entry<String, String> entry : expressions.entrySet()) {
                    content = content.replaceAll(String.format("<project\\.%s>", entry.getKey()),
                            entry.getValue());
                }

                String name = e.getName().substring(templateName.length() + 1);
                if ("gitignore".equals(name)) {
                    name = ".gitignore";
                }
                File file = new File(output, name);
                File parent = file.getParentFile();
                if (parent.exists()) {
                    if (!parent.isDirectory()) {
                        throw new RuntimeException();
                    }
                } else {
                    if (!parent.mkdirs()) {
                        throw new RuntimeException();
                    }
                }
                OutputStream stream = new FileOutputStream(file);
                IOUtils.copy(new StringReader(content), stream);
                IOUtils.closeQuietly(stream);
            }
        }
    }
}

From source file:com.cognifide.aet.rest.ArtifactServlet.java

@Override
protected void process(DBKey dbKey, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String id = req.getParameter(Helper.ID_PARAM);
    resp.setCharacterEncoding("UTF-8");
    Artifact artifact = artifactsDAO.getArtifact(dbKey, id);
    if (artifact != null) {
        resp.setContentType(artifact.getContentType());
        resp.setHeader("Cache-Control", "public, max-age=31536000");

        OutputStream output = resp.getOutputStream();
        IOUtils.copy(artifact.getArtifactStream(), output);
        output.flush();/*  w ww .j a v a  2s . c om*/
    } else {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        resp.setContentType("application/json");
        resp.getWriter()
                .write(responseAsJson("Unable to get artifact with id : %s form %s", id, dbKey.toString()));
    }
}

From source file:com.opensearchserver.textextractor.ParserAbstract.java

protected final static File createTempFile(InputStream inputStream, String extension) throws IOException {
    File tempFile = File.createTempFile("oss-text-extractor", extension);
    FileOutputStream fos = null;/*from   w w w .j  av a 2 s.com*/
    try {
        fos = new FileOutputStream(tempFile);
        IOUtils.copy(inputStream, fos);
        fos.close();
        fos = null;
        return tempFile;
    } finally {
        if (fos != null)
            IOUtils.closeQuietly(fos);
    }
}

From source file:com.talis.storage.s3.ExternalizableS3Object.java

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(getKey());//from  w  w w  . ja  v  a  2 s. c  o  m
    out.writeUTF(getBucketName());
    out.writeObject(getAcl());
    out.writeBoolean(isMetadataComplete());
    out.writeObject(getMetadataMap());
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        IOUtils.copy(this.getDataInputStream(), buffer);
    } catch (S3ServiceException e) {
        LOG.error("Error copying entity stream", e);
        throw new IOException("Error serializing object", e);
    }
    out.writeInt(buffer.toByteArray().length);
    out.write(buffer.toByteArray());
}

From source file:com.semsaas.jsonxml.tests.Tests.java

public void json2xjson(String jsonResource, String xmlResource) {
    InputStream is = ClassLoader.getSystemResourceAsStream(jsonResource);
    try {// w w w.j  ava  2 s  . c o m
        // The real test
        Node node = Examples.Json2Dom.json2dom(is);

        // Check the results
        StringWriter result = new StringWriter();
        Examples.serialize(node, result);

        StringWriter expected = new StringWriter();
        InputStream xmlIs = ClassLoader.getSystemResourceAsStream(xmlResource);
        IOUtils.copy(xmlIs, expected);

        assertEquals(expected.toString().replaceAll("[\\n\\s]+", ""),
                result.toString().replaceAll("[\\n\\s]+", ""));

    } catch (SAXException e) {
        fail(e.getMessage());
    } catch (TransformerException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    }
}