List of usage examples for org.apache.commons.io IOUtils contentEquals
public static boolean contentEquals(Reader input1, Reader input2) throws IOException
From source file:com.cloudant.sync.datastore.encryption.EndToEndEncryptionTest.java
/** * A basic check things round trip successfully. *///from w w w .j ava2 s . c o m @Test public void readAndWriteDocument() throws DocumentException, IOException { String documentId = "a-test-document"; final String nonAsciiText = ";:xx\uD83D\uDC79?\uD83D\uDC7D"; HashMap<String, String> documentBody = new HashMap<String, String>(); documentBody.put("name", "mike"); documentBody.put("pet", "cat"); documentBody.put("non-ascii", nonAsciiText); // Create DocumentRevision rev = new DocumentRevision(documentId); rev.setBody(DocumentBodyFactory.create(documentBody)); DocumentRevision saved = datastore.createDocumentFromRevision(rev); assertNotNull(saved); // Read DocumentRevision retrieved = datastore.getDocument(documentId); assertNotNull(retrieved); Map<String, Object> retrievedBody = retrieved.getBody().asMap(); assertEquals("mike", retrievedBody.get("name")); assertEquals("cat", retrievedBody.get("pet")); assertEquals(nonAsciiText, retrievedBody.get("non-ascii")); assertEquals(3, retrievedBody.size()); // Update DocumentRevision update = retrieved; Map<String, Object> updateBody = retrieved.getBody().asMap(); updateBody.put("name", "fred"); update.setBody(DocumentBodyFactory.create(updateBody)); DocumentRevision updated = datastore.updateDocumentFromRevision(update); assertNotNull(updated); Map<String, Object> updatedBody = updated.getBody().asMap(); assertEquals("fred", updatedBody.get("name")); assertEquals("cat", updatedBody.get("pet")); assertEquals(nonAsciiText, updatedBody.get("non-ascii")); assertEquals(3, updatedBody.size()); // Update with attachments, one from file, one a non-ascii string test final String attachmentName = "EncryptedAttachmentTest_plainText"; File expectedPlainText = TestUtils.loadFixture("fixture/EncryptedAttachmentTest_plainText"); assertNotNull(expectedPlainText); DocumentRevision attachmentRevision = updated; final Map<String, Attachment> atts = attachmentRevision.getAttachments(); atts.put(attachmentName, new UnsavedFileAttachment(expectedPlainText, "text/plain")); atts.put("non-ascii", new UnsavedStreamAttachment(new ByteArrayInputStream(nonAsciiText.getBytes()), "non-ascii", "text/plain")); DocumentRevision updatedWithAttachment = datastore.updateDocumentFromRevision(attachmentRevision); InputStream in = updatedWithAttachment.getAttachments().get(attachmentName).getInputStream(); assertTrue("Saved attachment did not read correctly", IOUtils.contentEquals(new FileInputStream(expectedPlainText), in)); in = updatedWithAttachment.getAttachments().get("non-ascii").getInputStream(); assertTrue("Saved attachment did not read correctly", IOUtils.contentEquals(new ByteArrayInputStream(nonAsciiText.getBytes()), in)); // perform a query to ensure we can use special chars IndexManager indexManager = new IndexManager(datastore); assertNotNull(indexManager.ensureIndexed(Arrays.<Object>asList("name", "pet"), "my index")); // query for the name fred and check that docs are returned. Map<String, Object> selector = new HashMap<String, Object>(); selector.put("name", "fred"); QueryResult queryResult = indexManager.find(selector); assertNotNull(queryResult); // Delete try { datastore.deleteDocumentFromRevision(saved); fail("Deleting document from old revision succeeded"); } catch (ConflictException ex) { // Expected exception } DocumentRevision deleted = datastore.deleteDocumentFromRevision(updatedWithAttachment); assertNotNull(deleted); assertEquals(true, deleted.isDeleted()); }
From source file:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java
@Test /**//from www . ja v a 2 s . co m * Assert passing an AttachmentStreamFactory with known key writes an encrypted and * gzipped file to disk. */ public void testPreparedAttachmentWritesEncryptedEncodedStream() throws AttachmentException, IOException, InvalidKeyException { AttachmentStreamFactory asf = new AttachmentStreamFactory(EncryptionTestConstants.keyProvider16Byte); File plainText = f("fixture/EncryptedAttachmentTest_plainText"); File actualOutput = new File(datastore_manager_dir, "temp" + UUID.randomUUID()); OutputStream out = asf.getOutputStream(actualOutput, Attachment.Encoding.Gzip); IOUtils.copy(new FileInputStream(plainText), out); out.close(); // 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, encoded stream didn't give correct output", IOUtils .contentEquals( new GZIPInputStream(new EncryptedAttachmentInputStream( new FileInputStream(actualOutput), EncryptionTestConstants.key16Byte)), new FileInputStream(plainText))); }
From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletTest.java
@Test public void testGIFFileDirectStream() throws Exception { MockSlingHttpServletResponse response = spy(aemContext.response()); MockSlingHttpServletRequest request = prepareRequest(IMAGE5_PATH, "img", "gif"); servlet.doGet(request, response);/*from w w w.j av a 2 s . com*/ ByteArrayInputStream stream = new ByteArrayInputStream(response.getOutput()); InputStream directStream = this.getClass().getClassLoader() .getResourceAsStream("image/Adobe_Systems_logo_and_wordmark.svg.gif"); assertTrue(IOUtils.contentEquals(stream, directStream)); }
From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacro.java
private DownloadResourceInfo attachImage(final ContentEntityObject page, final PlantUmlMacroParams macroParams, ImageInfo imageInfo, final FileFormat fileFormat, final DownloadResourceWriter resourceWriter) throws UnauthorizedDownloadResourceException, DownloadResourceNotFoundException, IOException { final String attachmentName; if (imageInfo.isSplitImage()) { attachmentName = macroParams.getExportName() + "-" + imageInfo.getIndex() + fileFormat.getFileSuffix(); } else {// www . jav a2 s. c o m attachmentName = macroParams.getExportName() + fileFormat.getFileSuffix(); } Attachment attachment = pageManager.getAttachmentManager().getAttachment(page, attachmentName); final Attachment previousVersion; if (attachment == null) { previousVersion = null; attachment = new Attachment(); attachment.setFileName(attachmentName); attachment.setContentType("image/" + fileFormat.name().toLowerCase()); attachment.setComment("PlantUML Diagram (generated)"); } else { try { previousVersion = (Attachment) attachment.clone(); } catch (CloneNotSupportedException e) { throw new InfrastructureException(e); } } final DownloadResourceReader resourceReader = writeableDownloadResourceManager.getResourceReader( AuthenticatedUserThreadLocal.getUsername(), resourceWriter.getResourcePath(), Collections.emptyMap()); if (previousVersion == null || previousVersion.getFileSize() != resourceReader.getContentLength() || !IOUtils.contentEquals(previousVersion.getContentsAsStream(), resourceReader.getStreamForReading())) { attachment.setFileSize(resourceReader.getContentLength()); page.addAttachment(attachment); pageManager.getAttachmentManager().saveAttachment(attachment, previousVersion, resourceReader.getStreamForReading()); logger.debug("Saved image as attachment " + attachmentName); } return new AttachmentDownloadResourceInfo(settingsManager.getGlobalSettings().getBaseUrl(), attachment); }
From source file:com.cloudant.sync.datastore.AttachmentStreamFactoryTest.java
@Test /**/*from w w w . j ava2s. c o m*/ * Assert passing an AttachmentStreamFactory with known key reads an encrypted and * gzipped file correctly. */ public void testSavedAttachmentReadsEncryptedEncodedStream() throws AttachmentException, IOException { AttachmentStreamFactory asf = new AttachmentStreamFactory(EncryptionTestConstants.keyProvider16Byte); File plainText = f("fixture/EncryptedAttachmentTest_plainText"); File cipherAttachmentBlob = f("fixture/EncryptedAttachmentTest_gzip_cipherText_aes128"); SavedAttachment savedAttachment = new SavedAttachment(0, "test", null, "text/plain", Attachment.Encoding.Gzip, 0, 0, 0, cipherAttachmentBlob, asf); Assert.assertTrue("Reading encrypted, encoded stream didn't give correct output", IOUtils.contentEquals(savedAttachment.getInputStream(), new FileInputStream(plainText))); }
From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletTest.java
@Test public void testGIFUploadedToDAM() throws Exception { MockSlingHttpServletResponse response = spy(aemContext.response()); MockSlingHttpServletRequest request = prepareRequest(IMAGE6_PATH, "img", "gif"); servlet.doGet(request, response);// w ww .ja va 2 s .co m ByteArrayInputStream stream = new ByteArrayInputStream(response.getOutput()); InputStream directStream = this.getClass().getClassLoader() .getResourceAsStream("image/Adobe_Systems_logo_and_wordmark.svg.gif"); assertTrue(IOUtils.contentEquals(stream, directStream)); }
From source file:com.cloudant.sync.datastore.AttachmentTest.java
@Test public void testContentPreparedAttachmentsTest() throws Exception { String imageAttachmentName = "bonsai-boston.jpg"; File imageFile = TestUtils.loadFixture("fixture/" + imageAttachmentName); Attachment att2 = new UnsavedFileAttachment(imageFile, "image/jpeg"); PreparedAttachment imagePatt = new PreparedAttachment(att2, datastore_manager_dir, 0, new AttachmentStreamFactory(new NullKeyProvider())); IOUtils.contentEquals(new FileInputStream(imageFile), new FileInputStream(imagePatt.tempFile)); }
From source file:com.igormaznitsa.jcp.context.PreprocessingState.java
public boolean saveBuffersToFile(@Nonnull final File outFile, final boolean removeComments) throws IOException { final File path = outFile.getParentFile(); if (path != null && !path.exists() && !path.mkdirs()) { throw new IOException("Can't make directory [" + PreprocessorUtils.getFilePath(path) + ']'); }//from www. jav a 2s . co m Writer writer = null; boolean wasSaved = false; try { final int totatBufferedChars = prefixPrinter.getSize() + normalPrinter.getSize() + postfixPrinter.getSize(); final int BUFFER_SIZE = Math.min(totatBufferedChars << 1, MAX_WRITE_BUFFER_SIZE); if (this.overrideOnlyIfContentChanged) { String content = ((StringWriter) writePrinterBuffers(new StringWriter(totatBufferedChars))) .toString(); if (removeComments) { content = ((StringWriter) new JavaCommentsRemover(new StringReader(content), new StringWriter(totatBufferedChars)).process()).toString(); } boolean needWrite = true; // better write than not final byte[] contentInBinaryForm = content.getBytes(globalOutCharacterEncoding); if (outFile.isFile() && outFile.length() == contentInBinaryForm.length) { // If file exists and has the same content, then skip overwriting it InputStream currentFileInputStream = null; try { currentFileInputStream = new BufferedInputStream(new FileInputStream(outFile), Math.max(16384, (int) outFile.length())); needWrite = !IOUtils.contentEquals(currentFileInputStream, new ByteArrayInputStream(contentInBinaryForm)); } finally { IOUtils.closeQuietly(currentFileInputStream); } } if (needWrite) { FileUtils.writeByteArrayToFile(outFile, contentInBinaryForm, false); wasSaved = true; } else { this.context.logDebug( "Ignore writing data for " + outFile + " because its content has not been changed"); } } else if (removeComments) { final String joinedBufferContent = ((StringWriter) writePrinterBuffers( new StringWriter(totatBufferedChars))).toString(); writer = new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(outFile, false), BUFFER_SIZE), globalOutCharacterEncoding); new JavaCommentsRemover(new StringReader(joinedBufferContent), writer).process(); wasSaved = true; } else { writer = new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(outFile, false), BUFFER_SIZE), globalOutCharacterEncoding); writePrinterBuffers(writer); wasSaved = true; } } finally { IOUtils.closeQuietly(writer); } if (wasSaved && this.context.isCopyFileAttributes() && outFile.exists()) { PreprocessorUtils.copyFileAttributes(this.getRootFileInfo().getSourceFile(), outFile); } return wasSaved; }
From source file:com.collective.celos.ci.mode.test.TestConfigurationParserTest.java
@Test public void testFixDir() throws Exception { String js = "" + "ci.fixDir({" + " file1: ci.fixFile('123')," + " file2: ci.fixFile('234')" + "})"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); FixDirHierarchyCreator creator = (FixDirHierarchyCreator) creatorObj.unwrap(); FixDir fixDir = creator.create(null); Assert.assertEquals(fixDir.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file1").asFile().getContent(), new ByteArrayInputStream("123".getBytes()))); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file2").asFile().getContent(), new ByteArrayInputStream("234".getBytes()))); }
From source file:com.collective.celos.ci.mode.test.TestConfigurationParserTest.java
@Test public void testFixDirWithFixDir() throws Exception { String js = "" + "ci.fixDir({" + " file0: ci.fixFile('012')," + " dir1: ci.fixDir({" + " file1: ci.fixFile('123')," + " file2: ci.fixFile('234')" + " })" + "})"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); FixDirHierarchyCreator creator = (FixDirHierarchyCreator) creatorObj.unwrap(); FixDir fixDir = creator.create(null); Assert.assertEquals(fixDir.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file0").asFile().getContent(), new ByteArrayInputStream("012".getBytes()))); FixDir fixDir2 = (FixDir) fixDir.getChildren().get("dir1"); Assert.assertEquals(fixDir2.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir2.getChildren().get("file1").asFile().getContent(), new ByteArrayInputStream("123".getBytes()))); Assert.assertTrue(IOUtils.contentEquals(fixDir2.getChildren().get("file2").asFile().getContent(), new ByteArrayInputStream("234".getBytes()))); }