List of usage examples for java.nio.file Files newBufferedReader
public static BufferedReader newBufferedReader(Path path, Charset cs) throws IOException
From source file:com.iitb.cse.Utils.java
public static boolean startExperiment(int expId, String timeout, String logBgTraffic) { File file = null;/* ww w. j a va 2s . c o m*/ File file1 = null; if (Constants.experimentDetailsDirectory.endsWith("/")) { file = new File(Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile); file1 = new File( Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()); } else { file = new File(Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile); file1 = new File( Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId()); } if (file.exists()) { Charset charset = Charset.forName("UTF-8"); String line = null; String[] data = new String[1000];// int index = 0; data[index] = ""; try { BufferedReader reader = Files.newBufferedReader(file.toPath(), charset); Calendar cal = Calendar.getInstance(); while ((line = reader.readLine()) != null) { System.out.println("\nLENGTH : " + line.length()); if (line.isEmpty() || line.trim().equals("")) { System.out.println("\nCASE1"); continue; } else if (line.trim().equals("*****\n")) { System.out.println("\nCASE2"); data[index] = expId + "\n" + data[index]; index++; data[index] = ""; continue; } else if (line.trim().equals("*****")) { System.out.println("\nCASE3"); data[index] = expId + "\n" + data[index]; index++; data[index] = ""; continue; } String[] lineVariables = line.split(" "); // int offset = Integer.parseInt(lineVariables[1]); // cal.add(Calendar.SECOND, offset); //**************************************************** double time = Double.parseDouble(lineVariables[1]); int sec = (int) time; double rem = time % 1; int remainder = (int) (rem * 1000); // Calendar cal = Calendar.getInstance(); // System.out.println("\nSec : " + sec + "\nMiSec : " + remainder + "\nTime : " + cal.getTime()); int flag = 0; if (remainder < 100) { flag = 1; remainder = remainder + 100; cal.add(Calendar.SECOND, sec); cal.add(Calendar.MILLISECOND, remainder); cal.add(Calendar.MILLISECOND, -100); } else { cal.add(Calendar.SECOND, sec); cal.add(Calendar.MILLISECOND, remainder); } //**************************************************** if (lineVariables.length == 5) { // System.out.println("\nINSIDE"); data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3], lineVariables[4]); } else { // System.out.println("\nOUTSIDE"); data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3]); } if (flag == 1) { cal.add(Calendar.SECOND, -1 * sec); cal.add(Calendar.MILLISECOND, -1 * remainder); cal.add(Calendar.MILLISECOND, 100); } else { cal.add(Calendar.SECOND, -1 * sec); cal.add(Calendar.MILLISECOND, -1 * remainder); } } data[index] = expId + "\n" + data[index]; } catch (IOException ex) { System.out.println(ex.toString()); return false; } int controlFileIndex = 0; for (DeviceInfo d : Constants.currentSession.getFilteredClients()) { if (controlFileIndex >= Constants.currentSession.getFilteredClients().size()) { break; } else if (data[controlFileIndex] != null) { String jsonString = Utils.getControlFileJson(data[controlFileIndex], timeout, logBgTraffic); System.out.println("\njsonString : " + jsonString); System.out.println("\nControl FIle : " + data[controlFileIndex]); /* Locally keep the corresponding control file to each client*/ PrintWriter writer; try { writer = new PrintWriter(file1 + "/" + d.macAddress + "_confFile"); writer.write(data[controlFileIndex]); writer.flush(); writer.close(); } catch (FileNotFoundException ex) { System.out.println("\nException : " + ex.toString()); } //writer.close(); System.out.println("\nDevice Info : IP " + d.ip + " Port " + d.port + " Mac " + d.macAddress); Thread sendData = new Thread(new SendData(expId, d, 0, jsonString, data[controlFileIndex])); sendData.start(); } else { break; } controlFileIndex++; } } else { System.out.println("\nConfig FIle not found in location : " + Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()); } return true; }
From source file:org.apache.lucene.benchmark.byTask.tasks.WriteLineDocTaskTest.java
public void testMultiThreaded() throws Exception { Path file = getWorkDir().resolve("one-line"); PerfRunData runData = createPerfRunData(file, false, ThreadingDocMaker.class.getName()); final WriteLineDocTask wldt = new WriteLineDocTask(runData); Thread[] threads = new Thread[10]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread("t" + i) { @Override//w w w. ja v a 2 s. co m public void run() { try { wldt.doLogic(); } catch (Exception e) { throw new RuntimeException(e); } } }; } for (Thread t : threads) t.start(); for (Thread t : threads) t.join(); wldt.close(); Set<String> ids = new HashSet<>(); try (BufferedReader br = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { String line = br.readLine(); assertHeaderLine(line); // header line is written once, no matter how many threads there are for (int i = 0; i < threads.length; i++) { line = br.readLine(); String[] parts = line.split(Character.toString(WriteLineDocTask.SEP)); assertEquals(3, parts.length); // check that all thread names written are the same in the same line String tname = parts[0].substring(parts[0].indexOf('_')); ids.add(tname); assertEquals(tname, parts[1].substring(parts[1].indexOf('_'))); assertEquals(tname, parts[2].substring(parts[2].indexOf('_'))); } // only threads.length lines should exist assertNull(br.readLine()); assertEquals(threads.length, ids.size()); } }
From source file:com.github.anba.es6draft.util.Resources.java
private static <T extends TestInfo> Function<Path, T> mapper(BiFunction<Path, Iterator<String>, T> fn) { return file -> { try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { return fn.apply(file, new LineIterator(reader)); } catch (IOException e) { throw new UncheckedIOException(e); }//from w w w . j a v a 2s .c om }; }
From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java
/** * Create a JavaScript engine packed with given scripts. If two scripts have methods with same name, * later method will override the previous method. * * @param domain//from w w w . ja v a 2 s.c o m * @return JavaScript engine * @throws TemplateDeploymentException if there are any errors in JavaScript evaluation */ public static ScriptEngine createJavaScriptEngine(Domain domain) throws TemplateDeploymentException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager .getEngineByName(TemplateManagerConstants.JAVASCRIPT_ENGINE_NAME); if (scriptEngine == null) { // Exception will be thrown later, only if function calls are used in the template log.warn("JavaScript engine is not available. Function calls in the templates cannot be evaluated"); } else { if (domain != null && domain.getScripts() != null && domain.getScripts().getScript() != null) { Path scriptDirectory = Paths.get(TemplateManagerConstants.TEMPLATE_SCRIPT_PATH); if (Files.exists(scriptDirectory, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(scriptDirectory)) { for (Script script : domain.getScripts().getScript()) { String src = script.getSrc(); String content = script.getContent(); if (src != null) { // Evaluate JavaScript file Path scriptFile = scriptDirectory.resolve(src).normalize(); if (Files.exists(scriptFile, LinkOption.NOFOLLOW_LINKS) && Files.isReadable(scriptFile)) { if (!scriptFile.startsWith(scriptDirectory)) { // The script file is not in the permitted directory throw new TemplateDeploymentException("Script file " + scriptFile.toAbsolutePath() + " is not in the permitted directory " + scriptDirectory.toAbsolutePath()); } try { scriptEngine .eval(Files.newBufferedReader(scriptFile, Charset.defaultCharset())); } catch (ScriptException e) { throw new TemplateDeploymentException("Error in JavaScript " + scriptFile.toAbsolutePath() + ": " + e.getMessage(), e); } catch (IOException e) { throw new TemplateDeploymentException( "Error in reading JavaScript file: " + scriptFile.toAbsolutePath()); } } else { throw new TemplateDeploymentException("JavaScript file not exist at: " + scriptFile.toAbsolutePath() + " or not readable."); } } if (content != null) { // Evaluate JavaScript content try { scriptEngine.eval(content); } catch (ScriptException e) { throw new TemplateDeploymentException( "JavaScript declared in " + domain.getName() + " has error", e); } } } } else { log.warn("Script directory not found at: " + scriptDirectory.toAbsolutePath()); } } } return scriptEngine; }
From source file:org.jboss.as.test.integration.security.auditing.CustomAuditProviderModuleTest.java
@Test public void testBaduser1() throws Exception { /*// w ww. j a va2s .co m * baduser1 can authenticate, because we use the correct password, but he does not have the "gooduser" role required by * SecuredServlet and the server thus return 403 rather than 401 */ assertResponse(CustomLoginModule1.BADUSER1_USERNAME, CustomLoginModule1.BADUSER1_PASSWORD, 403); try (BufferedReader r = Files.newBufferedReader(AUDIT_LOG_PATH, UTF_8)) { assertAuditLog(r, Pattern.quote("INFO " + CustomAuditProviderModule.class.getName() + " [Success]principal=" + CustomLoginModule1.BADUSER1_USERNAME + ";")); } }
From source file:org.wso2.carbon.pc.core.transfer.ProcessImport.java
/** * Add the flow chart of imported process into the registry * * @param processName process name//from w w w. j a v a2 s . c om * @param processVersion process version * @param processDirPath process directory path * @param processAssetPath process path * @throws UserStoreException * @throws RegistryException * @throws IOException */ private void setFlowChart(String processName, String processVersion, String processDirPath, String processAssetPath) throws UserStoreException, RegistryException, IOException { UserRegistry reg = registryService.getGovernanceUserRegistry(user); RegPermissionUtil.setPutPermission(registryService, user, ProcessCenterConstants.AUDIT.PROCESS_FLOW_CHART_PATH); Resource flowchartContentResource = reg.newResource(); Path flowChartJSONFilePath = Paths .get(processDirPath + "/" + ProcessCenterConstants.EXPORTED_FLOW_CHART_FILE); if (Files.exists(flowChartJSONFilePath)) { String flowChartFileContent = ""; try (BufferedReader reader = Files.newBufferedReader(flowChartJSONFilePath, Charsets.US_ASCII)) { String line; while ((line = reader.readLine()) != null) { flowChartFileContent += line; } } catch (IOException e) { String errMsg = "Error in reading process's flowChart.json file"; throw new IOException(errMsg, e); } flowchartContentResource.setContent(flowChartFileContent); flowchartContentResource.setMediaType(MediaType.APPLICATION_JSON); String flowchartContentPath = ProcessCenterConstants.PROCESS_CENTER_RESOURCES_PATH + ProcessCenterConstants.PROCESS + "/" + ProcessCenterConstants.FLOW_CHART + "/" + processName + "/" + processVersion; reg.put(flowchartContentPath, flowchartContentResource); //add reg association reg.addAssociation(flowchartContentPath, processAssetPath, ProcessCenterConstants.ASSOCIATION_TYPE); } }
From source file:com.qwazr.server.configuration.ServerConfiguration.java
protected static Map<String, String> argsToMap(final String... args) throws IOException { final Map<String, String> props = argsToMapPrefix("--", args); // Load the QWAZR_PROPERTIES String propertyFile = props.get(QWAZR_PROPERTIES); if (propertyFile == null) propertyFile = System.getProperty(QWAZR_PROPERTIES, System.getenv(QWAZR_PROPERTIES)); if (propertyFile != null) { final Path propFile = Paths.get(propertyFile); LOGGER.info(() -> "Load QWAZR_PROPERTIES file: " + propFile.toAbsolutePath()); final Properties properties = new Properties(); try (final BufferedReader reader = Files.newBufferedReader(propFile, StandardCharsets.UTF_8)) { properties.load(reader);/* w w w .j a v a 2 s . c om*/ } // Priority to program argument, we only put the value if the key is not present properties.forEach((key, value) -> props.putIfAbsent(key.toString(), value.toString())); } return props; }
From source file:org.opencb.opencga.core.common.networks.Layout.java
public LayoutResp coordinates(String layoutAlgorithm, String dotData, String jsonpCallback) { LayoutResp resp = new LayoutResp(); logger.debug("LayoutWSServer: coordinates() method"); if (graphvizLayoutAlgorithms.contains(layoutAlgorithm)) { StringBuilder sb = new StringBuilder("{"); try {//w w w . j a v a 2s.c o m Path randomFolder = Paths .get(properties.getProperty("TMP.FOLDER") + "/" + StringUtils.randomString(20) + "_layout"); logger.debug("Creating output folder: " + randomFolder); Files.createDirectory(randomFolder); // FileUtils.createDirectory(randomFolder); String inputFile = randomFolder + "/input.dot"; String outputFile = randomFolder + "/output.plain"; Path inputPath = Paths.get(inputFile); Path outputPath = Paths.get(outputFile); logger.debug("Writting dot data file: " + inputFile); // IOUtils.write(inputFile, dotData); Files.write(inputPath, dotData.getBytes(), StandardOpenOption.CREATE_NEW); int exitValue = executeGraphviz(new File(inputFile), layoutAlgorithm, "plain", new File(outputFile)); if (exitValue == 0 && Files.exists(outputPath)) { // FileUtils.checkFile(outputFile); // getting the coords form the file // Grep the file BufferedReader br = Files.newBufferedReader(outputPath, Charset.defaultCharset()); final Pattern pattern = Pattern.compile("^node.+"); String currentLine; List<String> lines = new ArrayList<>(); while ((currentLine = br.readLine()) != null) { if (pattern.matcher(currentLine).matches()) { lines.add(currentLine); } } // List<String> lines = IOUtils.grep(new File(outputFile), "^node.+"); String[] fields; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; String[] ids = new String[lines.size()]; double[][] coords = new double[lines.size()][2]; for (int i = 0; i < lines.size(); i++) { fields = lines.get(i).split(" "); ids[i] = fields[1]; coords[i][0] = Double.parseDouble(fields[2]); coords[i][1] = Double.parseDouble(fields[3]); min = Math.min(min, Math.min(coords[i][0], coords[i][1])); max = Math.max(max, Math.max(coords[i][0], coords[i][1])); } // max needs to be calculated after subtract min max -= min; for (int i = 0; i < ids.length; i++) { sb.append("\"" + ids[i] + "\"").append(": {").append("\"id\":\"").append(ids[i]) .append("\", \"x\": ").append((coords[i][0] - min) / max).append(", \"y\": ") .append((coords[i][1] - min) / max).append("}"); if (i < ids.length - 1) { sb.append(", "); } } sb.append("}"); if (jsonpCallback != null && !jsonpCallback.equals("")) { // return Response.ok("var " + jsonpCallback + " = (" + sb.toString() + ")", MediaType.APPLICATION_JSON_TYPE).build(); // return createOkResponse("var " + jsonpCallback + " = (" + sb.toString() + ")", MediaType.APPLICATION_JSON_TYPE); resp.setData("var " + jsonpCallback + " = (" + sb.toString() + ")"); resp.setType("json"); return resp; } else { // return Response.ok(sb.toString(), MediaType.TEXT_PLAIN).build(); // return createOkResponse(sb.toString(), MediaType.TEXT_PLAIN_TYPE); resp.setData(sb.toString()); resp.setType("text"); return resp; } } else { // return Response.ok("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN).build(); // return createOkResponse("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN_TYPE); resp.setData("Graphviz exit status not 0: '" + exitValue + "'"); resp.setType("text"); return resp; } } catch (Exception e) { logger.error("Error in LayoutWSServer, layout() method: " + e); // return Response.ok("Error in LayoutWSServer, coordinates() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN).build(); // return createOkResponse("Error in LayoutWSServer, coordinates() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN_TYPE); resp.setData("Error in LayoutWSServer, coordinates() method:\n" + e); resp.setType("text"); return resp; } } else { // return Response.ok("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN).build(); // return createOkResponse("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN_TYPE); resp.setData("Algorithm '" + layoutAlgorithm + "' is not valid"); resp.setType("text"); return resp; } }
From source file:org.jboss.as.test.integration.security.auditing.CustomAuditProviderModuleTest.java
@Test public void testGooduser1() throws Exception { assertResponse(CustomLoginModule1.GOODUSER1_USERNAME, CustomLoginModule1.GOODUSER1_PASSWORD, 200); try (BufferedReader r = Files.newBufferedReader(AUDIT_LOG_PATH, UTF_8)) { assertAuditLog(r, Pattern.quote("INFO " + CustomAuditProviderModule.class.getName() + " [Success]principal=" + CustomLoginModule1.GOODUSER1_USERNAME + ";")); }//from ww w . j a v a 2 s.c o m }
From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverter.java
private Metadata readMetadata(File file) throws ArtifactConversionException { MetadataXpp3Reader reader = new MetadataXpp3Reader(); try (Reader fileReader = Files.newBufferedReader(file.toPath(), Charset.defaultCharset())) { return reader.read(fileReader); } catch (IOException | XmlPullParserException e) { throw new ArtifactConversionException(Messages.getString("error.reading.target.metadata"), e); //$NON-NLS-1$ }/* w w w .j a v a2s .c o m*/ }