List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java
@Override public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) { if (testedPropertyValue == null && validatorPropertyValue == null) return true; ObjectMapper mapper = new ObjectMapper(); ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue, ContentFileTestExpectation.class); ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class); InputStream dataStream;/*ww w . jav a 2 s . co m*/ if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) { return true; } try { System.out.println("About to retrieve content for " + referencedData.toString()); dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData); System.out.println("Finished retrieving content for " + referencedData.toString()); } catch (DataSourceException e) { e.printStackTrace(); System.err.println("Failed to acquire referenced data."); e.printStackTrace(); TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(), e); return false; } try { String contentFileName = expectation.getExpectedContentFile(); Path contentFile = Paths.get(contentFileName); if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) { contentFile = Paths.get(testSourcefileBaseFolder, contentFileName); } if (Files.notExists(contentFile)) { contentFile = Paths.get(testDataFolder, contentFileName); } byte[] expectedFileBytes = Files.readAllBytes(contentFile); if (expectation.getComparisonType() == ContentComparisonType.TEXT) { String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8); String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8); if (expectation.getExpectedSimilarityPercentage() == 100) { boolean equals = actualText.equals(expectedText); if (!equals) { String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n" + expectedText + "\n\n*** Actual Text ***\n" + actualText; System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } return true; } double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText); System.out.println("Compared text similarity:" + similarity + "%"); if (similarity < expectation.getExpectedSimilarityPercentage()) { String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage() + "% but actual similarity was " + similarity + "%"; System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } } else { byte[] actualDataBytes = IOUtils.toByteArray(dataStream); boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes); if (!equals) { String actualContentFileName = contentFile.getFileName() + "_actual"; Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName); Files.deleteIfExists(actualFilePath); Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE); String message = "Data returned was different than expected for file: " + contentFileName + "\nActual content saved in file: " + actualFilePath.toString(); System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } } } catch (IOException e) { e.printStackTrace(); TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e); return false; } return true; }
From source file:edu.odu.cs.cs350.yellow1.ui.cli.Main.java
/** * Main program function. Creates and runs mutants as well as logging and output files * /* w w w . j av a 2 s .c o m*/ * @param srcFolder Source folder for project to be mutated * @param fileToBeMutated Source file for project to be mutated * @param testSuitePath Path for test suite * @param goldOutput Original version output file * @throws BuildFileNotFoundException * @throws IOException */ @SuppressWarnings("static-access") public static void mutate(String srcFolder, String fileToBeMutated, String testSuitePath, String goldOutput) throws BuildFileNotFoundException, IOException { //Step 1: Set up file directory paths for antRunner, jarExecutor, and fileMover logger = LogManager.getLogger(Main.class); mutLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs" + File.separator + "mutationsApplied.txt"); aliveLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs" + File.separator + "mutationsAlive.txt"); logFolder = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"); // ok because of the output on jenkins sanitize the logs directory if (logFolder.exists()) if (logFolder.isDirectory()) for (File f : logFolder.listFiles()) f.delete(); //give ant runer the project location ant = new AntRunner(srcFolder); ant.requiresInit(true); //call setup ant.setUp(); a = new JavaFile(); //give the jarUtil the directory where to expect the jar the directory where to put the jar jar = new JarUtil((srcFolder + File.separator + "bin"), (srcFolder + File.separator + "mutantDir")); //get a file object to the original file File goldFile = new File(fileToBeMutated); goldPath = goldFile.toPath(); //get the bytes from it for checking if applying mutation and restore works goldOrgContent = Files.readAllBytes(goldPath); File script = new File(srcFolder + File.separator + "compare.sh"); //build the JarExecutor using the JarExecutor jarExecutor = JarExecutorBuilder.pathToJarDirectory(srcFolder + File.separator + "mutantDir") .pathToCompareScript(script.getAbsolutePath()) .pathToLogDir(srcFolder + File.separator + "mutantDir" + File.separator + "logs") .pathToGold(goldOutput.toString()).withExecutionState(ExecutionState.multiFile) .withTestSuitePath(testSuitePath).create(); File tDir = new File(srcFolder + File.separator + "mutantDir"); if (!tDir.exists()) tDir.mkdir(); //Create a fileMover object give it the directory where mutations will be placed the directory of the original file location fMover = new FileMover(srcFolder + File.separator + "mutantDir", fileToBeMutated); fMover.setNoDelete(true); try { fMover.setUp(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } //Step2: Create and run mutants try { a.readFile(fileToBeMutated); } catch (IOException e) { e.printStackTrace(); } a.executeAll(); int mutantsCreated = a.getMutantCaseVector().getSize(); logger.info("Created " + mutantsCreated + " Mutants"); for (int i = 0; i < a.getMutantCaseVector().getSize(); i++) { a.getMutantCaseOperations(i).writeMutation(srcFolder + File.separator + "mutantDir" + File.separator + "Mutation" + Integer.toString(i + 1) + ".java"); } //get the files into the file mover object fMover.pullFiles(); //check to see if the filemover got all the files //assertEquals(fMover.getFileToBeMovedCount(),mutantsCreated); int moved = 0; int failed = 0; //move through each file moving them one by one while (fMover.hasMoreFiles()) { try { //move next file fMover.moveNextFile(); //build the new executable ant.build(); //move the created jar with correct number corresponding to the mutation created jar.moveJarToDestNumbered(); //clean the project ant.clean(); //check to see if the mutation was applied //assertThat(additionOrgContent, IsNot.not(IsEqual.equalTo(Files.readAllBytes(additionPath)))); } catch (FileMovingException | BuildException | TargetNotFoundException | IOException e) { //build failed if (e instanceof BuildException) { logger.error("Build exception " + e.getMessage()); //restore the file back since compilation was not successful fMover.restorTarget(); //try { // //check to see if the file was restored // assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath)); //} catch (IOException e1) { // //} //clean the project try { ant.clean(); } catch (BuildException e1) { } catch (TargetNotFoundException e1) { } //indicate compile failure ++failed; } //fail(); } //restore the file back to its original state fMover.restorTarget(); //check to see if the file was restored //try { // assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath)); //} catch (IOException e) { // //} //increment move count ++moved; //see if the file mover has the correct amount of mutatants still to be moved //assertEquals(fMover.getFileToBeMovedCount(), mutantsCreated - moved); } //set up for execution jarExecutor.setUp(); //start execution of jars jarExecutor.start(); //get the number of successful and failed runs int succesful = jarExecutor.getNumberOfMutantsKilled(); int failurs = jarExecutor.getNumberOfMutantsNotKilled(); int numTests = jarExecutor.getNumberOfTests(); int total = succesful + failurs; String aliveFile = null; String newLine = System.lineSeparator(); //Find any test jars that remain alive and write them to the log file List<ExecutionResults> testResults = jarExecutor.getMutationTestingResults(); for (ExecutionResults result : testResults) { if (!result.isKilled()) { aliveFile = result.getJarName(); FileUtils.writeStringToFile(aliveLog, aliveFile + newLine, true); } } //moved - failed = number of jars actually created moved = moved - failed; //see if the total number of executions equals the total amount of jars created //assertEquals(succesful+failurs,moved); logger.debug("Compilation failurs= " + failed + " total files moved= " + moved); logger.debug("Execution succesful=" + succesful + " Execution failurs= " + failurs); EOL eol = System.getProperty("os.name").toLowerCase().contains("windows") ? EOL.DOS : EOL.NIX; try { a.writeMutationsLog(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs" + File.separator + "mutationsApplied.txt", eol); } catch (Exception e) { logger.error(e.getMessage()); } String finalOutput = "Number of tests: " + numTests + " " + "Number of mutants: " + total + " " + "Mutants killed: " + succesful; FileUtils.writeStringToFile(mutLog, newLine + finalOutput, true); System.out.println(finalOutput + "\n"); }
From source file:grakn.core.daemon.executor.Storage.java
private void initialiseConfig() { try {/* w ww.jav a2 s . c o m*/ ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); TypeReference<Map<String, Object>> reference = new TypeReference<Map<String, Object>>() { }; ByteArrayOutputStream outputstream = new ByteArrayOutputStream(); // Read the original Cassandra config from services/cassandra/cassandra.yaml into a String byte[] oldConfigBytes = Files.readAllBytes(Paths.get(STORAGE_CONFIG_PATH, STORAGE_CONFIG_NAME)); String oldConfig = new String(oldConfigBytes, StandardCharsets.UTF_8); // Convert the String of config values into a Map Map<String, Object> oldConfigMap = mapper.readValue(oldConfig, reference); oldConfigMap = Maps.transformValues(oldConfigMap, value -> value == null ? EMPTY_VALUE : value); // Set the original config as the starting point of the new config values Map<String, Object> newConfigMap = new HashMap<>(oldConfigMap); // Read the Grakn config which is available to the user Config inputConfig = Config .read(Paths.get(Objects.requireNonNull(SystemProperty.CONFIGURATION_FILE.value()))); // Set the new data directories for Cassandra String newDataDir = inputConfig.getProperty(ConfigKey.DATA_DIR); newConfigMap.put(DATA_FILE_DIR_CONFIG_KEY, Collections.singletonList(newDataDir + DATA_SUBDIR)); newConfigMap.put(SAVED_CACHES_DIR_CONFIG_KEY, newDataDir + SAVED_CACHES_SUBDIR); newConfigMap.put(COMMITLOG_DIR_CONFIG_KEY, newDataDir + COMMITLOG_SUBDIR); // Overwrite Cassandra config values with values provided in the Grakn config inputConfig.properties().stringPropertyNames().stream().filter(key -> key.contains(CONFIG_PARAM_PREFIX)) .forEach(key -> newConfigMap.put(key.replaceAll(CONFIG_PARAM_PREFIX, ""), inputConfig.properties().getProperty(key))); // Write the new Cassandra config into the original file: services/cassandra/cassandra.yaml mapper.writeValue(outputstream, newConfigMap); String newConfigStr = outputstream.toString(StandardCharsets.UTF_8.name()); Files.write(Paths.get(STORAGE_CONFIG_PATH, STORAGE_CONFIG_NAME), newConfigStr.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ijfx.service.history.HistoryService.java
public Workflow loadWorkflow(File file) { try {/*from www . j a va2 s. co m*/ return loadWorkflow(new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())))); } catch (IOException ex) { ImageJFX.getLogger().log(Level.SEVERE, "Error when loading workflow.", ex); ; } return null; }
From source file:com.surevine.gateway.scm.gatewayclient.MetadataUtil.java
public static Map<String, String> getMetadataFromPath(final Path metadataPath) { final Map<String, String> metadata = new HashMap<>(); try {// w w w . j a v a2 s .c o m final JSONObject jsonObject = new JSONObject( new String(Files.readAllBytes(metadataPath), Charset.forName("UTF-8"))); for (final Object key : jsonObject.keySet()) { try { final String keyString = (String) key; final String value = jsonObject.getString(keyString); if (value != null && !value.isEmpty()) { metadata.put(keyString, value); } } catch (final JSONException jsonException) { // no-op - skip as the value is not a string and metadata entries are expected to be String:String } } } catch (final IOException e) { LOGGER.error("Could not read the mock gateway config", e); } return metadata; }
From source file:com.ericsson.eiffel.remrem.publish.cli.CLI.java
/** * Handle event from file/*from ww w .ja v a 2s . co m*/ * @param filePath the path of the file where the messages reside */ public void handleContentFile(String filePath) { try { byte[] fileBytes = Files.readAllBytes(Paths.get(filePath)); String fileContent = new String(fileBytes); handleContent(fileContent); } catch (final NoSuchFileException e) { log.debug("NoSuchFileException", e); System.err.println("File not found: " + e.getMessage()); CliOptions.exit(CLIExitCodes.HANDLE_CONTENT_FILE_NOT_FOUND_FAILED); } catch (Exception e) { System.err.println("Could not read content file. Cause: " + e.getMessage()); CliOptions.exit(CLIExitCodes.HANDLE_CONTENT_FILE_COULD_NOT_READ_FAILED); } }
From source file:com.sonar.javascript.it.plugin.SonarLintTest.java
private ClientInputFile createInputFile(final Path path, final boolean isTest) { return new ClientInputFile() { @Override//from ww w . j a va2s. c o m public String getPath() { return path.toString(); } @Override public boolean isTest() { return isTest; } @Override public Charset getCharset() { return StandardCharsets.UTF_8; } @Override public <G> G getClientObject() { return null; } @Override public String contents() throws IOException { return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); } @Override public InputStream inputStream() throws IOException { return Files.newInputStream(path); } }; }
From source file:io.undertow.server.handlers.accesslog.AccessLogFileTestCase.java
private void verifySingleLogMessageToFile(Path logFileName, DefaultAccessLogReceiver logReceiver) throws IOException, InterruptedException { CompletionLatchHandler latchHandler; DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(new AccessLogHandler(HELLO_HANDLER, logReceiver, "Remote address %a Code %s test-header %{i,test-header} %{i,non-existent}", AccessLogFileTestCase.class.getClassLoader()))); TestHttpClient client = new TestHttpClient(); try {// w ww . ja va 2 s . com HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); get.addHeader("test-header", "single-val"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Hello", HttpClientUtils.readResponse(result)); latchHandler.await(); logReceiver.awaitWrittenForTest(); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header single-val -\n", new String(Files.readAllBytes(logFileName))); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.jetbrains.webdemo.examples.ExamplesLoader.java
private static Example loadExample(String path, String parentUrl, boolean loadTestVersion, List<ObjectNode> commonFilesManifests) throws IOException { File manifestFile = new File(path + File.separator + "manifest.json"); try (BufferedInputStream reader = new BufferedInputStream(new FileInputStream(manifestFile))) { ObjectNode manifest = (ObjectNode) JsonUtils.getObjectMapper().readTree(reader); String name = new File(path).getName(); String id = (parentUrl + name).replaceAll(" ", "%20"); String args = manifest.has("args") ? manifest.get("args").asText() : ""; String runConfiguration = manifest.get("confType").asText(); boolean searchForMain = manifest.has("searchForMain") ? manifest.get("searchForMain").asBoolean() : true;//from w w w .j a va 2 s. c o m String expectedOutput; List<String> readOnlyFileNames = new ArrayList<>(); List<ProjectFile> files = new ArrayList<>(); List<ProjectFile> hiddenFiles = new ArrayList<>(); if (manifest.has("expectedOutput")) { expectedOutput = manifest.get("expectedOutput").asText(); } else if (manifest.has("expectedOutputFile")) { Path expectedOutputFilePath = Paths .get(path + File.separator + manifest.get("expectedOutputFile").asText()); expectedOutput = new String(Files.readAllBytes(expectedOutputFilePath)); } else { expectedOutput = null; } String help = null; File helpFile = new File(path + File.separator + "task.md"); if (helpFile.exists()) { PegDownProcessor processor = new PegDownProcessor(org.pegdown.Extensions.FENCED_CODE_BLOCKS); String helpInMarkdown = new String(Files.readAllBytes(helpFile.toPath())); help = new GFMNodeSerializer().toHtml(processor.parseMarkdown(helpInMarkdown.toCharArray())); } List<JsonNode> fileManifests = new ArrayList<JsonNode>(); if (manifest.has("files")) { for (JsonNode fileManifest : manifest.get("files")) { fileManifests.add(fileManifest); } } fileManifests.addAll(commonFilesManifests); for (JsonNode fileDescriptor : fileManifests) { if (loadTestVersion && fileDescriptor.has("skipInTestVersion") && fileDescriptor.get("skipInTestVersion").asBoolean()) { continue; } String filePath = fileDescriptor.has("path") ? fileDescriptor.get("path").asText() : path + File.separator + fileDescriptor.get("filename").textValue(); ExampleFile file = loadExampleFile(filePath, id, fileDescriptor); if (!loadTestVersion && file.getType().equals(ProjectFile.Type.SOLUTION_FILE)) { continue; } if (!file.isModifiable()) { readOnlyFileNames.add(file.getName()); } if (file.isHidden()) { hiddenFiles.add(file); } else { files.add(file); } } loadDefaultFiles(path, id, files, loadTestVersion); return new Example(id, name, args, runConfiguration, id, expectedOutput, searchForMain, files, hiddenFiles, readOnlyFileNames, help); } catch (IOException e) { System.err.println("Can't load project: " + e.toString()); return null; } }
From source file:ch.threema.apitool.helpers.E2EHelper.java
/** * Encrypt an image message and send it to the given recipient. * * @param threemaId target Threema ID//w ww . j a va 2 s. c o m * @param imageFilePath path to read image data from * @return generated message ID * @throws NotAllowedException * @throws IOException * @throws InvalidKeyException */ public String sendImageMessage(String threemaId, String imageFilePath) throws NotAllowedException, IOException, InvalidKeyException { //fetch public key byte[] publicKey = this.apiConnector.lookupKey(threemaId); if (publicKey == null) { throw new InvalidKeyException("invalid threema id"); } //check capability of a key CapabilityResult capabilityResult = this.apiConnector.lookupKeyCapability(threemaId); if (capabilityResult == null || !capabilityResult.canImage()) { throw new NotAllowedException(); } byte[] fileData = Files.readAllBytes(Paths.get(imageFilePath)); if (fileData == null) { throw new IOException("invalid file"); } //encrypt the image EncryptResult encryptResult = CryptTool.encrypt(fileData, this.privateKey, publicKey); //upload the image UploadResult uploadResult = apiConnector.uploadFile(encryptResult); if (!uploadResult.isSuccess()) { throw new IOException("could not upload file (upload response " + uploadResult.getResponseCode() + ")"); } //send it EncryptResult imageMessage = CryptTool.encryptImageMessage(encryptResult, uploadResult, privateKey, publicKey); return apiConnector.sendE2EMessage(threemaId, imageMessage.getNonce(), imageMessage.getResult()); }