List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java
@Test(enabled = true, invocationCount = 1) public void write() throws IOException, FileBackException { fileContext.fileOperationSupplier(() -> FileOperation.WRITE); final ByteBuffer fileKey = randomFileKey(); fileContext.targetKeySupplier(() -> fileKey); final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true); final byte[] fileBytes = randomFileBytes(); final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean(); if (fileWritten) { Files.write(leafPath, fileBytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); logger.trace("file written"); }// ww w . j a v a 2 s.co m fileContext.sourceChannelSupplier(() -> Channels.newChannel(new ByteArrayInputStream(fileBytes))); fileContext.targetChannelConsumer(v -> { try { final long copied = IOUtils.copyLarge(new ByteArrayInputStream(fileBytes), Channels.newOutputStream(v)); } catch (final IOException ioe) { logger.error("failed to copy", ioe); } }); fileBack.operate(fileContext); if (fileWritten) { final byte[] actual = Files.readAllBytes(leafPath); assertEquals(actual, fileBytes); } }
From source file:com.pentaho.ctools.cde.reference.ExportPopupComponent.java
/** * ############################### Test Case 1 ############################### * * Test Case Name://from www .j av a 2s . c om * Sniff test to sample * * Description: * This test is to assert simple functionality of sample * * Steps: * 1. Open Duplicate Component sample and assert elements on page * 2. Export to PNG and assert file * 3. Export to SVG and assert file * 4. Export to CSV and assert file * 5. Export to XLS and assert file * 6. Export to JSON and assert file * 7. Export to XML and assert file * */ @Test public void tc01_CDEDashboard_ExportPopupComponentWorks() { this.log.info("tc01_CDEDashboard_ExportPopupComponentWorks"); /* * ## Step 1 */ //Open Duplicate Component sample driver.get(PageUrl.EXPORT_POPUP_COMPONENT); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Get Title of sample String title = this.elemHelper.WaitForElementPresentGetText(driver, By.id("Title")); assertEquals("Export Popup Component Reference", title); //Assert presence of elements WebElement chart = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("TheChartprotovis")); WebElement chartBar = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath( "//div[@id='TheChartprotovis']/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g']/*[name()='g'][2]/*[name()='rect'][4]")); WebElement chartLegend = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath( "//div[@id='TheChartprotovis']/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g'][4]/*[name()='g']/*[name()='g'][6]/*[name()='text']")); WebElement table = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("TheTableTable")); WebElement columnHeader = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//table[@id='TheTableTable']/thead/tr/th")); WebElement c2r6 = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//table[@id='TheTableTable']/tbody/tr[6]/td[2]")); assertNotNull(chart); assertNotNull(chartBar); assertNotNull(chartLegend); assertNotNull(table); assertNotNull(columnHeader); assertNotNull(c2r6); /* * ## Step 2 */ //Click to Export to PNG WebElement exportPNG = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='ChartExportPNGExporting']/div")); assertNotNull(exportPNG); exportPNG.click(); WebElement linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.cssSelector("div.exportElement")); assertNotNull(linkExport); linkExport.click(); //Assert chart popup WebElement exportChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content")); assertNotNull(exportChartPopup); // Check URL of displayed image String chartSRCUrl = this.elemHelper.GetAttribute(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src"); assertEquals(baseUrl + "plugin/cgg/api/services/draw?outputType=png&script=%2Fpublic%2Fplugin-samples%2Fpentaho-cdf-dd%2Ftests%2FExportPopup%2FBarChart.js¶mwidth=350¶mheight=200", chartSRCUrl); assertEquals(200, HttpUtils.GetResponseCode(chartSRCUrl, "admin", "password")); // Export chart and assert export was successful WebElement chartExportButton = this.elemHelper.FindElement(driver, By.cssSelector("div.exportChartPopupButton.exportChartOkButton")); assertNotNull(chartExportButton); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath).delete(); //Click to export chartExportButton.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 5000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "3bc1e421664d221d7c3fdc9cd56069ca"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } // Close dialog box this.elemHelper.Click(driver, By.id("fancybox-close")); assertTrue(this.elemHelper.WaitForElementNotPresent(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]"))); /* * ## Step 3 */ this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.exportElement")); //Click export Button WebElement exportCountryChartButton = this.elemHelper.FindElement(driver, By.xpath("//div[@id='ChartExportSVGExporting']/div")); assertNotNull(exportCountryChartButton); exportCountryChartButton.click(); //Assert popup and click Export Chart link WebElement exportCountryChartLink = this.elemHelper.FindElement(driver, By.xpath("//body/div[9]/div[1]")); assertNotNull(exportCountryChartLink); exportCountryChartLink.click(); //Assert chart popup WebElement exportCountryChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content")); assertNotNull(exportCountryChartPopup); // Check URL of displayed image String countryChartSRCUrl = this.elemHelper.GetAttribute(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src"); assertEquals(baseUrl + "plugin/cgg/api/services/draw?outputType=svg&script=%2Fpublic%2Fplugin-samples%2Fpentaho-cdf-dd%2Ftests%2FExportPopup%2FBarChart.js¶mwidth=350¶mheight=200", countryChartSRCUrl); assertEquals(200, HttpUtils.GetResponseCode(countryChartSRCUrl, "admin", "password")); // Export chart and assert export was successful WebElement countryChartExportButton = this.elemHelper.FindElement(driver, By.cssSelector("div.exportChartPopupButton.exportChartOkButton")); assertNotNull(countryChartExportButton); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath2).delete(); //Click to export countryChartExportButton.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath2); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 30000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "954fae4599f547ff62c8d2684fd9b497"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } // Close dialog box this.elemHelper.Click(driver, By.id("fancybox-close")); assertTrue(this.elemHelper.WaitForElementNotPresent(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]"))); /* * ## Step 4 */ //Click to Export to CSV WebElement exportCSV = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportCSVExporting']/div")); assertNotNull(exportCSV); exportCSV.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[10]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath3).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath3); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 3000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "a1be04c7c26ad6fbfb1d1920568b96ff"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 5 */ //Click to Export to CSV WebElement exportXLS = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportXLSExporting']/div")); assertNotNull(exportXLS); exportXLS.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[11]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath4).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath4); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 20000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "b680747e0e0f6e881a063027222d76d9"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 6 */ //Click to Export to JSON WebElement exportJSON = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportJSONExporting']/div")); assertNotNull(exportJSON); exportJSON.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[12]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath5).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath5); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 4000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "44fe88dc404ec0b240cd3095955ff084"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 7 */ //Click to Export to XML WebElement exportXML = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportXMLExporting']/div")); assertNotNull(exportXML); exportXML.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[13]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath6).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath6); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 6000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "a33133fbd76bb2cf6d0c8e3949c08e81"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } }
From source file:org.terracotta.management.model.cluster.ClusterTest.java
@Test public void test_toMap() throws IOException { String expectedJson = new String(Files.readAllBytes(new File("src/test/resources/cluster.json").toPath()), "UTF-8"); Map actual = cluster1.toMap(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); assertEquals(expectedJson, mapper.writeValueAsString(actual)); }
From source file:com.pentaho.ctools.cde.require.ExportPopupComponent.java
/** * ############################### Test Case 1 ############################### * * Test Case Name://from w w w . j a v a 2 s . c o m * Sniff test to sample * * Description: * This test is to assert simple functionality of sample * * Steps: * 1. Open Duplicate Component sample and assert elements on page * 2. Export to PNG and assert file * 3. Export to SVG and assert file * 4. Export to CSV and assert file * 5. Export to XLS and assert file * 6. Export to JSON and assert file * 7. Export to XML and assert file * */ @Test public void tc01_CDEDashboard_ExportPopupComponentWorks() { this.log.info("tc01_CDEDashboard_ExportPopupComponentWorks"); /* * ## Step 1 */ //Open Duplicate Component sample driver.get(PageUrl.EXPORT_POPUP_COMPONENT_REQUIRE); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Get Title of sample String title = this.elemHelper.WaitForElementPresentGetText(driver, By.id("Title")); assertEquals("Export Popup Component Reference", title); //Assert presence of elements WebElement chart = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("TheChartprotovis")); WebElement chartBar = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath( "//div[@id='TheChartprotovis']/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g']/*[name()='g'][2]/*[name()='rect'][4]")); WebElement chartLegend = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath( "//div[@id='TheChartprotovis']/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']/*[name()='g']/*[name()='g'][2]/*[name()='g']/*[name()='g'][4]/*[name()='g']/*[name()='g'][6]/*[name()='text']")); WebElement table = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("TheTableTable")); WebElement columnHeader = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//table[@id='TheTableTable']/thead/tr/th")); WebElement c2r6 = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//table[@id='TheTableTable']/tbody/tr[6]/td[2]")); assertNotNull(chart); assertNotNull(chartBar); assertNotNull(chartLegend); assertNotNull(table); assertNotNull(columnHeader); assertNotNull(c2r6); /* * ## Step 2 */ //Click to Export to PNG WebElement exportPNG = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='ChartExportPNGExporting']/div")); assertNotNull(exportPNG); exportPNG.click(); WebElement linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.cssSelector("div.exportElement")); assertNotNull(linkExport); linkExport.click(); //Assert chart popup WebElement exportChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content")); assertNotNull(exportChartPopup); // Check URL of displayed image String chartSRCUrl = this.elemHelper.GetAttribute(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src"); assertEquals(baseUrl + "plugin/cgg/api/services/draw?outputType=png&script=%2Fpublic%2Fplugin-samples%2Fpentaho-cdf-dd%2Fpentaho-cdf-dd-require%2Ftests%2FExportPopup%2FBarChart.js¶mwidth=350¶mheight=200", chartSRCUrl); assertEquals(200, HttpUtils.GetResponseCode(chartSRCUrl, "admin", "password")); // Export chart and assert export was successful WebElement chartExportButton = this.elemHelper.FindElement(driver, By.cssSelector("div.exportChartPopupButton.exportChartOkButton")); assertNotNull(chartExportButton); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath).delete(); //Click to export chartExportButton.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 5000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "3bc1e421664d221d7c3fdc9cd56069ca"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } // Close dialog box this.elemHelper.Click(driver, By.id("fancybox-close")); assertTrue(this.elemHelper.WaitForElementNotPresent(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]"))); /* * ## Step 3 */ this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.exportElement")); //Click export Button WebElement exportCountryChartButton = this.elemHelper.FindElement(driver, By.xpath("//div[@id='ChartExportSVGExporting']/div")); assertNotNull(exportCountryChartButton); exportCountryChartButton.click(); //Assert popup and click Export Chart link WebElement exportCountryChartLink = this.elemHelper.FindElement(driver, By.xpath("//body/div[9]/div[1]")); assertNotNull(exportCountryChartLink); exportCountryChartLink.click(); //Assert chart popup WebElement exportCountryChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content")); assertNotNull(exportCountryChartPopup); // Check URL of displayed image String countryChartSRCUrl = this.elemHelper.GetAttribute(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src"); assertEquals(baseUrl + "plugin/cgg/api/services/draw?outputType=svg&script=%2Fpublic%2Fplugin-samples%2Fpentaho-cdf-dd%2Fpentaho-cdf-dd-require%2Ftests%2FExportPopup%2FBarChart.js¶mwidth=350¶mheight=200", countryChartSRCUrl); assertEquals(200, HttpUtils.GetResponseCode(countryChartSRCUrl, "admin", "password")); // Export chart and assert export was successful WebElement countryChartExportButton = this.elemHelper.FindElement(driver, By.cssSelector("div.exportChartPopupButton.exportChartOkButton")); assertNotNull(countryChartExportButton); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath2).delete(); //Click to export countryChartExportButton.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath2); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 30000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "954fae4599f547ff62c8d2684fd9b497"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } // Close dialog box this.elemHelper.Click(driver, By.id("fancybox-close")); assertTrue(this.elemHelper.WaitForElementNotPresent(driver, By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]"))); /* * ## Step 4 */ //Click to Export to CSV WebElement exportCSV = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportCSVExporting']/div")); assertNotNull(exportCSV); exportCSV.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[10]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath3).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath3); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 3000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "a1be04c7c26ad6fbfb1d1920568b96ff"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 5 */ //Click to Export to CSV WebElement exportXLS = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportXLSExporting']/div")); assertNotNull(exportXLS); exportXLS.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[11]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath4).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath4); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 20000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "b680747e0e0f6e881a063027222d76d9"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 6 */ //Click to Export to JSON WebElement exportJSON = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportJSONExporting']/div")); assertNotNull(exportJSON); exportJSON.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[12]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath5).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath5); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 4000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "44fe88dc404ec0b240cd3095955ff084"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } /* * ## Step 7 */ //Click to Export to XML WebElement exportXML = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//div[@id='DataExportXMLExporting']/div")); assertNotNull(exportXML); exportXML.click(); linkExport = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//body/div[13]/div[1]")); assertNotNull(linkExport); //Click export and assert file is correctly downloaded try { //Delete the existence if exist new File(this.exportFilePath6).delete(); //Click to export linkExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); //Check if the file really exist File exportFile = new File(this.exportFilePath6); // assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 6000) { break; } this.log.info("BeforeSleep " + nSize); Thread.sleep(100); } this.log.info("File size :" + FileUtils.sizeOf(exportFile)); //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "a33133fbd76bb2cf6d0c8e3949c08e81"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } }
From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java
private void handleClassEntry(Path pathInZip, final Class c, FileSystem fs, Path uploadersDirectory) throws IOException { Path classLocationOnDisk = uploadersDirectory.resolve(pathInZip.toString()); DirectoryStream<Path> ds = Files.newDirectoryStream(classLocationOnDisk, new DirectoryStream.Filter<Path>() { @Override/*w w w . j av a2 s . c o m*/ public boolean accept(Path entry) throws IOException { String fn = entry.getFileName().toString(); String cn = c.getSimpleName(); return fn.equals(cn + ".class") || fn.startsWith(cn + "$"); } }); for (Path p : ds) { byte[] b = Files.readAllBytes(p); Files.write(pathInZip.resolve(p.getFileName().toString()), b); } // say we want to zie SomeClass.class // then we also need to zip SomeClass$1.class // That is, we also need to zip inner classes and inner annoymous classes // into the zip as well }
From source file:org.primeframework.mvc.test.RequestResult.java
/** * Verifies that the response body is equal to the given JSON text file. * * @param jsonFile The JSON file to load and compare to the JSON response. * @param values key value pairs of replacement values for use in the JSON file. * @return This./* w w w .j av a2 s . c o m*/ * @throws IOException If the JSON marshalling failed. */ public RequestResult assertJSONFile(Path jsonFile, Object... values) throws IOException { if (values.length == 0) { return assertJSON(new String(Files.readAllBytes(jsonFile), "UTF-8")); } return assertJSON(BodyTools.processTemplate(jsonFile, values)); }
From source file:com.netscape.cmstools.CRMFPopClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();/*from ww w. java 2 s. c o m*/ CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String tokenPassword = cmd.getOptionValue("p"); String tokenName = cmd.getOptionValue("h"); String algorithm = cmd.getOptionValue("a", "rsa"); int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048")); String profileID = cmd.getOptionValue("f"); String subjectDN = cmd.getOptionValue("n"); boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false")); // if transportCertFilename is not specified then assume no key archival String transportCertFilename = cmd.getOptionValue("b"); String popOption = cmd.getOptionValue("q", "POP_SUCCESS"); String curve = cmd.getOptionValue("c", "nistp256"); boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false")); boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true")); int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1")); int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1")); boolean self_sign = cmd.hasOption("y"); // get the keywrap algorithm KeyWrapAlgorithm keyWrapAlgorithm = null; String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString(); if (cmd.hasOption("w")) { kwAlg = cmd.getOptionValue("w"); } else { String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM"); if (alg != null) { kwAlg = alg; } } String output = cmd.getOptionValue("o"); String hostPort = cmd.getOptionValue("m"); String username = cmd.getOptionValue("u"); String requestor = cmd.getOptionValue("r"); if (hostPort != null) { if (cmd.hasOption("w")) { printError("Any value specified for the key wrap parameter (-w) " + "will be overriden. CRMFPopClient will contact the " + "CA to determine the supported algorithm when " + "hostport is specified"); } } if (subjectDN == null) { printError("Missing subject DN"); System.exit(1); } if (tokenPassword == null) { printError("Missing token password"); System.exit(1); } if (algorithm.equals("rsa")) { if (cmd.hasOption("c")) { printError("Illegal parameter for RSA: -c"); System.exit(1); } if (cmd.hasOption("t")) { printError("Illegal parameter for RSA: -t"); System.exit(1); } if (cmd.hasOption("s")) { printError("Illegal parameter for RSA: -s"); System.exit(1); } if (cmd.hasOption("e")) { printError("Illegal parameter for RSA: -e"); System.exit(1); } if (cmd.hasOption("x")) { printError("Illegal parameter for RSA: -x"); System.exit(1); } } else if (algorithm.equals("ec")) { if (cmd.hasOption("l")) { printError("Illegal parameter for ECC: -l"); System.exit(1); } if (sensitive != 0 && sensitive != 1 && sensitive != -1) { printError("Illegal input parameters for -s: " + sensitive); System.exit(1); } if (extractable != 0 && extractable != 1 && extractable != -1) { printError("Illegal input parameters for -e: " + extractable); System.exit(1); } } else { printError("Invalid algorithm: " + algorithm); System.exit(1); } if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) { printError("Invalid POP option: " + popOption); System.exit(1); } if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caEncUserCert"; } else if (algorithm.equals("ec")) { profileID = "caEncECUserCert"; } else { throw new Exception("Unknown algorithm: " + algorithm); } } try { if (verbose) System.out.println("Initializing security database: " + databaseDir); CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); try { token.login(password); } catch (Exception e) { throw new Exception("Unable to login: " + e, e); } CRMFPopClient client = new CRMFPopClient(); client.setVerbose(verbose); String encoded = null; X509Certificate transportCert = null; if (transportCertFilename != null) { if (verbose) System.out.println("archival option enabled"); if (verbose) System.out.println("Loading transport certificate"); encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); byte[] transportCertData = Cert.parseCertificate(encoded); transportCert = manager.importCACertPackage(transportCertData); } else { if (verbose) System.out.println("archival option not enabled"); } if (verbose) System.out.println("Parsing subject DN"); Name subject = client.createName(subjectDN, encodingEnabled); if (subject == null) { subject = new Name(); subject.addCommonName("Me"); subject.addCountryName("US"); subject.addElement( new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid"))); } if (verbose) System.out.println("Generating key pair"); KeyPair keyPair; if (algorithm.equals("rsa")) { keyPair = CryptoUtil.generateRSAKeyPair(token, keySize); } else if (algorithm.equals("ec")) { keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable); } else { throw new Exception("Unknown algorithm: " + algorithm); } // print out keyid to be used in cmc decryptPOP PrivateKey privateKey = (PrivateKey) keyPair.getPrivate(); @SuppressWarnings("deprecation") byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); System.out.println("Keypair private key id: " + kid); if ((transportCert != null) && (hostPort != null)) { // check the CA for the required key wrap algorithm // if found, override whatever has been set by the command line // options for the key wrap algorithm ClientConfig config = new ClientConfig(); String host = hostPort.substring(0, hostPort.indexOf(':')); int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1)); config.setServerURL("http", host, port); PKIClient pkiclient = new PKIClient(config); kwAlg = getKeyWrapAlgotihm(pkiclient); } if (verbose && (transportCert != null)) System.out.println("Using key wrap algorithm: " + kwAlg); if (transportCert != null) { keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); } if (verbose) System.out.println("Creating certificate request"); CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair, subject, keyWrapAlgorithm); ProofOfPossession pop = null; if (!popOption.equals("POP_NONE")) { if (verbose) System.out.println("Creating signer"); Signature signer = client.createSigner(token, algorithm, keyPair); if (popOption.equals("POP_SUCCESS")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); certRequest.encode(bo); signer.update(bo.toByteArray()); } else if (popOption.equals("POP_FAIL")) { byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; signer.update(data); } byte[] signature = signer.sign(); if (verbose) System.out.println("Creating POP"); pop = client.createPop(algorithm, signature); } if (verbose) System.out.println("Creating CRMF request"); String request = client.createCRMFRequest(certRequest, pop); StringWriter sw = new StringWriter(); try (PrintWriter out = new PrintWriter(sw)) { out.println(Cert.REQUEST_HEADER); out.print(request); out.println(Cert.REQUEST_FOOTER); } String csr = sw.toString(); if (hostPort != null) { System.out.println("Submitting CRMF request to " + hostPort); client.submitRequest(request, hostPort, username, profileID, requestor); } else if (output != null) { System.out.println("Storing CRMF request into " + output); try (FileWriter out = new FileWriter(output)) { out.write(csr); } } else { System.out.println(csr); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:net.morimekta.idltool.IdlUtils.java
public static Map<String, String> buildSha1Sums(Path dir) throws IOException { ImmutableSortedMap.Builder<String, String> sha1sums = ImmutableSortedMap.naturalOrder(); // TODO: Support nested directories. Files.list(dir).forEach(file -> { try {//from w ww . j a v a2s . co m if (Files.isRegularFile(file)) { String sha = DigestUtils.sha1Hex(Files.readAllBytes(file)); sha1sums.put(file.getFileName().toString(), sha); } } catch (IOException e) { throw new UncheckedIOException(e.getMessage(), e); } }); return sha1sums.build(); }
From source file:com.ibm.zurich.Main.java
private static byte[] readFromFile(String fileName) throws IOException { return Files.readAllBytes(Paths.get(fileName)); }
From source file:lab4.YouQuiz.java
private void switchToQuizMode() { JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false);//w ww .j a v a 2s . c o m backButton.setFocusable(false); toolbar.add(backButton); toolbar.setAlignmentX(0); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { contentPanel.setQuestion(questionsArray.get(--questionIndex)); forwardButton.setEnabled(true); if (questionIndex - 1 < 0) { backButton.setEnabled(false); } updateAnswerForm(); } }); forwardButton.setFocusable(false); toolbar.add(forwardButton); toolbar.setAlignmentX(0); forwardButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { contentPanel.setQuestion(questionsArray.get(++questionIndex)); backButton.setEnabled(true); if (questionsArray.size() == questionIndex + 1) { forwardButton.setEnabled(false); } updateAnswerForm(); } }); speakButton.setFocusable(false); toolbar.add(speakButton); toolbar.setAlignmentX(0); speakButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Audio audio = Audio.getInstance(); InputStream sound = null; try { sound = audio.getAudio(questionsArray.get(questionIndex).getQuestion(), Language.ENGLISH); } catch (IOException ex) { Logger.getLogger(YouQuiz.class.getName()).log(Level.SEVERE, null, ex); } try { audio.play(sound); } catch (JavaLayerException ex) { Logger.getLogger(YouQuiz.class.getName()).log(Level.SEVERE, null, ex); } } }); refreshButton.setFocusable(false); toolbar.add(refreshButton); toolbar.setAlignmentX(0); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { shuffleQuestions(); questionIndex = 0; backButton.setEnabled(false); if (questionsArray.size() == 1) { forwardButton.setEnabled(false); } else { forwardButton.setEnabled(true); } contentPanel.setQuestion(questionsArray.get(questionIndex)); updateAnswerForm(); } }); micButton.setFocusable(false); toolbar.add(micButton); toolbar.setAlignmentX(0); micButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { GSpeechDuplex dup = new GSpeechDuplex(); dup.addResponseListener(new GSpeechResponseListener() { @Override public void onResponse(GoogleResponse gr) { if (questionsArray.get(questionIndex).checkAnswer(gr.getResponse())) { JOptionPane.showMessageDialog(null, "Thats Great, Correct Answer", "Excellent", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Oops! '" + gr.getResponse() + "' is a wrong Answer. Its '" + questionsArray.get(questionIndex).getAnswer().get(0) + "'", "Sorry", JOptionPane.ERROR_MESSAGE); } } }); Microphone mic = new Microphone(FLACFileWriter.FLAC); File file = new File("CRAudioTest.flac"); try { mic.captureAudioToFile(file); Thread.sleep(5000); mic.close(); byte[] data = Files.readAllBytes(mic.getAudioFile().toPath()); dup.recognize(data, (int) mic.getAudioFormat().getSampleRate()); mic.getAudioFile().delete(); } catch (LineUnavailableException | InterruptedException | IOException ex) { } } }); contentPanel = new ContentPanel(); contentPanel.add(Box.createRigidArea(new Dimension(0, 10))); contentPanel.add(toolbar, BorderLayout.NORTH); contentPanel.add(Box.createRigidArea(new Dimension(0, 50))); contentPanel.add(contentPanel.questionLabel); add(contentPanel, BorderLayout.CENTER); if (questionsArray.isEmpty()) { refreshButton.setEnabled(false); backButton.setEnabled(false); forwardButton.setEnabled(false); speakButton.setEnabled(false); } else { questionIndex = 0; backButton.setEnabled(false); if (questionsArray.size() == 1) { forwardButton.setEnabled(false); } contentPanel.setQuestion(questionsArray.get(questionIndex)); contentPanel.add(Box.createRigidArea(new Dimension(0, 20))); contentPanel.add(contentPanel.answerPanel); contentPanel.add(Box.createRigidArea(new Dimension(0, 10))); contentPanel.add(contentPanel.checkButton); updateAnswerForm(); } }