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.wavemaker.runtime.FileController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String path = WMAppContext.getInstance().getAppContextRoot();
    boolean isGzipped = false;
    boolean addExpiresTag = false;
    String reqPath = request.getRequestURI();
    String contextPath = request.getContextPath();
    reqPath = reqPath.replaceAll("%20", " ");
    reqPath = reqPath.replaceAll("//", "/");

    // trim off the servlet name
    if (!contextPath.equals("") && reqPath.startsWith(contextPath)) {
        reqPath = reqPath.substring(reqPath.indexOf('/', 1));
    }/*from  w w  w.  j  ava2 s  .  c o  m*/

    if (reqPath.startsWith(WM_BUILD_GZIPPED_URL) || reqPath.startsWith(WM_GZIPPED_URL)
            || reqPath.equals(WM_BUILD_DOJO_JS_URL)) {
        isGzipped = true;
        addExpiresTag = true;
        reqPath += ".gz";
    } else if (reqPath.startsWith(WM_BUILD_DOJO_THEMES_URL) || reqPath.startsWith(WM_BUILD_WM_THEMES_URL)
            || reqPath.startsWith(WM_BUILD_DOJO_FOLDER_URL) || reqPath.equals(WM_BOOT_URL)
            || reqPath.equals(WM_RUNTIME_LOADER_URL) || reqPath.startsWith(WM_IMAGE_URL)
            || reqPath.startsWith(WM_STUDIO_BUILD_URL)) {
        addExpiresTag = true;
    } else if (!reqPath.contains(WM_CONFIG_URL)) {
        throw new WMRuntimeException(MessageResource.STUDIO_UNKNOWN_LOCATION, reqPath, request.getRequestURI());
    }

    File sendFile = null;
    if (!isGzipped && reqPath.lastIndexOf(".js") == reqPath.length() - 3) {
        sendFile = new File(path, reqPath + ".gz");
        if (!sendFile.exists()) {
            sendFile = null;
        } else {
            isGzipped = true;
        }
    }

    if (sendFile == null) {
        sendFile = new File(path, reqPath);
    }

    if (DataServiceLoggers.fileControllerLogger.isDebugEnabled()) {
        DataServiceLoggers.fileControllerLogger
                .debug("FileController: " + sendFile.getAbsolutePath() + "\t (" + reqPath + ")");
    }

    if (sendFile != null && !sendFile.exists()) {
        logger.debug("File " + reqPath + " not found in expected path: " + sendFile);
        handleError(response, "File " + reqPath + " not found in expected path: " + sendFile,
                HttpServletResponse.SC_NOT_FOUND);
    } else if (sendFile != null) {
        if (addExpiresTag) {
            // setting cache expire to one year.
            setCacheExpireDate(response, 365 * 24 * 60 * 60);
        }

        if (!isGzipped) {
            setContentType(response, sendFile);
        } else {
            response.setHeader("Content-Encoding", "gzip");
        }

        OutputStream os = response.getOutputStream();
        InputStream is = new FileInputStream(sendFile);
        if (reqPath.contains(WM_CONFIG_URL)) {
            StringBuilder content = new StringBuilder(IOUtils.toString(is));
            int offset = ServerUtils.getServerTimeOffset();
            int timeout = this.serviceResponse.getConnectionTimeout();
            String timeStamp = "0";
            File timeFile = new File(sendFile.getParent(), "timestamp.txt");
            if (timeFile.exists()) {
                InputStream isTime = new FileInputStream(timeFile);
                timeStamp = IOUtils.toString(isTime);
                isTime.close();
            } else {
                System.out.println("File timestamp.txt not found, using 0");
            }
            content.append("\r\nwm.serverTimeOffset = ").append(offset).append(";");
            content.append("\r\nwm.connectionTimeout = ").append(timeout).append(";");
            content.append("\r\nwm.saveTimestamp = ").append(timeStamp).append(";");

            String language = request.getHeader("accept-language");
            if (language != null && language.length() > 0) {
                int index = language.indexOf(",");
                language = index == -1 ? language : language.substring(0, index);
                content.append("\r\nwm.localeString = '").append(language).append("';");
            }
            File bootFile = new File(sendFile.getParent(), "boot.js");
            if (bootFile.exists()) {
                InputStream is2 = new FileInputStream(bootFile);
                String bootString = IOUtils.toString(is2);
                bootString = bootString.substring(bootString.indexOf("*/") + 2);
                content.append(bootString);
                is2.close();
            } else {
                System.out.println("Boot file not found");
            }
            IOUtils.write(content.toString(), os);
        } else {
            IOUtils.copy(is, os);
        }
        os.close();
        is.close();
    }

    // we've already written our response
    return null;
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/* ww  w  . j av  a 2s.  co m*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir("/some/silly/random/homeDir");

        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");
        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test123");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.cloudera.csd.tools.MetricDescriptorGeneratorTool.java

@Override
public void run(CommandLine cmdLine, OutputStream out, OutputStream err) throws Exception {
    Preconditions.checkNotNull(cmdLine);
    Preconditions.checkNotNull(out);//from w  w w .j  a v a 2  s.c  o m
    Preconditions.checkNotNull(err);

    FileInputStream mdlInputStream = null;
    MapConfiguration config = generateAndValidateConfig(cmdLine);
    try {
        mdlInputStream = new FileInputStream(config.getString(OPT_INPUT_MDL.getLongOpt()));
        JsonMdlParser mdlParser = new JsonMdlParser();
        ServiceMonitoringDefinitionsDescriptor mdl = mdlParser.parse(IOUtils.toByteArray(mdlInputStream));
        ServiceMonitoringDefinitionsDescriptorImpl.Builder mdlBuilder = new ServiceMonitoringDefinitionsDescriptorImpl.Builder(
                mdl);

        MetricFixtureAdapter adapter = newMetricFixtureAdapter(config, out, err);
        adapter.init(config.getString(OPT_INPUT_FIXTURE.getLongOpt()),
                config.getString(OPT_INPUT_CONVENTIONS.getLongOpt()));

        mdlBuilder.addMetricDefinitions(adapter.getServiceMetrics());

        if (null != mdl.getRoles()) {
            List<RoleMonitoringDefinitionsDescriptor> roles = Lists.newArrayList();
            for (RoleMonitoringDefinitionsDescriptor role : mdl.getRoles()) {
                RoleMonitoringDefinitionsDescriptorImpl.Builder roleBuilder = new RoleMonitoringDefinitionsDescriptorImpl.Builder(
                        role);
                roleBuilder.addMetricDefinitions(adapter.getRoleMetrics(role.getName()));
                roles.add(roleBuilder.build());
            }
            mdlBuilder.setRoles(roles);
        }

        if (null != mdl.getMetricEntityTypeDefinitions()) {
            List<MetricEntityTypeDescriptor> entities = Lists.newArrayList();
            for (MetricEntityTypeDescriptor entity : mdl.getMetricEntityTypeDefinitions()) {
                MetricEntityTypeDescriptorImpl.Builder entityBuilder = new MetricEntityTypeDescriptorImpl.Builder(
                        entity);
                entityBuilder.addMetricDefinitions(adapter.getEntityMetrics(entity.getName()));
                entities.add(entityBuilder.build());
            }
            mdlBuilder.setMetricEntityTypeDescriptor(entities);
        }
        FileUtils.write(new File(config.getString(OPT_GENERATE_OUPTUT.getLongOpt(), DEFAULT_OUTPUT_FILE)),
                mdlParser.valueAsString(mdlBuilder.build(), true));
    } catch (Exception ex) {
        LOG.error("Could not run MetricGenerator tool.", ex);
        IOUtils.write(ex.getMessage() + "\n", err);
        throw ex;
    } finally {
        IOUtils.closeQuietly(mdlInputStream);
    }
}

From source file:cz.lbenda.dataman.db.sql.SQLEditorController.java

/** Save data to SQL file */
public void saveToFile(File file) {
    try (FileWriter fr = new FileWriter(file)) {
        IOUtils.write(getText(), fr);
        this.lastFile = file;
    } catch (IOException e) {
        LOG.error("The file isn't writable", e);
        ExceptionMessageFrmController.showException("The file isn't writable", e);
    }/* www. j a  v  a  2s .com*/
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

private static void toFile(String fileName, String data) throws Exception {
    IOUtils.write(data, new FileOutputStream(fileName));

    log.info("Created file " + fileName);
}

From source file:ezbake.deployer.utilities.ArtifactHelpers.java

/**
 * Append to the given ArchiveInputStream writing to the given outputstream, the given entries to add.
 * This will duplicate the InputStream to the Output.
 *
 * @param inputStream - archive input to append to
 * @param output      - what to copy the modified archive to
 * @param filesToAdd  - what entries to append.
 *///from  www.  j ava 2 s. c  o m
private static void appendFilesInTarArchive(ArchiveInputStream inputStream, OutputStream output,
        Iterable<ArtifactDataEntry> filesToAdd) throws DeploymentException {
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    try {
        HashMap<String, ArtifactDataEntry> newFiles = new HashMap<>();
        for (ArtifactDataEntry entry : filesToAdd) {
            newFiles.put(entry.getEntry().getName(), entry);
        }
        GZIPOutputStream gzs = new GZIPOutputStream(output);
        TarArchiveOutputStream aos = (TarArchiveOutputStream) asf
                .createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs);
        aos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        // copy the existing entries
        ArchiveEntry nextEntry;
        while ((nextEntry = inputStream.getNextEntry()) != null) {
            //If we're passing in the same file, don't copy into the new archive
            if (!newFiles.containsKey(nextEntry.getName())) {
                aos.putArchiveEntry(nextEntry);
                IOUtils.copy(inputStream, aos);
                aos.closeArchiveEntry();
            }
        }

        for (ArtifactDataEntry entry : filesToAdd) {
            aos.putArchiveEntry(entry.getEntry());
            IOUtils.write(entry.getData(), aos);
            aos.closeArchiveEntry();
        }
        aos.finish();
        gzs.finish();
    } catch (ArchiveException | IOException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:ch.cyberduck.core.cryptomator.S3MultipartUploadServiceTest.java

@Test
public void testUpload() throws Exception {
    // 5L * 1024L * 1024L
    final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("s3.key"),
                    System.getProperties().getProperty("s3.secret")))) {
    };/*  w ww.  j a v  a2s.co  m*/
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.directory));
    final Path test = new Path(vault, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    session.withRegistry(
            new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final CryptoUploadFeature m = new CryptoUploadFeature<>(session,
            new S3MultipartUploadService(session, new S3WriteFeature(session), 5L * 1024L * 1024L, 5),
            new S3WriteFeature(session), cryptomator);
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(6 * 1024 * 1024);
    IOUtils.write(content, local.getOutputStream(false));
    final TransferStatus writeStatus = new TransferStatus();
    final Cryptor cryptor = cryptomator.getCryptor();
    final FileHeader header = cryptor.fileHeaderCryptor().create();
    writeStatus.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header));
    writeStatus.setLength(content.length);
    m.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            writeStatus, null);
    assertEquals((long) content.length, writeStatus.getOffset(), 0L);
    assertTrue(writeStatus.isComplete());
    assertTrue(new CryptoFindFeature(session, new S3FindFeature(session), cryptomator).find(test));
    assertEquals(content.length,
            new CryptoAttributesFeature(session, new S3AttributesFinderFeature(session), cryptomator).find(test)
                    .getSize());
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    final TransferStatus readStatus = new TransferStatus().length(content.length);
    final InputStream in = new CryptoReadFeature(session, new S3ReadFeature(session), cryptomator).read(test,
            readStatus, new DisabledConnectionCallback());
    new StreamCopier(readStatus, readStatus).transfer(in, buffer);
    assertArrayEquals(content, buffer.toByteArray());
    new CryptoDeleteFeature(session, new S3DefaultDeleteFeature(session), cryptomator)
            .delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:gov.nih.nci.firebird.service.registration.AbstractPdfGenerator.java

void attachFiles(byte[] pdfBytesBeforeAttachment, OutputStream outputStream) throws IOException {
    byte[] pdfBytes = pdfBytesBeforeAttachment;
    for (FirebirdFile firebirdFile : getAttachments()) {
        pdfBytes = attachSupportingFile(pdfBytes, firebirdFile);
    }//ww  w  .  j  a v  a  2s .  co  m
    IOUtils.write(pdfBytes, outputStream);
}

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

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

    RestAssuredMockMvc.config = config()
            .multiPartConfig(multiPartConfig().with().defaultControlName("something"));

    given().multiPart(file).when().post("/fileUploadWithControlNameEqualToSomething").then()
            .body("size", greaterThan(10)).body("name", equalTo("something"))
            .body("originalName", equalTo("filename.txt"));
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void execute() throws MojoExecutionException {
    File sourceDirectory = getSourceDirectory();
    getLog().debug("source=" + sourceDirectory + " target=" + getOutputDirectory());
    if (!(sourceDirectory != null && sourceDirectory.exists())) {
        getLog().info("Request to add '" + sourceDirectory + "' folder. Not added since it does not exist.");
        return;//from  ww  w .j a  v  a 2  s . co  m
    }

    File f = outputDirectory;
    if (!f.exists()) {
        f.mkdirs();
    }
    setupVariables();

    extractJarToDirectory(jythonArtifact.getFile(), temporaryBuildDirectory);

    // now what? we have the jython content, now we need
    // easy_install
    getLog().debug("installing easy_install ...");
    try {
        FileUtils.copyInputStreamToFile(setuptoolsResource.openStream(), setuptoolsJar);
    } catch (IOException e) {
        throw new MojoExecutionException("copying setuptools failed", e);
    }
    try {
        FileUtils.copyInputStreamToFile(botoURL.openStream(), botoFile);
    } catch (IOException e) {
        throw new MojoExecutionException("copying boto failed", e);
    }
    try {
        FileUtils.copyInputStreamToFile(tropoURL.openStream(), tropoFile);
    } catch (IOException e) {
        throw new MojoExecutionException("copying troposphere 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().debug("installing easy_install done");
    Iterator<String> it = libs.iterator();
    while (it.hasNext()) {
        String s = it.next();
        if (s == null || s.length() == 0) {
            it.remove();
        }
    }
    if (libs == null || libs.size() == 0) {
        getLog().info("no python libraries requested");
    } else {
        getLog().debug("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"), null);
        getLog().debug("installing requested python libraries done");
    }

    processFiles();
}