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:hudson.plugins.sonar.SonarBuildWrapperTest.java

@Test
public void dontMaskDefaultPassword() throws IOException, InterruptedException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    configureSonar(new SonarInstallation("local", "http://localhost:9001", null, null, null, null, null, null,
            null, new TriggersConfig(), "$SONAR_CONFIG_NAME", null, null));

    OutputStream os = wrapper.decorateLogger(mock(AbstractBuild.class), bos);
    IOUtils.write("test sonar\ntest something\n", os);
    assertThat(new String(bos.toByteArray())).isEqualTo("test sonar\ntest something\n");
}

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

public void writeWithLength(byte[] data, String tag) throws IOException {
    lock.readLock().lock();/*from   w  w  w .j  av a2s  .  c o  m*/
    try {
        LogOutputStream os = getOutputStream(tag);
        ByteBuffer bf = ByteBuffer.allocate(4 + data.length);
        bf.put(BytesUtil.intToBytes(data.length));
        bf.put(data);
        bf.flip();
        IOUtils.write(bf.array(), os.getStream());
        os.addBytesWritten(4 + data.length);
        os.getStream().flush();
    } finally {
        lock.readLock().unlock();
    }
}

From source file:com.logsniffer.web.controller.sniffer.publisher.PublishersResourceController.java

@ExceptionHandler(value = Throwable.class)
@ResponseBody//from  www.  ja  v  a 2s.c o  m
public void handleAllExceptions(final Throwable ex, final HttpServletResponse response) throws IOException {
    logger.info("Failed to test event publishing", ex);
    response.setStatus(HttpStatus.CONFLICT.value());
    response.setContentType(MediaType.TEXT_PLAIN_VALUE);
    final String stackTrace = ExceptionUtils.getStackTrace(ex);
    IOUtils.write(stackTrace, response.getOutputStream());
}

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }// ww w  .  j  av a2  s .  c o  m
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:be.fedict.eid.dss.portal.control.bean.UploadBean.java

@Override
public void listener(UploadEvent event) throws Exception {
    this.log.debug("listener");
    UploadItem item = event.getUploadItem();
    this.log.debug("filename: #0", item.getFileName());
    this.filename = item.getFileName();
    this.log.debug("content type: #0", item.getContentType());
    String extension = FilenameUtils.getExtension(this.filename).toLowerCase();
    this.contentType = supportedFileExtensions.get(extension);
    if (null == this.contentType) {
        /*// w w  w  .ja va2s. co m
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(this.filename);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(item.getData(), zipOutputStream);
        zipOutputStream.close();
        this.filename = FilenameUtils.getBaseName(this.filename) + ".zip";
        this.document = outputStream.toByteArray();
        this.contentType = "application/zip";
        return;
    }
    this.log.debug("file size: #0", item.getFileSize());
    this.log.debug("data bytes available: #0", (null != item.getData()));
    if (null != item.getData()) {
        this.document = item.getData();
        return;
    }
    File file = item.getFile();
    if (null != file) {
        this.log.debug("tmp file: #0", file.getAbsolutePath());
        this.document = FileUtils.readFileToByteArray(file);
    }
}

From source file:com.youTransactor.uCube.rpc.RPCManager.java

private void sendSecureCommand(RPCCommand command) throws IOException {
    byte[] payload = command.getPayload();

    if (payload.length == 0) {
        sendInsecureCommand(command);//ww  w. ja va 2  s.  c  om
        return;
    }

    byte[] message = new byte[payload.length + Constants.RPC_SECURED_HEADER_LEN + Constants.RPC_SRED_MAC_SIZE];
    int securedLen = payload.length + Constants.RPC_SECURED_HEADER_CRYPTO_RND_LEN + Constants.RPC_SRED_MAC_SIZE;

    int offset = 0;

    message[offset++] = (byte) (securedLen / 0x100);
    message[offset++] = (byte) (securedLen % 0x100);
    message[offset++] = sequenceNumber++;
    message[offset++] = (byte) (command.getCommandId() / 0x100);
    message[offset++] = (byte) (command.getCommandId() % 0x100);

    message[offset++] = (byte) 0x7F; // TODO should be random

    System.arraycopy(payload, 0, message, offset, payload.length);
    offset += payload.length;

    /* Padding the last 4 bytes with 0x00 (SRED OPT) */
    for (int i = 0; i < Constants.RPC_SRED_MAC_SIZE; i++) {
        message[offset++] = 0x00;
    }

    int crc = computeChecksumCRC16(message);

    out.write(Constants.STX);
    IOUtils.write(message, out);
    out.write((byte) (crc / 0x100));
    out.write((byte) (crc % 0x100));
    out.write(Constants.ETX);

    LogManager.debug(RPCManager.class.getSimpleName(), "sent secure message: 0x" + Tools.bytesToHex(message));
}

From source file:com.formkiq.core.service.workflow.WorkflowServiceImpl.java

@Override
public ModelAndView actions(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    WebFlow flow = FlowManager.get(request);

    Map<String, String[]> parameterMap = request.getParameterMap();

    if (parameterMap.containsKey("_eventId_print")) {
        return getModelAndView(flow, DEFAULT_PDF_VIEW);
    }/*from www  . j  a v  a  2  s. co  m*/

    byte[] bytes = generatePDF(request, flow);

    response.setContentType("application/pdf");
    response.setContentLengthLong(bytes.length);
    IOUtils.write(bytes, response.getOutputStream());
    response.getOutputStream().flush();

    return null;
}

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testFileRefs() throws IOException {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());/*from   www.  jav  a 2s  .co  m*/
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "hello.txt"));
    IOUtils.write("secret\nfoo\n", writer);
    writer.close();
    Configuration conf = new Configuration();

    conf.set("a", "@hello.txt@");
    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    conf.set("aa", "${file(\"hello.txt\")}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aa", null));

    conf.set("aaa", "${file('hello.txt')}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aaa", null));

    writer = new FileWriter(new File(dir, "config.properties"));
    conf.save(writer);
    writer.close();

    conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    reader = new FileReader(new File(dir, "config.properties"));
    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(reader, stringWriter);
    reader.close();
    Assert.assertTrue(stringWriter.toString().contains("@hello.txt@"));
    Assert.assertTrue(stringWriter.toString().contains("${file(\"hello.txt\")}"));
    Assert.assertTrue(stringWriter.toString().contains("${file('hello.txt')}"));
    Assert.assertFalse(stringWriter.toString().contains("secret\nfoo\n"));
}

From source file:gov.nih.nci.cabig.caaers.service.SafetyMonitoringServiceImplTest.java

private void setupRules() throws Exception {
    InputStream in = RuleUtil.getResouceAsStream("safety_signalling_rules_study_1A.xml");
    String xml = RuleUtil.getFileContext(in);
    System.out.println(xml);/*w  w  w.j a  v a2  s. co  m*/
    File f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    System.out.println(f.getAbsolutePath());
    FileWriter fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());
    assertTrue(findRuleSets().isEmpty());
    caaersRulesEngineService.importRules(f.getAbsolutePath());
    f.delete();
    List<RuleSet> ruleSets = findRuleSets();
    assertFalse(ruleSets.isEmpty());
    RuleSet rs = ruleSets.get(0);
    assertTrue(rs.isEnabled());
}

From source file:gobblin.data.management.copy.recovery.RecoveryHelperTest.java

@Test
public void testPurge() throws Exception {
    String content = "contents";

    File persistDirBase = Files.createTempDir();
    persistDirBase.deleteOnExit();//from w  w w . j a  va 2 s . c  om

    State state = new State();
    state.setProp(RecoveryHelper.PERSIST_DIR_KEY, persistDirBase.getAbsolutePath());
    state.setProp(RecoveryHelper.PERSIST_RETENTION_KEY, "1");

    RecoveryHelper recoveryHelper = new RecoveryHelper(FileSystem.getLocal(new Configuration()), state);
    File persistDir = new File(RecoveryHelper.getPersistDir(state).get().toString());
    persistDir.mkdir();

    File file = new File(persistDir, "file1");
    OutputStream os = new FileOutputStream(file);
    IOUtils.write(content, os);
    os.close();
    file.setLastModified(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2));

    File file2 = new File(persistDir, "file2");
    OutputStream os2 = new FileOutputStream(file2);
    IOUtils.write(content, os2);
    os2.close();

    Assert.assertEquals(persistDir.listFiles().length, 2);

    recoveryHelper.purgeOldPersistedFile();

    Assert.assertEquals(persistDir.listFiles().length, 1);
}