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:ch.cyberduck.core.dropbox.DropboxReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final Path drive = new DefaultHomeFinderService(session).find();
    final Path test = new Path(drive, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    new DropboxTouchFeature(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  w  w w  .j a va  2  s  .  c om
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<String>(new DropboxWriteFeature(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 DropboxReadFeature read = new DropboxReadFeature(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 DropboxDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:com.cloudbees.jenkins.support.api.FileContent.java

@Override
public void writeTo(OutputStream os, ContentFilter filter) throws IOException {
    if (isBinary || filter == null) {
        writeTo(os);//w  w w.java  2  s.  c om
    }

    try {
        if (maxSize == -1) {
            for (String s : Files.readAllLines(file.toPath())) {
                String filtered = filter.filter(s);
                IOUtils.write(filtered, os);
            }
        } else {
            try (TruncatedFileReader reader = new TruncatedFileReader(file, maxSize)) {
                String s;
                while ((s = reader.readLine()) != null) {
                    String filtered = filter.filter(s);
                    IOUtils.write(filtered, os);
                }
            }
        }
    } catch (FileNotFoundException | NoSuchFileException e) {
        OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING);
        try {
            PrintWriter pw = new PrintWriter(osw, true);
            try {
                pw.println("--- WARNING: Could not attach " + file + " as it cannot currently be found ---");
                pw.println();
                SupportLogFormatter.printStackTrace(e, pw);
            } finally {
                pw.flush();
            }
        } finally {
            osw.flush();
        }
    }
}

From source file:com.cloudera.cli.validator.Main.java

/**
 * From the arguments, run the validation.
 *
 * @param args command line arguments//from  w  ww. j  a  va2  s .c  o  m
 * @throws IOException anything goes wrong with streams.
 * @return exit code
 */
public int run(String[] args) throws IOException {
    Writer writer = new OutputStreamWriter(outStream, Constants.CHARSET_UTF_8);
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    try {
        BeanDefinition cmdOptsbeanDefinition = BeanDefinitionBuilder
                .rootBeanDefinition(CommandLineOptions.class).addConstructorArgValue(appName)
                .addConstructorArgValue(args).getBeanDefinition();
        ctx.registerBeanDefinition(CommandLineOptions.BEAN_NAME, cmdOptsbeanDefinition);
        ctx.register(ApplicationConfiguration.class);
        ctx.refresh();
        CommandLineOptions cmdOptions = ctx.getBean(CommandLineOptions.BEAN_NAME, CommandLineOptions.class);
        CommandLineOptions.Mode mode = cmdOptions.getMode();
        if (mode == null) {
            throw new ParseException("No valid command line arguments");
        }
        ValidationRunner runner = ctx.getBean(mode.runnerName, ValidationRunner.class);
        boolean success = runner.run(cmdOptions.getCommandLineOptionActiveTarget(), writer);
        if (success) {
            writer.write("Validation succeeded.\n");
        }
        return success ? 0 : -1;
    } catch (BeanCreationException e) {
        String cause = e.getMessage();
        if (e.getCause() instanceof BeanInstantiationException) {
            BeanInstantiationException bie = (BeanInstantiationException) e.getCause();
            cause = bie.getMessage();
            if (bie.getCause() != null) {
                cause = bie.getCause().getMessage();
            }
        }
        IOUtils.write(cause + "\n", errStream);
        CommandLineOptions.printUsageMessage(appName, errStream);
        return -2;
    } catch (ParseException e) {
        LOG.debug("Exception", e);
        IOUtils.write(e.getMessage() + "\n", errStream);
        CommandLineOptions.printUsageMessage(appName, errStream);
        return -2;
    } finally {
        if (ctx != null) {
            ctx.close();
        }
        writer.close();
    }
}

From source file:at.tfr.securefs.process.ProcessFilesTest.java

@Test(expected = SecureFSError.class)
public void overwriteExistingFileProhibited() throws Exception {
    // Given: the target directory AND file(!), the source file
    toFilesPath = Files.createDirectories(toRoot.resolve(DATA_FILES));
    final String data = "Hallo Echo";
    try (OutputStream os = cp.getEncrypter(fromFile)) {
        IOUtils.write(data, os);
    }//from   ww w  .  ja  v a 2 s .  co  m
    Files.copy(fromFile, targetToFile);
    Assert.assertTrue(Files.exists(targetToFile));

    ProcessFilesData cfd = new ProcessFilesData().setFromRootPath(fromRoot.toString())
            .setToRootPath(toRoot.toString()).setUpdate(false).setProcessActive(true);

    // When: copy of source file to toRoot
    ProcessFilesBean pf = new ProcessFilesBean(new MockSecureFsCache());
    pf.copy(fromFile, fromRoot.getNameCount(), toRoot, cp, newSecret, cfd);

    // Then: Exception overwrite not allowed!!
}

From source file:it.biztech.btable.api.FileApi.java

@GET
@Path("/read")
@Produces("text/plain")
public void read(@QueryParam(MethodParams.PATH) @DefaultValue("") String path,
        @Context HttpServletResponse response) throws IOException {
    try {//from  w w w .j  av a 2 s .c  o m
        IBasicFile file = Utils.getFile(path, null);

        if (file == null) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        IPluginResourceLoader resLoader = PentahoSystem.get(IPluginResourceLoader.class, null);
        String maxAge = resLoader.getPluginSetting(this.getClass(), "max-age");

        String mimeType;
        try {
            final MimeTypes.FileType fileType = MimeTypes.FileType.valueOf(file.getExtension().toUpperCase());
            mimeType = MimeTypes.getMimeType(fileType);
        } catch (java.lang.IllegalArgumentException ex) {
            mimeType = "";
        } catch (EnumConstantNotPresentException ex) {
            mimeType = "";
        }

        response.setHeader("Content-Type", mimeType);
        response.setHeader("content-disposition", "inline; filename=\"" + file.getName() + "\"");

        if (maxAge != null) {
            response.setHeader("Cache-Control", "max-age=" + maxAge);
        }

        byte[] contents = IOUtils.toByteArray(file.getContents());

        IOUtils.write(contents, response.getOutputStream());

        response.getOutputStream().flush();
    } catch (SecurityException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.shuzhilian.icu.license.LicenseGenerator.java

private void generateLicense(String path, String name, char[] password, Properties properties)
        throws ParseException, IOException {

    String productName = properties.getProperty("ProductName");
    String productId = properties.getProperty("ProductId");
    String version = properties.getProperty("Version");
    String holder = properties.getProperty("Holder");
    String issuser = properties.getProperty("Issuser");
    String issuseDate = properties.getProperty("IssuseDate");
    String startDate = properties.getProperty("StartDate");
    String endDate = properties.getProperty("EndDate");
    String maxUser = properties.getProperty("MaxUser");
    String maxCore = properties.getProperty("MaxCore");
    String maxWorkflow = properties.getProperty("MaxWorkFlow");
    String maxJob = properties.getProperty("MaxJob");
    String machineId = properties.getProperty("MachineId");
    String avaliableOperator = properties.getProperty("AvaliableOperator");

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

    License.Builder builder = new License.Builder().withHolder(holder)
            .withGoodAfterDate(dateFormat.parse(startDate).getTime())
            .withGoodBeforeDate(dateFormat.parse(endDate).getTime())
            .withIssueDate(dateFormat.parse(issuseDate).getTime()).withIssuer(issuser).withProductKey(productId)
            .withSubject(productName).withVersion(version).withMaxUser(Integer.parseInt(maxUser))
            .withMaxCore(Integer.parseInt(maxCore)).withMaxJob(Integer.parseInt(maxJob))
            .withMaxWorkflow(Integer.parseInt(maxWorkflow)).withMachineId(machineId);

    String[] operators = avaliableOperator.split(",");
    for (String operator : operators) {
        builder.addFeature(operator.toLowerCase().trim());
    }/*from w  ww.j av a 2  s.  c  o  m*/

    License license = builder.build();
    byte[] licenseData = LicenseCreator.getInstance().signAndSerializeLicense(license, password);

    try {
        File file = new File(path, name);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        IOUtils.write(licenseData, new FileOutputStream(file));
    } catch (IOException e) {
        throw e;
    }

}

From source file:com.movilizer.connector.utils.DataContainerLogger.java

protected void writeTextFile(File currentDir, String filename, byte[] content) {
    filename = filename.replace(":", "-");
    File tFile = new File(currentDir, filename + ".xml");
    try {//from  ww  w.  j av  a  2s  . c om
        FileOutputStream output = new FileOutputStream(tFile);
        IOUtils.write(content, output);
        output.close();
    } catch (Exception e) {
        logger.error("Error while writing to file " + tFile.getAbsolutePath() + ": ", e);
    }
}

From source file:net.certiv.json.IOProcessor.java

public void storeData(String data) {
    if (FileOut) {
        try {/*from  w ww.  j  av  a  2  s .  c om*/
            FileUtils.writeStringToFile(new File(target), data);
        } catch (IOException e) {
            Log.error(this, "Error writing result data to file '" + target + "'", e);
        }
    } else if (StdIO) {
        OutputStream out = System.out;
        try {
            IOUtils.write(data, out);
        } catch (IOException e) {
            Log.error(this, "Error writing result data to standard out", e);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:com.taobao.tanggong.DataFilePersisterImpl.java

private void saveHash2UrlMap() {
    if (null != dataDirectory && !this.uri2HashCodes.isEmpty()) {
        File url2HashMapFile = new File(this.dataDirectory, "index.txt");

        File url2HashMapBackupFile = new File(this.dataDirectory, "index.txt.bak");

        if (url2HashMapFile.exists()) {
            url2HashMapFile.renameTo(url2HashMapBackupFile);
        }/*from ww  w. j  a v a 2 s.c o m*/

        OutputStream output = null;
        try {
            output = new FileOutputStream(url2HashMapFile);

            StringBuilder sb = new StringBuilder();
            for (String k : this.uri2HashCodes.keySet()) {

                sb.append(k).append("=");
                Collection<String> vs = this.uri2HashCodes.get(k);
                if (!vs.isEmpty()) {
                    for (String v : vs) {
                        sb.append(v).append(",");
                    }
                    sb.delete(sb.length() - 1, sb.length());
                    sb.append("\n");
                }

            }

            IOUtils.write(sb.toString(), output);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:deployer.publishers.artifact.PythonRequirementsPublisherTest.java

@Test
public void testGenerateEntries() throws DeploymentException, ArchiveException, IOException {

    wheels[0] = "";
    ByteBuffer buffer = TestUtils.createSampleOpenShiftWebAppTarBallWithEmptyFiles(wheels);

    // prepare the deployment artifact
    DeploymentMetadata metadata = new DeploymentMetadata();
    DeploymentArtifact artifact = new DeploymentArtifact(metadata, buffer);

    // generateEntries
    PythonRequirementsPublisher publisher = new PythonRequirementsPublisher();
    List<ArtifactDataEntry> entries = (List) publisher.generateEntries(artifact);

    // initial checks
    Assert.assertEquals(entries.size(), 1);
    ArtifactDataEntry entry = entries.get(0);
    Assert.assertEquals(entry.getEntry().getName(), "requirements.txt");

    // write contents out to file
    String filepath = "/tmp/" + entry.getEntry().getName();
    File requirementsFile = new File(filepath);
    FileOutputStream output = new FileOutputStream(requirementsFile);
    IOUtils.write(entry.getData(), output);

    // read file and check lines
    String[] assertionLines = new String[5];
    assertionLines[0] = "";
    assertionLines[1] = "coverage==3.7.1";
    assertionLines[2] = "cryptography==0.7.2";
    assertionLines[3] = "django_crispy_forms==1.4.0";
    assertionLines[4] = "enum34==1.0.4";

    FileInputStream fis = new FileInputStream(requirementsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = null;// w  w  w .  j a  va 2 s .  c o  m
    List<String> requirementContents = new ArrayList<String>();
    while ((line = br.readLine()) != null) {
        if (line.contains("=="))
            requirementContents.add(line);
    }

    for (int i = 1; i < assertionLines.length; i++) {
        line = assertionLines[i];
        Assert.assertTrue(line + " not found in: " + requirementContents.toString(),
                requirementContents.contains(line));
    }
}