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:eu.europa.ejusticeportal.dss.controller.action.ValidateSignedAcrobatPdfTest.java

/**
 * Initialises the trusted list store and creates the sealed PDF for the other tests.
 *
 * @throws Exception/*from   w ww.  ja v  a2s  .  c o  m*/
 */
@BeforeClass
public static void createSealedPDF() throws Exception {

    StringWriter writer = new StringWriter();
    IOUtils.copy(PortalFacadeTestImpl.class.getClassLoader().getResourceAsStream("dss/original.xml"), writer,
            "UTF-8");
    String xml = writer.toString();

    System.setProperty(SealedPDFService.PASSWORD_FILE_PROPERTY, "classpath:server.pwd");
    System.setProperty(SealedPDFService.CERTIFICATE_FILE_PROPERTY, "classpath:server.p12");
    portal = new PortalFacadeTestImpl(xml, "dss/original.pdf");
    HttpProxyConfig hc = Mockito.mock(HttpProxyConfig.class);
    Mockito.when(hc.isHttpEnabled()).thenReturn(Boolean.FALSE);
    Mockito.when(hc.isHttpsEnabled()).thenReturn(Boolean.FALSE);
    DocumentValidationConfig config = Mockito.mock(DocumentValidationConfig.class);
    Mockito.when(config.getOriginValidationLevel()).thenReturn(ValidationLevel.DISABLED);
    Mockito.when(config.getTamperedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getRevokedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getSignedValidationLevel()).thenReturn(ValidationLevel.EXCEPTION);
    Mockito.when(config.getSealMethod()).thenReturn(SealMethod.SEAL_CUSTOM);
    Mockito.when(config.getTrustedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getWorkflowValidationLevel()).thenReturn(ValidationLevel.DISABLED);
    //Mockito.when(config.getLotlUrl()).thenReturn("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml");
    Mockito.when(config.getLotlUrl()).thenReturn("https://example.com");
    Mockito.when(config.getRefreshPeriod()).thenReturn(3600);
    RefreshingTrustedListsCertificateSource.init(hc, config);
    RefreshingTrustedListsCertificateSource.getInstance().refresh();

    byte[] doc = SealedPDFService.getInstance().sealDocument(portal.getPDFDocument(getRequest()),
            portal.getPDFDocumentXML(getRequest()), "disclaimer", SealMethod.SEAL_CUSTOM);// document with embedded XML, signed by the server
    OutputStream os = new FileOutputStream(SEALED_PDF_FILE);
    IOUtils.write(doc, os);
    PAdESService pades = new PAdESService(new CommonCertificateVerifier(true)) {

        @Override
        protected void assertSigningDateInCertificateValidityRange(SignatureParameters parameters) {
        }

    };
    SignatureParameters p = new SignatureParameters();
    p.setDigestAlgorithm(DigestAlgorithm.SHA256);
    p.setPrivateKeyEntry(SealedPDFService.getInstance().getToken().getKeys().get(0));
    p.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B);
    p.setSigningToken(SealedPDFService.getInstance().getToken());
    DSSDocument signed = pades.signDocument(new InMemoryDocument(doc), p);
    os = new FileOutputStream(SIGNED_PDF_FILE);
    IOUtils.write(signed.getBytes(), os);

}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}//from www .j a v  a2  s .  c o m
 */
public void copyMageTabZipToOutputStream(CaArrayEntityReference experimentRef, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    MageTabFileSet mtset = exportMageTab(experimentRef);
    ZipOutputStream zos = new ZipOutputStream(ostream);
    zos.putNextEntry(new ZipEntry(mtset.getIdf().getMetadata().getName()));
    IOUtils.write(mtset.getIdf().getContents(), zos);
    zos.putNextEntry(new ZipEntry(mtset.getSdrf().getMetadata().getName()));
    IOUtils.write(mtset.getSdrf().getContents(), zos);
    for (gov.nih.nci.caarray.external.v1_0.data.File dataFile : mtset.getDataFiles()) {
        zos.putNextEntry(new ZipEntry(dataFile.getMetadata().getName()));
        copyFileContentsToOutputStream(dataFile.getReference(), false, zos);
    }
    zos.finish();
}

From source file:com.google.gwt.benchmark.compileserver.server.manager.BenchmarkWorker.java

private void writeHostPage(File outputDir, String moduleName) throws IOException {
    String tpl = moduleTemplate.replace("{module_nocache}", moduleName + "/" + moduleName + ".nocache.js");
    FileOutputStream stream = null;
    try {//  w  w  w. j a  v  a  2 s .co m
        stream = new FileOutputStream(new File(outputDir, moduleName + ".html"));
        IOUtils.write(tpl.getBytes("UTF-8"), stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.highcharts.export.controller.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);/*w  ww. j  av a 2  s  .co  m*/
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    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.palantir.docker.compose.logging.FileLogCollectorShould.java

@Test
public void collect_logs_when_one_container_is_running_and_does_not_terminate_until_after_start_collecting_is_run()
        throws Exception {
    when(compose.ps()).thenReturn(TestContainerNames.of("db"));
    CountDownLatch latch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        if (!latch.await(1, TimeUnit.SECONDS)) {
            throw new RuntimeException("Latch was not triggered");
        }//from   w  w  w.ja  v  a  2s  .  c o m
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("log", outputStream);
        return false;
    });
    logCollector.startCollecting(compose);
    latch.countDown();
    logCollector.stopCollecting();
    assertThat(logDirectory.listFiles(), arrayContaining(fileWithName("db.log")));
    assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log")));
}

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

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*from  w w w  .  java 2 s .  c om*/
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:de.bps.onyx.plugin.OnyxExportManager.java

public void exportResults(List<QTIResultSet> resultSets, ZipOutputStream exportStream,
        CourseNode currentCourseNode) {/*from www .  j a  v a  2  s .  c o  m*/
    final String path = createTargetFilename(currentCourseNode.getShortTitle(), "TEST");
    for (final QTIResultSet rs : resultSets) {
        String resultXml = getResultXml(rs.getIdentity().getName(),
                currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(),
                currentCourseNode.getIdent(), rs.getAssessmentID());

        String filename = path + "/" + rs.getIdentity().getName() + "_" + rs.getCreationDate() + ".xml";
        try {
            exportStream.putNextEntry(new ZipEntry(filename));
            IOUtils.write(resultXml, exportStream);
            exportStream.closeEntry();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//from   w w w.j  a v a 2 s. c  o m
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.linkedin.r2.filter.compression.stream.TestStreamingCompression.java

@Test
public void testDeflateCompressor()
        throws IOException, InterruptedException, CompressionException, ExecutionException {
    StreamingCompressor compressor = new DeflateCompressor(_executor);
    final byte[] origin = new byte[BUF_SIZE];
    Arrays.fill(origin, (byte) 'c');

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DeflaterOutputStream zlib = new DeflaterOutputStream(out);
    IOUtils.write(origin, zlib);
    zlib.close();/*from www  .  j a  va 2  s  . com*/
    byte[] compressed = out.toByteArray();

    testCompress(compressor, origin, compressed);
    testDecompress(compressor, origin, compressed);
    testCompressThenDecompress(compressor, origin);
}

From source file:com.github.rwitzel.streamflyer.experimental.bytestream.ByteStreamTest.java

private void assertOutputConversion_viaCharsetName(String charsetName, boolean conversionErrorsExpected)
        throws Exception {

    byte[] originalBytes = createBytes();

    {/*from   w ww.  j ava  2 s . co m*/
        // byte array as byte stream
        ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream();
        // byte stream as character stream
        Writer targetWriter = new OutputStreamWriter(targetByteStream, charsetName);
        // modifying writer (we don't modify here)
        Writer modifyingWriter = new ModifyingWriter(targetWriter, new RegexModifier("a", 0, "a"));
        // character stream as byte stream
        OutputStream modifyingByteStream = new WriterOutputStream(modifyingWriter, charsetName);
        // byte stream as byte array
        IOUtils.write(originalBytes, modifyingByteStream);
        modifyingByteStream.close();

        assertBytes(originalBytes, targetByteStream.toByteArray(), conversionErrorsExpected);
    }
}