List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java
/** * /*w w w . j av a 2 s.c o m*/ * @param serviceConfigFile * @return */ protected ServiceInfo parseServiceInfo(File serviceConfigFile) { ServiceInfo serviceInfo = null; String serviceConfigStr; try { serviceConfigStr = new String(Files.readAllBytes(serviceConfigFile.toPath())); serviceInfo = ServiceInfo.parse(serviceConfigStr); } catch (IOException e) { e.printStackTrace(); } return serviceInfo; }
From source file:info.pancancer.arch3.test.TestWorkerWithMocking.java
@Test public void testRunWorker() throws ShutdownSignalException, ConsumerCancelledException, InterruptedException, Exception { PowerMockito.whenNew(DefaultExecuteResultHandler.class).withNoArguments().thenReturn(this.handler); Mockito.doAnswer(new Answer<Object>() { @Override//from ww w . j ava 2s. com public Object answer(InvocationOnMock invocation) throws Throwable { for (int i = 0; i < 5; i++) { CommandLine cli = new CommandLine("echo"); cli.addArgument("iteration: " + i); mockExecutor.execute(cli); Thread.sleep(500); } CommandLine cli = new CommandLine("bash"); cli.addArgument("./src/test/resources/err_output.sh"); mockExecutor.execute(cli); // Here we make sure that the Handler that always gets used always returns 0, and then everything completes OK. handler.onProcessComplete(0); return null; } }).when(mockExecutor).execute(any(CommandLine.class), any(ExecuteResultHandler.class)); PowerMockito.whenNew(DefaultExecutor.class).withNoArguments().thenReturn(mockExecutor); setupConfig(); Job j = new Job(); j.setWorkflowPath("/workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0"); j.setWorkflow("HelloWorld"); j.setWorkflowVersion("1.0-SNAPSHOT"); j.setJobHash("asdlk2390aso12jvrej"); j.setUuid("1234567890"); Map<String, String> iniMap = new HashMap<>(3); iniMap.put("param1", "value1"); iniMap.put("param2", "value2"); iniMap.put("param3", "help I'm trapped in an INI file"); j.setIni(iniMap); byte[] body = j.toJSON().getBytes(); Delivery testDelivery = new Delivery(mockEnvelope, mockProperties, body); Mockito.when(mockConsumer.nextDelivery()).thenReturn(testDelivery); PowerMockito.whenNew(QueueingConsumer.class).withArguments(mockChannel).thenReturn(mockConsumer); WorkerRunnable testWorker = new WorkerRunnable("src/test/resources/workerConfig.ini", "vm123456", 1); testWorker.run(); // String testResults = TestWorkerWithMocking.outBuffer.toString();// this.outStream.toString(); Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); List<LoggingEvent> tmpList = new LinkedList<LoggingEvent>(argCaptor.getAllValues()); String testResults = this.appendEventsIntoString(tmpList); testResults = cleanResults(testResults); // System.out.println("\n===============================\nTest Results: " + testResults); // System.out.println(testResults); String expectedDockerCommand = "docker run --rm -h master -t -v /var/run/docker.sock:/var/run/docker.sock -v /workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0:/workflow -v /tmp/seqware_tmpfile.ini:/ini -v /datastore:/datastore -v /home/$USER/.gnos:/home/$USER/.gnos -v /home/$USER/custom-seqware-settings:/home/seqware/.seqware/settings pancancer/seqware_whitestar_pancancer:1.2.3.4 seqware bundle launch --dir /workflow --ini /ini --no-metadata --engine whitestar"; // System.out.println(expectedDockerCommand); assertTrue("Check for docker command, got " + testResults, testResults.contains(expectedDockerCommand)); assertTrue("Check for sleep message in the following:" + testResults, testResults.contains("Sleeping before executing workflow for 1000 ms.")); assertTrue("Check for workflow complete", testResults.contains("Docker execution result: \"iteration: 0\"\n" + "\"iteration: 1\"\n" + "\"iteration: 2\"\n" + "\"iteration: 3\"\n" + "\"iteration: 4\"\n")); String begining = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_Start.txt"))); assertTrue("check begining of output:" + StringUtils.difference(begining, testResults), testResults.contains(begining)); assertTrue("check INI: " + testResults, testResults.contains("param1=value1") && testResults.contains("param2=value2") && testResults.contains("param3=help I'm trapped in an INI file")); String ending = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_End.txt"))); assertTrue("check ending of output", testResults.contains(ending)); String initalHeartbeat = new String( Files.readAllBytes(Paths.get("src/test/resources/testInitialHeartbeat.txt"))); assertTrue("Check for an initial heart beat, found" + testResults, testResults.contains(initalHeartbeat)); assertTrue("check for stderr in heartbeat", testResults.contains("\"stderr\": \"123_err\",")); }
From source file:io.undertow.server.handlers.accesslog.AccessLogFileTestCase.java
@Test public void testForcedLogRotation() throws IOException, InterruptedException { Path logFileName = logDirectory.resolve("server.log"); DefaultAccessLogReceiver logReceiver = new DefaultAccessLogReceiver(DefaultServer.getWorker(), logDirectory, "server."); CompletionLatchHandler latchHandler; DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(new AccessLogHandler(HELLO_HANDLER, logReceiver, "Remote address %a Code %s test-header %{i,test-header}", AccessLogFileTestCase.class.getClassLoader()))); TestHttpClient client = new TestHttpClient(); try {/* w w w .j a va 2s .co m*/ HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); get.addHeader("test-header", "v1"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Hello", HttpClientUtils.readResponse(result)); latchHandler.await(); latchHandler.reset(); logReceiver.awaitWrittenForTest(); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header v1\n", new String(Files.readAllBytes(logFileName))); logReceiver.rotate(); logReceiver.awaitWrittenForTest(); Assert.assertFalse(Files.exists(logFileName)); Path firstLogRotate = logDirectory .resolve("server." + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".log"); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header v1\n", new String(Files.readAllBytes(firstLogRotate))); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); get.addHeader("test-header", "v2"); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Hello", HttpClientUtils.readResponse(result)); latchHandler.await(); latchHandler.reset(); logReceiver.awaitWrittenForTest(); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header v2\n", new String(Files.readAllBytes(logFileName))); logReceiver.rotate(); logReceiver.awaitWrittenForTest(); Assert.assertFalse(Files.exists(logFileName)); Path secondLogRotate = logDirectory .resolve("server." + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "-1.log"); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header v2\n", new String(Files.readAllBytes(secondLogRotate))); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.apache.drill.test.framework.Utils.java
private static TestCaseModeler getTestCaseModeler(String testDefFile) throws IOException { byte[] jsonData = Files.readAllBytes(Paths.get(testDefFile)); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(new String(jsonData), TestCaseModeler.class); }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }//from w ww . j a v a 2 s . c o m }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:com.team3637.service.TeamServiceMySQLImpl.java
@Override public void importCSV(String inputFile) { try {//from ww w . j a va 2 s . c om String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile))); csvData = csvData.replaceAll("\\r", ""); CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n")); for (CSVRecord record : parser) { Team team = new Team(); team.setId(Integer.parseInt(record.get(0))); team.setTeam(Integer.parseInt(record.get(1))); team.setAvgscore(Double.parseDouble(record.get(2))); team.setMatches(Integer.parseInt(record.get(3))); String[] tags = record.get(4).substring(1, record.get(4).length() - 1).split(","); for (int i = 0; i < tags.length; i++) tags[i] = tags[i].trim(); if (tags.length > 0 && !tags[0].equals("")) team.setTags(Arrays.asList(tags)); else team.setTags(new ArrayList<String>()); if (checkForTeam(team.getTeam())) update(team); else create(team); } } catch (IOException e) { e.printStackTrace(); } }
From source file:ch.unibas.charmmtools.generate.inputs.CHARMM_Generator_DGHydr.java
@Override public String getText() { String content = ""; try {/* www. j a v a2s .co m*/ content = new String(Files.readAllBytes(Paths.get(output.getAbsolutePath()))); } catch (IOException ex) { logger.error("Error while reading simulation output file : " + ex); } return content; }
From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java
protected void createStableZip(ZipOutputStream zipOS, Path parentDirectory, Path archiveRoot, MessageDigest md) throws IOException { // Sort & zip files final List<Path> childDirectories = new ArrayList<>(); final List<Path> childFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDirectory); for (Path eachChild : dirStream) { if (Files.isDirectory(eachChild)) { childDirectories.add(eachChild); } else {/* w w w. j a v a2 s . com*/ childFiles.add(eachChild); } } final int archiveRootLength = archiveRoot.toAbsolutePath().toString().length() + 1; childFiles.stream().sorted().forEach(eachPath -> { final String zeName = eachPath.toAbsolutePath().toString().substring(archiveRootLength); try { final ZipEntry ze = new ZipEntry(zeName); zipOS.putNextEntry(ze); Files.copy(eachPath, zipOS); md.update(Files.readAllBytes(eachPath)); zipOS.closeEntry(); } catch (IOException ex) { throw new RuntimeException(ex.getMessage()); } }); childDirectories.stream().sorted().forEach(eachPath -> { try { createStableZip(zipOS, eachPath, archiveRoot, md); } catch (IOException ex) { throw new RuntimeException(ex.getMessage()); } }); }
From source file:com.epam.wilma.extras.shortcircuit.ShortCircuitResponseInformationFileHandler.java
private String loadFileToString(final String fileName) { String text;/*from w w w.ja va 2 s. c o m*/ try { //CHECKSTYLE OFF - ignoring new String() error, as this is the most effective implementation text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8); //CHECKSTYLE ON } catch (IOException e) { //cannot read a file text = null; } return text; }
From source file:org.jetbrains.webdemo.examples.ExamplesLoader.java
private static ExampleFile loadExampleFile(String path, String projectUrl, JsonNode fileManifest) throws IOException { try {//w w w . j a v a 2 s. c o m String fileName = fileManifest.get("filename").textValue(); boolean modifiable = fileManifest.get("modifiable").asBoolean(); boolean hidden = fileManifest.has("hidden") ? fileManifest.get("hidden").asBoolean() : false; String confType = fileManifest.has("confType") ? fileManifest.get("confType").asText() : null; File file = new File(path); String fileContent = new String(Files.readAllBytes(file.toPath())).replaceAll("\r\n", "\n"); String filePublicId = (projectUrl + "/" + fileName).replaceAll(" ", "%20"); ProjectFile.Type fileType = null; if (!fileManifest.has("type")) { fileType = ProjectFile.Type.KOTLIN_FILE; } else if (fileManifest.get("type").asText().equals("kotlin-test")) { fileType = ProjectFile.Type.KOTLIN_TEST_FILE; } else if (fileManifest.get("type").asText().equals("solution")) { fileType = ProjectFile.Type.SOLUTION_FILE; } else if (fileManifest.get("type").asText().equals("java")) { fileType = ProjectFile.Type.JAVA_FILE; } return new ExampleFile(fileName, fileContent, filePublicId, fileType, confType, modifiable, hidden); } catch (IOException e) { System.err.println("Can't load file: " + e.toString()); return null; } }