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.GetSealedPdfTest.java

@SuppressWarnings("unchecked")
private void getSealedPdf() throws Exception {
    GetSealedPdf d = new GetSealedPdf();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    HttpServletRequest request = getRequest();
    request.getParameterMap().put(SigningAction.DATA_PARAM, new String[] { Utils.toString(new Fingerprint()) });
    ServletOutputStream sos = new ServletOutputStreamImpl(baos);
    d.elaborate(portal, request, getResponse(sos));
    String s = new String(baos.toByteArray(), "UTF-8");
    Gson gson = new Gson();
    DataWrapper w = gson.fromJson(s, DataWrapper.class);
    SealedPDF spdf = (SealedPDF) Utils.fromString(w.getData());
    byte[] doc = Base64.decodeBase64(spdf.getPdfBase64());
    OutputStream os = new FileOutputStream("target/hello-world-sealed.pdf");
    IOUtils.write(doc, os);
    PDFDocumentValidator validator = (PDFDocumentValidator) SignedDocumentValidator
            .fromDocument(new InMemoryDocument(doc));

    validator.setCertificateVerifier(new CommonCertificateVerifier(null, null, null, null));
    doc = PdfUtils.signPdf(doc, SealedPDFService.getInstance().getToken());
    assertTrue(//  w  w w.  j av a2 s .com
            TestUtils.isSealed(null, doc, SealedPDFService.getInstance().getToken(), SealMethod.SEAL_CUSTOM));
    String testXML = new String(PdfUtils.extractAttachment(
            IOUtils.toByteArray(new FileInputStream("target/hello-world-sealed.pdf")),
            SealedPDFService.EMBEDDED_XML_ID), "UTF-8");
    assertEquals(testXML, GetSealedPdfTest.TEST_XML);

}

From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  w  w  w  . ja  v a 2  s.  c  om
        if (ServletFileUpload.isMultipartContent(req)) {
            file = screenshotService.takeScreenshot(getUploadedFiles(req));
        } else {
            File html = File.createTempFile("htmlScreenshot", ".html");
            if (req.getParameter("html") != null) {
                IOUtils.write(req.getParameter("html").getBytes(), new FileOutputStream(html));
            } else {
                IOUtils.copy(req.getInputStream(), new FileOutputStream(html));
            }
            System.out.println(html.getAbsolutePath());
            // TO Do After the copy the of the files
            browserWidth = (readBrowserParam(req, "browserWidth") != "")
                    ? Integer.parseInt(req.getParameter("browserWidth"))
                    : HtmlScreenshotService.DEFAULT_WIDTH;
            browserHeight = (readBrowserParam(req, "browserHeight") != "")
                    ? Integer.parseInt(req.getParameter("browserHeight"))
                    : HtmlScreenshotService.DEFAULT_HEIGHT;
            useFireFox = (readBrowserParam(req, "useFireFox") != "")
                    ? Boolean.parseBoolean(req.getParameter("useFireFox"))
                    : false;

            file = screenshotService.takeScreenshot(html, browserWidth, browserHeight, useFireFox);
            if (transformScreenshot(req)) {
                imageTransformer.transform(file, resp.getOutputStream(), readParam(req, "format"),
                        readParam(req, "size"), readParam(req, "crop"), readParam(req, "priority"),
                        readParam(req, "params1"), readParam(req, "params2"));
            } else
                IOUtils.copy(new FileInputStream(file), resp.getOutputStream());
        }
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace();
    }
}

From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java

@Test
public void collect_logs_when_one_container_is_running_and_does_not_terminate()
        throws IOException, InterruptedException {
    when(compose.ps()).thenReturn(TestContainerNames.of("db"));
    CountDownLatch latch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("log", outputStream);
        try {//from  w  w  w  .  j a va2 s .c o  m
            latch.await(1, TimeUnit.SECONDS);
            fail("Latch was not triggered");
        } catch (InterruptedException e) {
            // Success
            return true;
        }
        fail("Latch was not triggered");
        return false;
    });
    logCollector.startCollecting(compose);
    logCollector.stopCollecting();
    assertThat(logDirectory.listFiles(), arrayContaining(fileWithName("db.log")));
    assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log")));
    latch.countDown();
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private void setDoOutput(String method, String requestBody, URLConnection urlConnection) throws IOException {
    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        urlConnection.setDoOutput(true);
        if (!StringUtils.isEmpty(requestBody)) {
            IOUtils.write(requestBody, urlConnection.getOutputStream());
        }/*from  w w  w.j av a2 s .c  o m*/
    } else {
        urlConnection.setDoOutput(false);
    }
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>//from   w w w . ja va  2s. c o m
 * In the given W3C DOM represented XML document find all maths nodes (see
 * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and
 * substitute them for series of formulae with leaf elements substituted
 * gradually for a special unification representing symbol {@code &#x25CD;}
 * (for Presentation MathML, see {@link Constants#PMATHML_UNIFICATOR}) or
 * {@code &#x25D0;} (for Content MathML, see
 * {@link Constants#CMATHML_UNIFICATOR}).
 * </p>
 * <p>
 * Resulting series of the original and unified MathML nodes is itself
 * encapsulated in a new element &lt;unified-math&gt; (see
 * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace
 * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see
 * {@link Constants#UNIFIED_MATHML_NS}).
 * </p>
 * <p>
 * Untouched input will be returned and error logged in case of any error
 * during the processing.
 * </p>
 *
 * @param is Input stream with UTF-8 encoded string representation of the
 * XML document to work on.
 * @param os Output stream to write UTF-8 encoded string representation of
 * the processed XML document.
 * @param operatorUnification If <code>true</code> unify also operator
 * nodes, otherwise keep operator nodes intact.
 * @throws java.io.IOException If any I/O error occurs while reading the
 * input stream.
 * @see DocumentParser#findMathMLNodes(org.w3c.dom.Document)
 */
public static void unifyMathML(InputStream is, OutputStream os, boolean operatorUnification)
        throws IOException {

    String originalDoc = IOUtils.toString(is);

    try {
        Document doc = DOMBuilder.buildDoc(new ByteArrayInputStream(originalDoc.getBytes()));
        unifyMathML(doc, operatorUnification);
        XMLOut.xmlSerializer(doc, os);
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        Logger.getLogger(MathMLUnificator.class.getName()).log(Level.SEVERE,
                "MathML Unification from string failed, input string not modified.", ex);
        IOUtils.write(originalDoc, os);
    }

}

From source file:ch.cyberduck.core.irods.IRODSUploadFeatureTest.java

@Test
public void testWrite() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(
            new HashSet<>(Collections.singleton(new IRODSProtocol())));
    final Profile profile = new ProfilePlistReader(factory)
            .read(new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
    final Host host = new Host(profile, profile.getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("irods.key"),
                    System.getProperties().getProperty("irods.secret")));

    final IRODSSession session = new IRODSSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final int length = 32770;
    final byte[] content = RandomUtils.nextBytes(length);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();//from  ww  w . ja va 2 s .c  o  m
    final Checksum checksum;
    final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final TransferStatus status = new TransferStatus().length(content.length);
    checksum = new IRODSUploadFeature(session).upload(test, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status,
            new DisabledConnectionCallback());
    assertTrue(status.isComplete());
    assertEquals(content.length, status.getOffset());
    assertEquals(checksum, new MD5ChecksumCompute().compute(new FileInputStream(local.getAbsolute()), status));
    final byte[] buffer = new byte[content.length];
    final InputStream in = new IRODSReadFeature(session).read(test, new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    IOUtils.readFully(in, buffer);
    in.close();
    assertArrayEquals(content, buffer);
    new IRODSDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.streamsets.pipeline.lib.parser.TestCompressionInputBuilder.java

@SuppressWarnings("unchecked")
private void testArchive(String archiveType) throws Exception {
    //create an archive with multiple files, files containing multiple objects
    File dir = new File("target", UUID.randomUUID().toString());
    dir.mkdirs();//from  ww w. j  a va 2s  . com

    OutputStream archiveOut = new FileOutputStream(new File(dir, "myArchive"));
    ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiveType,
            archiveOut);

    File inputFile;
    ArchiveEntry archiveEntry;
    FileOutputStream fileOutputStream;
    for (int i = 0; i < 5; i++) {
        String fileName = "file-" + i + ".txt";
        inputFile = new File(dir, fileName);
        fileOutputStream = new FileOutputStream(inputFile);
        IOUtils.write(("StreamSets" + i).getBytes(), fileOutputStream);
        fileOutputStream.close();
        archiveEntry = archiveOutputStream.createArchiveEntry(inputFile, fileName);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        IOUtils.copy(new FileInputStream(inputFile), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();
    }
    archiveOutputStream.finish();
    archiveOut.close();

    //create compression input
    FileInputStream fileInputStream = new FileInputStream(new File(dir, "myArchive"));
    CompressionDataParser.CompressionInputBuilder compressionInputBuilder = new CompressionDataParser.CompressionInputBuilder(
            Compression.ARCHIVE, "*.txt", fileInputStream, "0");
    CompressionDataParser.CompressionInput input = compressionInputBuilder.build();

    // before reading
    Assert.assertNotNull(input);

    // The default wrapped offset before reading any file
    String wrappedOffset = "{\"fileName\": \"myfile\", \"fileOffset\":\"0\"}";

    Map<String, Object> archiveInputOffset = OBJECT_MAPPER.readValue(wrappedOffset, Map.class);
    Assert.assertNotNull(archiveInputOffset);
    Assert.assertEquals("myfile", archiveInputOffset.get("fileName"));
    Assert.assertEquals("0", archiveInputOffset.get("fileOffset"));

    Assert.assertEquals("0", input.getStreamPosition(wrappedOffset));

    // read and check wrapped offset
    BufferedReader reader = new BufferedReader(new InputStreamReader(input.getNextInputStream()));
    Assert.assertEquals("StreamSets0", reader.readLine());
    wrappedOffset = input.wrapOffset("4567");
    archiveInputOffset = OBJECT_MAPPER.readValue(wrappedOffset, Map.class);
    Assert.assertNotNull(archiveInputOffset);
    Assert.assertEquals("file-0.txt", archiveInputOffset.get("fileName"));
    Assert.assertEquals("4567", archiveInputOffset.get("fileOffset"));

    String recordIdPattern = "myFile/file-0.txt";
    Assert.assertEquals(recordIdPattern, input.wrapRecordId("myFile"));

}

From source file:edu.cmu.cs.diamond.android.Filter.java

private void sendBinary(byte[] b) throws IOException {
    if (b == null) {
        IOUtils.write("0", os);
    } else {//from  w w  w.j ava  2  s . co  m
        Log.d(TAG, "SendingBinary: " + getHash(b));
        IOUtils.write(Integer.toString(b.length), os);
    }
    sendBlank();
    if (b != null) {
        os.write(b);
    }
    sendBlank();
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public boolean deleteRoom(String room_id) {
    String query = String.format(HipChatConstants.ROOMS_DELETE_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);//  w w w.  ja v a 2  s. c  o m
    StringBuilder params = new StringBuilder();

    if (room_id == null || room_id.length() == 0) {
        throw new IllegalArgumentException("Cannot delete room with null or empty id");
    } else {
        params.append("room_id=");
        params.append(room_id);
    }

    final String paramsToSend = params.toString();

    OutputStream output = null;
    InputStream input = null;

    HttpURLConnection connection = null;
    boolean result = false;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_DELETE + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoOutput(true);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        output = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(paramsToSend, output);
        IOUtils.closeQuietly(output);

        input = connection.getInputStream();
        result = UtilParser.parseDeleteResult(input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return result;
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

/**
 * These signatures are invalid because of non ordered  signed attributes
 *///from w w  w  .  ja  va  2  s  .  c  om
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}