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.jayway.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

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

    Greeting greeting = new Greeting();
    greeting.setFirstName("John");
    greeting.setLastName("Doe");

    String content = given().multiPart("controlName1", file, "mime-type1")
            .multiPart("controlName2", greeting, "application/json").when().post("/multiFileUpload").then()
            .root("[%d]").body("size", withArgs(0), is(13)).body("name", withArgs(0), equalTo("controlName1"))
            .body("originalName", withArgs(0), equalTo("something"))
            .body("mimeType", withArgs(0), equalTo("mime-type1"))
            .body("content", withArgs(0), equalTo("Something3210")).body("size", withArgs(1), greaterThan(10))
            .body("name", withArgs(1), equalTo("controlName2"))
            .body("originalName", withArgs(1), equalTo("file"))
            .body("mimeType", withArgs(1), equalTo("application/json"))
            .body("content", withArgs(1), notNullValue()).extract().path("[1].content");

    JsonPath jsonPath = new JsonPath(content);

    assertThat(jsonPath.getString("firstName"), equalTo("John"));
    assertThat(jsonPath.getString("lastName"), equalTo("Doe"));
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

public static void unTar(File inFile, File untarDir) throws IOException, ArchiveException {

    final InputStream is = new FileInputStream(inFile);
    final TarArchiveInputStream in = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream(ArchiveStreamFactory.TAR, is);
    TarArchiveEntry entry = null;// w ww  . j  a  v  a  2s. c o m
    untarDir.mkdirs();
    while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) {
        byte[] content = new byte[(int) entry.getSize()];
        in.read(content);
        final File entryFile = new File(untarDir, entry.getName());
        if (entry.isDirectory() && !entryFile.exists()) {
            if (!entryFile.mkdirs()) {
                throw new IOException("Create directory failed: " + entryFile.getAbsolutePath());
            }
        } else {
            final OutputStream out = new FileOutputStream(entryFile);
            IOUtils.write(content, out);
            out.close();
        }
    }
    in.close();
}

From source file:Highcharts.ExportController.java

@RequestMapping(method = RequestMethod.POST)
    public void exporter(@RequestParam(value = "svg", required = false) String svg,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "filename", required = false) String filename,
            @RequestParam(value = "width", required = false) String width,
            @RequestParam(value = "scale", required = false) String scale,
            @RequestParam(value = "options", required = false) String options,
            @RequestParam(value = "constr", required = false) String constructor,
            @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
            HttpServletRequest request) throws ServletException, IOException, InterruptedException,
            SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

        long start1 = System.currentTimeMillis();

        MimeType mime = getMime(type);
        filename = getFilename(filename);
        Float parsedWidth = widthToFloat(width);
        Float parsedScale = scaleToFloat(scale);
        options = sanitize(options);//from  ww w  .  j a  v  a 2s .  c om
        String input;

        boolean convertSvg = false;

        if (options != null) {
            // create a svg file out of the options
            input = options;
            callback = sanitize(callback);
        } else {
            // assume SVG conversion
            if (svg == null) {
                throw new ServletException("The manadatory svg POST parameter is undefined.");
            } else {
                svg = sanitize(svg);
                if (svg == null) {
                    throw new ServletException("The manadatory svg POST parameter is undefined.");
                }
                convertSvg = true;
                input = svg;
            }
        }

        ByteArrayOutputStream stream = null;
        if (convertSvg && mime.equals(MimeType.SVG)) {
            // send this to the client, without converting.
            stream = new ByteArrayOutputStream();
            stream.write(input.getBytes());
        } else {
            //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);
            stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);
        }

        if (stream == null) {
            throw new ServletException("Error while converting");
        }

        logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentLength(stream.size());
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-disposition",
                "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\"");

        IOUtils.write(stream.toByteArray(), response.getOutputStream());
        response.flushBuffer();
    }

From source file:com.square.document.core.service.implementations.GedServiceImpl.java

@Override
public RetourAjoutDocumentDto ajouterDocument(DocumentDto document, String utilisateur) {
    if (document.getNumeroClient() == null || document.getNumeroClient().trim().isEmpty()) {
        throw new BusinessException(messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_NUMBER_USER_REQUIRED));
    }/* ww  w .  j a v a 2  s .  com*/
    final String cheminDossierClient = gedMappingService.getCheminRepertoire() + "/"
            + document.getNumeroClient();

    creerDossier(cheminDossierClient);

    if (document.getNom() == null) {
        throw new BusinessException(messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_NAME_REQUIRED));
    }

    final String name = Calendar.getInstance().getTimeInMillis() + "-" + document.getNom();
    final File file = new File(cheminDossierClient + "/" + name);

    try {
        file.createNewFile();
        final FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.write(document.getContenu(), fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    } catch (IOException e) {
        throw new BusinessException(messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_CONTENU));
    }

    final Set<Tag> listeTypes = new HashSet<Tag>();
    // TODO : A reprendre

    for (CodeLibelleDto typeDocument : document.getTypes()) {
        final Tag tag = tagDao.getTagByCriteria(typeDocument.getCode());
        if (tag == null) {
            throw new BusinessException("tag null");
        }
        listeTypes.add(tag);
    }

    final Document docToSave = mapperDozerBean.map(document, Document.class);
    docToSave.setNom(name);
    docToSave.setTags(listeTypes);

    documentDao.ajoutDocument(docToSave);

    final RetourAjoutDocumentDto createdUpdatedFile = new RetourAjoutDocumentDto();
    createdUpdatedFile.setIdentifiantDocument(String.valueOf(docToSave.getId()));

    return createdUpdatedFile;
}

From source file:com.alibaba.zonda.logger.server.writer.OutputStreamManager.java

public void write(byte[] data, String tag) throws IOException {
    lock.readLock().lock();//from  ww  w.j  ava  2s.c  om
    try {
        LogOutputStream os = getOutputStream(tag);
        IOUtils.write(data, os.getStream());
        os.addBytesWritten(data.length);
        os.getStream().flush();
    } finally {
        lock.readLock().unlock();
    }
}

From source file:net.sf.mavenjython.JythonMojo.java

/**
 * Strategy A: include jython in plugin. Extract on the run.
 * //from  www.j  av  a2s. c om
 * Strategy B: Project also has dependency on jython. We find that jar and
 * extract it and work from there.
 * 
 * B has the benefit that we don't have to update this plugin for every
 * version and the user needs the jython dependency anyway to call the
 * Python Console
 */
public void execute() throws MojoExecutionException {
    setupVariables();

    extractJarToDirectory(jythonArtifact.getFile(), temporaryBuildDirectory);

    // now what? we have the jython content, now we need
    // easy_install
    getLog().info("installing easy_install ...");
    try {
        if (OVERRIDE || !setuptoolsJar.exists()) {
            FileUtils.copyInputStreamToFile(setuptoolsResource.openStream(), setuptoolsJar);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("copying setuptools failed", e);
    }
    extractJarToDirectory(setuptoolsJar, new File(sitepackagesdir, SETUPTOOLS_EGG));
    try {
        IOUtils.write("./" + SETUPTOOLS_EGG + "\n",
                new FileOutputStream(new File(sitepackagesdir, "setuptools.pth")));
    } catch (IOException e) {
        throw new MojoExecutionException("writing path entry for setuptools failed", e);
    }
    getLog().info("installing easy_install done");

    if (libraries == null) {
        getLog().info("no python libraries requested");
    } else {
        getLog().info("installing requested python libraries");
        // then we need to call easy_install to install the other
        // dependencies.
        runJythonScriptOnInstall(temporaryBuildDirectory,
                getEasyInstallArgs("Lib/site-packages/" + SETUPTOOLS_EGG + "/easy_install.py"));
        getLog().info("installing requested python libraries done");
    }

    getLog().info("copying requested libraries");
    /**
     * we installed the packages into our temporary build directory now we
     * want to move these libraries into outputDirectory/Lib
     * 
     * <pre>
     * mv --no-override temporaryBuildDirectory/Lib/site-packages/*.egg/* outputDirectory/Lib/
     * </pre>
     */
    for (File i : sitepackagesdir.listFiles(
            (FileFilter) new AndFileFilter(DirectoryFileFilter.INSTANCE, new SuffixFileFilter(".egg")))) {
        getLog().info("copying " + i + " into " + new File(outputDirectory, "Lib"));
        try {
            FileUtils.deleteDirectory(new File(installlibdir, i.getName()));
        } catch (IOException e) {
        }
        try {
            FileUtils.copyDirectory(i, installlibdir);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "copying " + i + " to " + new File(outputDirectory, "Lib") + " failed", e);
        }
    }

    /**
     * Setuptools installs a site.py for every package. This might conflict
     * with the jython installation. All it does anyway is help look for
     * eggs, so it wouldn't help us. Errors are ignored here.
     */
    new File(installlibdir, "site.py").delete();
    new File(installlibdir, "site$py.class").delete();
    getLog().info("copying requested libraries done");

    /**
     * If the project does not want its python sources to be in Lib/ it
     * needs to call
     * 
     * PySystemState.addPaths(path, jarFileName + "/myLibFolder");
     * 
     * before starting Python up.
     */
}

From source file:com.sap.prd.mobile.ios.mios.VersionInfoXmlManager.java

private void createVersionInfoFile(final String groupId, final String artifactId, final String version,
        Properties versionInfo, List<Dependency> dependencies, OutputStream os)
        throws MojoExecutionException, JAXBException {
    try {// w  ww . jav a  2  s . c  om

        final Versions versions = new Versions();

        for (final Dependency dep : dependencies)
            versions.addDependency(dep);

        final SCM scm = new SCM();
        scm.setConnection(SCMUtil.getConnectionString(versionInfo, false));
        scm.setRevision(SCMUtil.getRevision(versionInfo));

        final Coordinates coordinates = new Coordinates();
        coordinates.setGroupId(groupId);
        coordinates.setArtifactId(artifactId);
        coordinates.setVersion(version);

        versions.setScm(scm);
        versions.setCoordinates(coordinates);

        final JAXBContext context = JAXBContext.newInstance(Versions.class);

        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                "urn:xml.sap.com:XCodePlugin:VersionInfo" + " " + NEXUS_URL + "/content/repositories/"
                        + SCHEMA_REPOSITORY + "/" + SCHEMA_GROUP_ID.replace(".", "/") + "/" + SCHEMA_ARTIFACT_ID
                        + "/" + SCHEMA_VERSION + "/" + SCHEMA_ARTIFACT_ID + "-" + SCHEMA_VERSION + ".xsd");

        final ByteArrayOutputStream byteOs = new ByteArrayOutputStream();

        marshaller.marshal(versions, byteOs);

        final byte[] b = byteOs.toByteArray();

        DomUtils.validateDocument(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(b)));

        IOUtils.write(b, os);
    } catch (ParserConfigurationException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (SAXException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    }
}

From source file:ee.ria.xroad.common.conf.globalconf.GenerateTestData.java

static String hash(String content) throws Exception {
    DigestCalculator dc = createDigestCalculator("SHA-512");
    IOUtils.write(content, dc.getOutputStream());

    return encodeBase64(dc.getDigest());
}

From source file:com.devnexus.ting.web.controller.PresentationController.java

@RequestMapping(value = "/s/presentations/{presentationId}/slides", method = RequestMethod.GET)
public void getPresentationSlides(@PathVariable("presentationId") Long presentationId,
        HttpServletResponse response) {/*from w ww. j  ava 2 s .c om*/

    final FileData presentationFileData = businessService.getPresentationFileData(presentationId);

    if (presentationFileData != null) {

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition",
                "attachment; filename=\"" + presentationFileData.getName() + "\"");
        response.setContentLength(presentationFileData.getFileSize().intValue());
        try {
            IOUtils.write(presentationFileData.getFileData(), response.getOutputStream());
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

    } else {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

}

From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.java

private void createVersionInfoFile(final String groupId, final String artifactId, final String version,
        Properties versionInfo, List<Dependency> dependencies, OutputStream os)
        throws MojoExecutionException, JAXBException {
    try {/* ww w .ja  v a 2  s  .  c om*/

        final String connectionString = "scm:perforce:" + versionInfo.getProperty("port") + ":"
                + getDepotPath(versionInfo.getProperty("depotpath"));

        final Versions versions = new Versions();

        for (final Dependency dep : dependencies)
            versions.addDependency(dep);

        final SCM scm = new SCM();
        scm.setConnection(connectionString);
        scm.setRevision(versionInfo.getProperty("changelist"));

        final Coordinates coordinates = new Coordinates();
        coordinates.setGroupId(groupId);
        coordinates.setArtifactId(artifactId);
        coordinates.setVersion(version);

        versions.setScm(scm);
        versions.setCoordinates(coordinates);

        final JAXBContext context = JAXBContext.newInstance(Versions.class);

        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                "urn:xml.sap.com:XCodePlugin:VersionInfo" + " " + NEXUS_URL + "/content/repositories/"
                        + SCHEMA_REPOSITORY + "/" + SCHEMA_GROUP_ID.replace(".", "/") + "/" + SCHEMA_ARTIFACT_ID
                        + "/" + SCHEMA_VERSION + "/" + SCHEMA_ARTIFACT_ID + "-" + SCHEMA_VERSION + ".xsd");

        final ByteArrayOutputStream byteOs = new ByteArrayOutputStream();

        marshaller.marshal(versions, byteOs);

        final byte[] b = byteOs.toByteArray();

        DomUtils.validateDocument(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(b)));

        IOUtils.write(b, os);
    } catch (ParserConfigurationException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (SAXException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    }
}