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:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void putGetFileExample() throws Exception {
    HttpsURLConnection connection;
    String redirect;//w  ww .  j av a  2 s  .  c  o m
    InputStream input;
    OutputStream output;

    String data = UUID.randomUUID().toString();

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=CREATE");
    connection.setRequestMethod("PUT");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    output = connection.getOutputStream();
    IOUtils.write(data.getBytes(), output);
    output.close();
    connection.disconnect();
    assertThat(connection.getResponseCode(), is(201));

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=OPEN");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    input = connection.getInputStream();
    assertThat(IOUtils.toString(input), is(data));
    input.close();
    connection.disconnect();

}

From source file:jodtemplate.pptx.ImageService.java

private Image getImage(final byte[] imageContents, final Presentation presentation, final Resources resources)
        throws IOException {
    final Image image;
    final String md5 = DigestUtils.md5Hex(imageContents);
    if (presentation.containsImage(md5)) {
        image = presentation.getImage(md5);
    } else {/*from   www .j av  a2 s. co m*/
        image = new Image();
        image.setMd5(md5);

        final ImageMetadataExtractor simpleImageInfo = new ImageMetadataExtractor(imageContents);
        image.setWidth(simpleImageInfo.getWidth());
        image.setHeight(simpleImageInfo.getHeight());
        image.setExtension(simpleImageInfo.getMimeType());

        final int imageIndex = presentation.getNumberOfImages() + 1;
        image.setFullPath(
                presentation.getFullPath() + "media/imageJodT" + imageIndex + "." + image.getExtension());

        presentation.addImage(image);

        final Resource imageResource = resources
                .createResource(Utils.removePrefixSeparator(image.getFullPath()));

        try (final OutputStream resOutput = imageResource.getOutputStream()) {
            IOUtils.write(imageContents, resOutput);
        }
    }
    return image;
}

From source file:eu.europa.ejusticeportal.dss.controller.action.ValidateSignedPdfTest.java

/**
 * Initialises the trusted list store and creates the sealed PDF for the other tests.
 *
 * @throws Exception//  ww w  .  j  ava  2s  .c o  m
 */
@BeforeClass
public static void createSealedPDF() throws Exception {
    System.setProperty(SealedPDFService.PASSWORD_FILE_PROPERTY, "classpath:server.pwd");
    System.setProperty(SealedPDFService.CERTIFICATE_FILE_PROPERTY, "classpath:server.p12");
    portal = new PortalFacadeTestImpl(TEST_XML, "dss/hello-world.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.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.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:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*from w  w w .  j  av  a2  s.co  m*/
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:de.sandroboehme.lesscss.mojo.NodeJsLessCompiler.java

private String compile(String input) throws LessException, IOException, InterruptedException {
    long start = System.currentTimeMillis();

    File inputFile = File.createTempFile("lessc-input-", ".less");
    FileOutputStream out = new FileOutputStream(inputFile);
    IOUtils.write(input, out);
    out.close();/*from  w w w. j  a  va  2s . c  o  m*/
    File outputFile = File.createTempFile("lessc-output-", ".css");
    File lesscJsFile = new File(tempDir, "lessc.js");

    ProcessBuilder pb = new ProcessBuilder(nodeExecutablePath, lesscJsFile.getAbsolutePath(),
            inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress));
    pb.redirectErrorStream(true);
    Process process = pb.start();
    IOUtils.copy(process.getInputStream(), System.out);

    int exitStatus = process.waitFor();

    FileInputStream in = new FileInputStream(outputFile);
    String result = IOUtils.toString(in);
    in.close();
    if (!inputFile.delete()) {
        log.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        log.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

    log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms.");

    return result;
}

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

private void sendString(String s) throws IOException {
    IOUtils.write(Integer.toString(s.length()), os);
    sendBlank();/*from ww  w .  j  ava2  s .  c o m*/
    IOUtils.write(s, os);
    sendBlank();
    os.flush();
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypterDecrypterTest.java

@Test
public void testFileEncryptOutputStreamDecrypt() throws Exception {
    InputStream testFileInStream = this.getClass().getResourceAsStream("/testFile.txt");
    final ByteArrayOutputStream testFileBuffer = new ByteArrayOutputStream();
    IOUtils.copy(testFileInStream, testFileBuffer);
    final byte[] testFileBytes = testFileBuffer.toByteArray();

    final ByteArrayOutputStream encTestFileOutStream = new ByteArrayOutputStream();
    final OutputStream encryptingOutputStream = this.fileEncrypter.encrypt("testFile.txt", testFileBytes.length,
            encTestFileOutStream);/*  w w  w. j  a va  2s .co  m*/
    IOUtils.write(testFileBytes, encryptingOutputStream);
    encryptingOutputStream.close();

    final ByteArrayOutputStream decTestFileOutStream = new ByteArrayOutputStream();
    this.fileDecrypter.decrypt(new ByteArrayInputStream(encTestFileOutStream.toByteArray()),
            decTestFileOutStream);

    testFileInStream = this.getClass().getResourceAsStream("/testFile.txt");
    final String expected = IOUtils.toString(testFileInStream);
    final String actual = IOUtils.toString(new ByteArrayInputStream(decTestFileOutStream.toByteArray()));

    assertEquals(expected, actual);
}

From source file:ch.cyberduck.core.dav.DAVUploadFeatureTest.java

@Test
public void testAppend() throws Exception {
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final DAVSession session = new DAVSession(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();/*  www  . j  av  a  2s . com*/
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    {
        final TransferStatus status = new TransferStatus().length(content.length / 2);
        new DAVUploadFeature(new DAVWriteFeature(session)).upload(test, local,
                new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status,
                new DisabledConnectionCallback());
    }
    {
        final TransferStatus status = new TransferStatus().length(content.length / 2).skip(content.length / 2)
                .append(true);
        new DAVUploadFeature(new DAVWriteFeature(session)).upload(test, local,
                new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status,
                new DisabledConnectionCallback());
    }
    final byte[] buffer = new byte[content.length];
    final InputStream in = new DAVReadFeature(session).read(test, new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    IOUtils.readFully(in, buffer);
    in.close();
    assertArrayEquals(content, buffer);
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:com.redoute.datamap.servlet.picture.FindPicture.java

private void processApplicationPagePicture(final String application, final String page, final String picture)
        throws IOException {
    @SuppressWarnings("serial")
    String individualSearch = IndividualSearchUtil.constructIndividualSearch(new HashMap<String, String>() {
        {//from   w ww .  java2 s.  c  o m
            put(ParameterKey.Application.name(), application);
            put(ParameterKey.Page.name(), page);
            put(ParameterKey.Picture.name(), picture);
        }
    });
    List<Picture> pictures = pictureService.findPictureListByCriteria(individualSearch, "");
    if (pictures == null || pictures.isEmpty()) {
        return;
    }

    // In case of multiple pictures, takes the first one by default
    Picture pic = pictures.get(0);
    try {
        response.setContentType(String.format("image/%s", HTML5CanvasURLUtil.parseImageType(pic.getBase64())));
        IOUtils.write(HTML5CanvasURLUtil.decodeBase64Data(HTML5CanvasURLUtil.parseBase64Data(pic.getBase64())),
                response.getOutputStream());
    } catch (HTML5CanvasURLParsingException e) {
        throw new IOException(e);
    }
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />/*  ww  w. jav  a  2s.c  o m*/
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(final URL url, final String post, final String contentType,
        final String auth) throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}