Example usage for org.apache.commons.io IOUtils contentEquals

List of usage examples for org.apache.commons.io IOUtils contentEquals

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils contentEquals.

Prototype

public static boolean contentEquals(Reader input1, Reader input2) throws IOException 

Source Link

Document

Compare the contents of two Readers to determine if they are equal or not.

Usage

From source file:alluxio.cli.fs.command.CpCommandIntegrationTest.java

private boolean equals(AlluxioURI file1, AlluxioURI file2) throws Exception {
    try (Closer closer = Closer.create()) {
        OpenFileOptions openFileOptions = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
        FileInStream is1 = closer.register(mFileSystem.openFile(file1, openFileOptions));
        FileInStream is2 = closer.register(mFileSystem.openFile(file2, openFileOptions));
        return IOUtils.contentEquals(is1, is2);
    }//from   www .java 2  s .  co m
}

From source file:mobi.jenkinsci.server.core.services.ImageRequestCommandTest.java

@Test
public void imageStreamShouldBeEqualsToResourceStreamFromFilesystem() throws IOException {
    mockRequestParameterToReturnTestImageName(IMAGE_NAME_FROM_FILESYSTEM);
    final File imageFromFilesystem = createImageFile();
    mockConfigToReturnFileFromFilesystem(IMAGE_NAME_FROM_FILESYSTEM, imageFromFilesystem);

    final AbstractNode imageNode = imageRequestConsumer.process(mockAccount, mockRequest);
    assertThat(imageNode, hasProperty("downloadedObjectData", instanceOf(InputStream.class)));
    Assert.assertTrue(IOUtils.contentEquals(imageNode.getDownloadedObjectData(),
            new FileInputStream(imageFromFilesystem)));
}

From source file:com.barchart.netty.server.http.handlers.TestStaticResourceHandler.java

@Test
public void testClasspathCacheExpired() throws Exception {

    HttpGet get = new HttpGet("http://localhost:" + port + "/classpath/test.css");
    HttpResponse response = client.execute(get);

    final String modified = response.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue();
    final long modtime = DateUtils.parseDate(modified).getTime();

    get = new HttpGet("http://localhost:" + port + "/classpath/test.css");
    get.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(new Date(modtime - 1000)));
    response = client.execute(get);//w w w.j  a v  a2s.c om

    assertEquals(200, response.getStatusLine().getStatusCode());
    assertTrue(IOUtils.contentEquals(getClass().getResourceAsStream("/files/test.css"),
            response.getEntity().getContent()));

}

From source file:com.cloudant.sync.datastore.encryption.EndToEndEncryptionTest.java

@Test
public void attachmentsDataEncrypted() throws IOException, DocumentException, InvalidKeyException {

    DocumentRevision rev = new DocumentRevision();
    rev.setBody(DocumentBodyFactory.create(new HashMap<String, String>()));

    File expectedPlainText = TestUtils.loadFixture("fixture/EncryptedAttachmentTest_plainText");
    assertNotNull(expectedPlainText);//from w ww  .  j  a  va 2s . c  o m

    UnsavedFileAttachment attachment = new UnsavedFileAttachment(expectedPlainText, "text/plain");
    rev.getAttachments().put("EncryptedAttachmentTest_plainText", attachment);

    datastore.createDocumentFromRevision(rev);

    File attachmentsFolder = new File(datastoreManagerDir + File.separator + "EndToEndEncryptionTest"
            + File.separator + "extensions" + File.separator + "com.cloudant.attachments");

    File[] contents = attachmentsFolder.listFiles();
    assertNotNull("Didn't find expected attachments folder", contents);
    assertThat("Didn't find expected file in attachments", contents.length, IsEqual.equalTo(1));
    InputStream in = new FileInputStream(contents[0]);

    if (dataShouldBeEncrypted) {

        byte[] actualContent = new byte[expectedFirstAttachmentByte.length];
        int readLength = in.read(actualContent);
        assertEquals("Didn't read full buffer", actualContent.length, readLength);
        assertArrayEquals("First byte not version byte", expectedFirstAttachmentByte, actualContent);

        assertTrue("Encrypted attachment did not decrypt correctly",
                IOUtils.contentEquals(new EncryptedAttachmentInputStream(new FileInputStream(contents[0]), KEY),
                        new FileInputStream(expectedPlainText)));

    } else {
        assertTrue("Unencrypted attachment did not read correctly",
                IOUtils.contentEquals(new FileInputStream(expectedPlainText), in));
    }
}

From source file:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java

@Test
/**//from ww  w  . ja va  2  s  .c om
 * Assert passing an AttachmentStreamFactory with known key reads an encrypted file correctly.
 */
public void testSavedAttachmentReadsEncryptedUnencodedStream() throws AttachmentException, IOException {

    AttachmentStreamFactory asf = new AttachmentStreamFactory(EncryptionTestConstants.keyProvider16Byte);

    File plainText = f("fixture/EncryptedAttachmentTest_plainText");
    File cipherAttachmentBlob = f("fixture/EncryptedAttachmentTest_cipherText_aes128");

    SavedAttachment savedAttachment = new SavedAttachment(0, "test", null, "text/plain",
            Attachment.Encoding.Plain, 0, 0, 0, cipherAttachmentBlob, asf);

    Assert.assertTrue("Reading encrypted, un-encoded stream didn't give correct output",
            IOUtils.contentEquals(savedAttachment.getInputStream(), new FileInputStream(plainText)));

}

From source file:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java

@Test
/**//w  ww . j a  v a  2s.  c om
 * Assert passing an AttachmentStreamFactory with known key to both a PreparedAttachment
 * (writer) and SavedAttachment (reader) round trips the data correctly.
 */
public void testSavedAttachmentReadsPreparedAttachmentEncryptedUnencodedStream()
        throws AttachmentException, IOException, InvalidKeyException {

    AttachmentStreamFactory asf = new AttachmentStreamFactory(EncryptionTestConstants.keyProvider16Byte);

    File plainText = f("fixture/EncryptedAttachmentTest_plainText");

    UnsavedFileAttachment usf = new UnsavedFileAttachment(plainText, "text/plain");
    PreparedAttachment preparedAttachment = new PreparedAttachment(usf, datastore_manager_dir, 0, asf);

    Assert.assertTrue("Writing to encrypted stream didn't give correct output",
            IOUtils.contentEquals(
                    new EncryptedAttachmentInputStream(new FileInputStream(preparedAttachment.tempFile),
                            EncryptionTestConstants.key16Byte),
                    new FileInputStream(plainText)));

    SavedAttachment savedAttachment = new SavedAttachment(0, "test", null, "text/plain",
            Attachment.Encoding.Plain, 0, 0, 0, preparedAttachment.tempFile, asf);

    Assert.assertTrue("Reading from written encrypted, un-encoded blob didn't give correct output",
            IOUtils.contentEquals(savedAttachment.getInputStream(), new FileInputStream(plainText)));

}

From source file:net.ontopia.utils.TestFileUtils.java

/**
  * INTERNAL: Compares the contents of a file and a resource that will be loaded from classpath
  *///from   w ww . ja v  a2 s.  c om
public static boolean compareFileToResource(String fileName, String resourceName) throws IOException {
    try (FileInputStream in1 = new FileInputStream(fileName);
            InputStream in2 = StreamUtils.getInputStream(resourceName)) {
        return IOUtils.contentEquals(in1, in2);
    }
}

From source file:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java

@Test
/**//from   w  ww  .  j  a  va2  s .  co m
 * Assert that using a different key to write using a PreparedAttachment than the one used to
 * read using a SavedAttachment doesn't give us the original plaintext. That is, make sure
 * using the wrong key does what you'd expect: fails to decrypt the attachment.
 *
 * Note the decryption process will still work as AES doesn't check the plaintext decrypted
 * is correct or not, you just get garbage data out.
 */
public void testSavedAttachmentCannotReadPreparedAttachmentEncryptedUsingDifferentKey()
        throws AttachmentException, IOException, InvalidKeyException {

    //
    // Encrypt attachment blob using well known key
    //

    AttachmentStreamFactory asf = new AttachmentStreamFactory(EncryptionTestConstants.keyProvider16Byte);

    File plainText = f("fixture/EncryptedAttachmentTest_plainText");

    UnsavedFileAttachment usf = new UnsavedFileAttachment(plainText, "text/plain");
    PreparedAttachment preparedAttachment = new PreparedAttachment(usf, datastore_manager_dir, 0, asf);

    Assert.assertTrue("Writing to encrypted, un-encoded stream didn't give correct output",
            IOUtils.contentEquals(
                    new EncryptedAttachmentInputStream(new FileInputStream(preparedAttachment.tempFile),
                            EncryptionTestConstants.key16Byte),
                    new FileInputStream(plainText)));

    //
    // Attempt to read using a different key
    //

    byte[] otherKey = Arrays.copyOf(EncryptionTestConstants.key16Byte, 16);
    otherKey[12] = (byte) (otherKey[12] - 1);
    AttachmentStreamFactory asf2 = new AttachmentStreamFactory(
            EncryptionTestConstants.keyProviderUsingBytesAsKey(otherKey));
    SavedAttachment savedAttachment = new SavedAttachment(0, "test", null, "text/plain",
            Attachment.Encoding.Plain, 0, 0, 0, preparedAttachment.tempFile, asf2);

    Assert.assertFalse("Reading with different key shouldn't produce plaintext content",
            IOUtils.contentEquals(savedAttachment.getInputStream(), new FileInputStream(plainText)));

}

From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public String put(InputStream content) throws BinaryStoreServiceException, DataCollisionException {
    try {/*from   ww w . j  a  va2s  .c  o m*/
        HashedFilterInputStream input = factory.getHashedFilterInputStream(content);
        try {
            Path tmpfile = Paths.get(working.toString(), Long.toString(System.nanoTime()));

            Files.copy(input, tmpfile);
            LOGGER.log(Level.FINE, "content stored in local temporary file: " + tmpfile.toString());
            String hash = input.getHash();
            LOGGER.log(Level.FINE, "content based generated sha1 hash: " + hash);

            String digit = hash.substring(0, DISTINGUISH_SIZE);
            Path volume = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit));
            Path parent = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit);
            Path file = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit, hash);
            if (!Files.exists(volume)) {
                Files.createDirectory(volume);
            }
            if (!Files.exists(parent)) {
                Files.createDirectory(parent);
            }
            if (!Files.exists(file)) {
                Files.move(tmpfile, file);
                LOGGER.log(Level.FINE, "content moved in local definitive file: " + file.toString());
            } else {
                LOGGER.log(Level.FINE, "a file with same hash already exists, trying to detect collision");
                try (InputStream input1 = Files.newInputStream(file);
                        InputStream input2 = Files.newInputStream(tmpfile)) {
                    if (IOUtils.contentEquals(input1, input2)) {
                        Files.delete(tmpfile);
                    } else {
                        LOGGER.log(Level.SEVERE,
                                "BINARY COLLISION DETECTED - storing colliding files in dedicated folder");
                        Files.copy(file, Paths.get(collide.toString(), hash + ".origin"));
                        Files.move(tmpfile, Paths.get(collide.toString(), hash + ".colliding"));
                        throw new DataCollisionException();
                    }
                }
            }
            return hash;
        } catch (IOException | VolumeNotFoundException e) {
            throw new BinaryStoreServiceException(e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new BinaryStoreServiceException(e);
    }
}

From source file:net.ontopia.utils.TestFileUtils.java

/**
  * INTERNAL: Compares the contents of a file and a resource that will be loaded from classpath
  *///from w ww  .  ja v  a2s . c  o  m
public static boolean compareFileToResource(File file, String resourceName) throws IOException {
    try (FileInputStream in1 = new FileInputStream(file);
            InputStream in2 = StreamUtils.getInputStream(resourceName)) {
        return IOUtils.contentEquals(in1, in2);
    }
}