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:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java

@Test
/**/*from  www .  j  a v  a 2 s.  c  o m*/
 * Assert passing an AttachmentStreamFactory with no key reads an unencrypted and
 * gzipped file correctly.
 */
public void testSavedAttachmentReadsUnencryptedEncodedStream() throws AttachmentException, IOException {

    AttachmentStreamFactory asf = new AttachmentStreamFactory(new NullKeyProvider());

    File plainText = f("fixture/EncryptedAttachmentTest_plainText");
    File zippedPlainText = f("fixture/EncryptedAttachmentTest_plainText.gz");

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

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

}

From source file:com.google.mr4c.sources.SourceTestUtils.java

public static void compareFiles(DataFileSource expectedFile, DataFileSource actualFile) throws IOException {

    String msg = String.format("binary content doesn't match: expected file is %s; actual file is %s",
            expectedFile.getDescription(), actualFile.getDescription());

    InputStream expectedInput = null;
    InputStream actualInput = null;

    try {//from   ww  w . ja  va2 s. com
        expectedInput = expectedFile.getFileInputStream();
        actualInput = actualFile.getFileInputStream();
        assertTrue(msg, IOUtils.contentEquals(expectedInput, actualInput));
    } finally {
        IOUtils.closeQuietly(actualInput);
        IOUtils.closeQuietly(expectedInput);
    }

}

From source file:net.ontopia.topicmaps.core.VariantNameTest.java

public void testReader() throws Exception {
    // read file and store in object
    File filein = TestFileUtils.getTransferredTestInputFile("various", "clob.xml");
    File fileout = TestFileUtils.getTestOutputFile("various", "clob.xml.out");

    Reader ri = new FileReader(filein);
    long inlen = filein.length();
    variant.setReader(ri, inlen, DataTypes.TYPE_BINARY);

    assertTrue("Variant datatype is incorrect", Objects.equals(DataTypes.TYPE_BINARY, variant.getDataType()));

    // read and decode content
    Reader ro = variant.getReader();
    try {/*from  w  w w .  j  a  v  a 2 s .  c  o  m*/
        Writer wo = new FileWriter(fileout);
        try {
            IOUtils.copy(ro, wo);
        } finally {
            wo.close();
        }
    } finally {
        ro.close();
    }
    assertTrue("Reader value is null", ro != null);
    try {
        ri = new FileReader(filein);
        ro = new FileReader(fileout);
        long outlen = variant.getLength();
        try {
            assertTrue("Variant value put in is not the same as the one we get out.",
                    IOUtils.contentEquals(ro, ri));
            assertTrue("Variant value length is different", inlen == outlen);
        } finally {
            ri.close();
        }
    } finally {
        ro.close();
    }
}

From source file:de.hska.ld.content.controller.DocumentControllerIntegrationTest.java

@Test
public void testFileDownload() throws Exception {

    //Add document
    HttpResponse responseCreateDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Document respondedDocument = ResponseHelper.getBody(responseCreateDocument, Document.class);
    Assert.assertNotNull(respondedDocument);

    //load file/* w w  w.  j  a  va 2s  .  c o m*/
    String fileName = "sandbox.pdf";
    InputStream in = null;
    byte[] source = null;
    try {
        in = UserSession.class.getResourceAsStream("/" + fileName);
        source = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    ByteArrayBody fileBody = new ByteArrayBody(source, fileName);

    //Add document
    System.out.println(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId());
    HttpResponse responseUploadAttachment = UserSession.user()
            .postFile(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId(), fileBody);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseUploadAttachment));
    Long attachmentId = ResponseHelper.getBody(responseUploadAttachment, Long.class);
    Assert.assertNotNull(attachmentId);

    String uri = RESOURCE_DOCUMENT + "/" + respondedDocument.getId() + "/download/" + attachmentId;
    HttpResponse response = UserSession.user().get(uri);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(response));

    HttpEntity entity = response.getEntity();
    System.out.println(entity.getContentType());
    InputStream inStream = entity.getContent();
    InputStream inStreamExistingFile = new FileInputStream("./src/test/resources/sandbox.pdf");
    Assert.assertNotNull(inStream);
    Assert.assertNotNull(inStreamExistingFile);
    Assert.assertTrue(IOUtils.contentEquals(inStream, inStreamExistingFile));
}

From source file:net.ontopia.topicmaps.core.OccurrenceTest.java

public void testReader() throws Exception {
    // read file and store in object
    File filein = TestFileUtils.getTransferredTestInputFile("various", "clob.xml");
    File fileout = TestFileUtils.getTestOutputFile("various", "clob.xml.out");

    long inlen = filein.length();
    Reader ri = new FileReader(filein);
    try {/*from  w w w .j ava2 s  . co  m*/
        occurrence.setReader(ri, inlen, DataTypes.TYPE_BINARY);
    } finally {
        try {
            ri.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ;
    }
    assertTrue("Occurrence datatype is incorrect",
            Objects.equals(DataTypes.TYPE_BINARY, occurrence.getDataType()));

    // read and decode content
    Reader ro = occurrence.getReader();
    try {
        Writer wo = new FileWriter(fileout);
        try {
            IOUtils.copy(ro, wo);
        } finally {
            wo.close();
        }
    } finally {
        ro.close();
    }
    assertTrue("Reader value is null", ro != null);
    try {
        ri = new FileReader(filein);
        ro = new FileReader(fileout);
        long outlen = occurrence.getLength();
        try {
            assertTrue("Occurrence value put in is not the same as the one we get out.",
                    IOUtils.contentEquals(ro, ri));
            assertTrue("Occurrence value length is different", inlen == outlen);
        } finally {
            ri.close();
        }
    } finally {
        ro.close();
    }
}

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

@Test
public void testClasspathCacheControl() 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();

    get = new HttpGet("http://localhost:" + port + "/classpath/test.css");
    get.addHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    get.addHeader(HttpHeaders.IF_MODIFIED_SINCE, modified);
    response = client.execute(get);//from   ww w.j  av  a2 s .co  m

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

}

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

@Test
public void imageStreamShouldBeEqualsToResourceStreamFromClassPath() throws IOException {
    mockRequestParameterToReturnTestImageName(IMAGE_NAME_FROM_CLASSPATH);

    final AbstractNode imageNode = imageRequestConsumer.process(mockAccount, mockRequest);
    assertThat(imageNode, hasProperty("downloadedObjectData", instanceOf(InputStream.class)));
    Assert.assertTrue(IOUtils.contentEquals(imageNode.getDownloadedObjectData(),
            ImageRequestCommand.class.getClassLoader().getResource(IMAGE_NAME_FROM_CLASSPATH).openStream()));
}

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

@Test
/**// w  ww  . java 2  s.c o m
 * Assert passing an AttachmentStreamFactory with known key writes an encrypted file to disk.
 */
public void testPreparedAttachmentWritesEncryptedUnencodedStream()
        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);

    // We check content using EncryptedAttachmentInputStream. It seems a bit circular,
    // but the aim of this test is to make sure AttachmentStreamFactory is providing
    // encrypted output readable by EncryptedAttachmentInputStream rather than exactly
    // what that output is (EncryptedAttachmentOutputStream's own tests do that).
    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)));

}

From source file:fr.ortolang.diffusion.usecase.StoreAndRetrieveFileUseCase.java

@Test
public void testHostSimpleFile() throws URISyntaxException {
    // Path origin = Paths.get(HostAndRetrieveFileTest.class.getClassLoader().getResource("file1.jpg").getPath());
    Path origin = Paths.get("/home/jerome/Images/test.jpg");
    LOGGER.log(Level.INFO, "Origin file to insert in container : " + origin.toString());

    Path destination = Paths.get("/tmp/" + System.currentTimeMillis());
    LOGGER.log(Level.INFO,/*from w  ww. java 2 s  . com*/
            "Destination file for retrieving content from container : " + destination.toString());

    String wkey = UUID.randomUUID().toString();
    String okey = UUID.randomUUID().toString();

    // Create a Workspace
    try {
        core.createWorkspace(wkey, "Test Workspace", "test");
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Create the Digital Object
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Files.copy(origin, baos);
        //core.createDataObject(wkey, "/" + okey, "Test Object", "A really simple test object !!", baos.toByteArray());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Check that the object is registered in the browser
    try {
        OrtolangObjectIdentifier identifier = browser.lookup(okey);
        assertEquals(identifier.getService(), CoreService.SERVICE_NAME);
        assertEquals(identifier.getType(), DataObject.OBJECT_TYPE);
    } catch (BrowserServiceException | KeyNotFoundException | AccessDeniedException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Retrieve this digital object informations using the key
    try {
        DataObject object = core.readDataObject(okey);
        LOGGER.log(Level.INFO, "Detected mime type : " + object.getMimeType());
        LOGGER.log(Level.INFO, "Detected size : " + object.getSize());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Retrieve this digital object data using the key
    try {
        //byte[] data = core.readDataObjectContent(okey);
        //Files.copy(new ByteArrayInputStream(data), destination);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Compare origin and destination :
    try {
        InputStream input1 = Files.newInputStream(origin);
        InputStream input2 = Files.newInputStream(destination);
        assertTrue(IOUtils.contentEquals(input1, input2));
        input1.close();
        input2.close();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Delete destination
    try {
        Files.delete(destination);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:eu.planets_project.services.datatypes.ImmutableContent.java

/**
 * {@inheritDoc}//from w  w  w.  j  a  v  a 2 s.  co  m
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(final Object obj) {
    if (!(obj instanceof ImmutableContent)) {
        return false;
    }
    ImmutableContent that = (ImmutableContent) obj;
    /*
     * Two content objects, even if they would be based on the same data, are not equal if they are not both by
     * reference or both by value:
     */
    if (this.isByValue() != that.isByValue()) {
        return false;
    }
    /* Else we compare either value or reference: */
    try {
        if (this.dataHandler != null && that.dataHandler != null) {
            return IOUtils.contentEquals(dataHandler.getInputStream(), that.dataHandler.getInputStream());
        } else if (this.bytes != null && that.bytes != null) {
            return IOUtils.contentEquals(new ByteArrayInputStream(this.bytes),
                    new ByteArrayInputStream(that.bytes));
        } else if (this.reference != null && that.reference != null) {
            return this.reference.toString().equals(that.reference.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}