List of usage examples for java.util Scanner hasNextLine
public boolean hasNextLine()
From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java
/** * XNDisc Server ? ? ?/*from w ww . ja v a2 s. c o m*/ * * @return ?? true, false */ private static boolean isXNDiscServerAlive() { boolean isAlive = false; String HOST = XNDiscConfig.getString(XNDiscConfig.HOST, XNDiscConfig.LOCAL_HOST); String PORT = XNDiscConfig.getString(XNDiscConfig.PORT); Scanner scanner = null; ByteArrayOutputStream baos = null; try { String os = System.getProperty("os.name").toLowerCase(); String ostype = (os.contains("windows")) ? "W" : "U"; CommandLine cmdline = new CommandLine("netstat"); cmdline.addArgument("-an"); if (ostype.equals("W")) { cmdline.addArgument("-p"); cmdline.addArgument("\"TCP\""); } else { // UNIX ? ? -an ? ? ? if (XNDiscUtils.isSolaris()) { cmdline.addArgument("-P"); cmdline.addArgument("tcp"); } else if (XNDiscUtils.isAix()) { cmdline.addArgument("-p"); cmdline.addArgument("TCP"); } } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); baos = new ByteArrayOutputStream(); PumpStreamHandler sh = new PumpStreamHandler(baos); executor.setStreamHandler(sh); executor.execute(cmdline); String str = baos.toString(); if (str != null && str.length() > 0) { // ? XNDisc alive ?(XNDisc Server ? ?) scanner = new Scanner(str); while (scanner.hasNextLine()) { String readline = scanner.nextLine(); if (readline.contains(HOST) && readline.contains(PORT) && readline.contains(XNDISC_LISTEN_STATUS)) { isAlive = true; break; } } } } catch (Exception e) { e.printStackTrace(); isAlive = false; } finally { try { if (scanner != null) { scanner.close(); } if (baos != null) { baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return isAlive; }
From source file:edu.ucuenca.authorsdisambiguation.Distance.java
public synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException { String md = s + mp.toString(); Statement stmt = conn.createStatement(); String sql;/*from w w w . j av a 2s. co m*/ sql = "SELECT * FROM cache where cache.key='" + getMD5(md) + "'"; java.sql.ResultSet rs = stmt.executeQuery(sql); String resp = ""; if (rs.next()) { resp = rs.getString("value"); rs.close(); stmt.close(); } else { rs.close(); stmt.close(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(s); //Add any parameter if u want to send it with Post req. for (Entry<String, String> mcc : mp.entrySet()) { method.addParameter(mcc.getKey(), mcc.getValue()); } int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream in = method.getResponseBodyAsStream(); final Scanner reader = new Scanner(in, "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); try { JsonParser parser = new JsonParser(); parser.parse(resp); PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)"); stmt2.setString(1, getMD5(md)); stmt2.setString(2, resp); stmt2.executeUpdate(); stmt2.close(); } catch (Exception e) { System.out.printf("Error al insertar en la DB: " + e); } } } return resp; }
From source file:ca.weblite.codename1.ios.CodenameOneIOSBuildTask.java
/** * Based on https://github.com/shannah/cn1/blob/master/Ports/iOSPort/xmlvm/src/xmlvm/org/xmlvm/proc/out/build/XCodeFile.java * @param template//from w w w .j ava2s. c o m * @param filter */ private String injectFilesIntoXcodeProject(String template, File[] files) { int nextid = 0; Pattern idPattern = Pattern.compile(" (\\d+) "); Matcher m = idPattern.matcher(template); while (m.find()) { int curr = Integer.parseInt(m.group(1)); if (curr > nextid) { nextid = curr; } } nextid++; StringBuilder filerefs = new StringBuilder(); StringBuilder buildrefs = new StringBuilder(); StringBuilder display = new StringBuilder(); StringBuilder source = new StringBuilder(); StringBuilder resource = new StringBuilder(); for (File f : files) { String fname = f.getName(); if (template.indexOf(" " + fname + " ") >= 0) { continue; } FileResource fres = new FileResource(fname); if (f.exists()) { filerefs.append("\t\t").append(nextid); filerefs.append(" /* ").append(fname).append(" */"); filerefs.append(" = { isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = "); filerefs.append(fres.type).append("; path = \""); filerefs.append(fname).append("\"; sourceTree = \"<group>\"; };"); filerefs.append('\n'); display.append("\t\t\t\t").append(nextid); display.append(" /* ").append(fname).append(" */"); display.append(",\n"); if (fres.isBuildable) { int fileid = nextid; nextid++; buildrefs.append("\t\t").append(nextid); buildrefs.append(" /* ").append(fname); buildrefs.append(" in ").append(fres.isSource ? "Sources" : "Resources"); buildrefs.append(" */ = {isa = PBXBuildFile; fileRef = ").append(fileid); buildrefs.append(" /* ").append(fname); buildrefs.append(" */; };\n"); if (fres.isSource) { source.append("\t\t\t\t").append(nextid); source.append(" /* ").append(fname).append(" */"); source.append(",\n"); } } nextid++; } } String data = template; data = data.replace("/* End PBXFileReference section */", filerefs.toString() + "/* End PBXFileReference section */"); data = data.replace("/* End PBXBuildFile section */", buildrefs.toString() + "/* End PBXBuildFile section */"); // The next two we probably shouldn't do by regex because there is no clear pattern. Stack<String> buffer = new Stack<String>(); Stack<String> backtrackStack = new Stack<String>(); Scanner scanner = new Scanner(data); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.indexOf("/* End PBXSourcesBuildPhase section */") >= 0) { // Found the end, let's backtrack while (!buffer.isEmpty()) { String l = buffer.pop(); backtrackStack.push(l); if (");".equals(l.trim())) { // This is the closing of the sources list // we can insert the sources here buffer.push(source.toString()); while (!backtrackStack.isEmpty()) { buffer.push(backtrackStack.pop()); } break; } } } else if (line.indexOf("name = Application;") >= 0) { while (!buffer.isEmpty()) { String l = buffer.pop(); backtrackStack.push(l); if (");".equals(l.trim())) { buffer.push(display.toString()); while (!backtrackStack.isEmpty()) { buffer.push(backtrackStack.pop()); } break; } } } buffer.push(line); } StringBuilder sb = new StringBuilder(); String[] lines = buffer.toArray(new String[0]); for (String line : lines) { sb.append(line).append("\n"); } data = sb.toString(); return data; }
From source file:edu.ucuenca.authorsdisambiguation.Distance.java
public synchronized String Http(String s) throws SQLException, IOException { Statement stmt = conn.createStatement(); String sql;/* ww w .java 2s . co m*/ sql = "SELECT * FROM cache where cache.key='" + getMD5(s) + "'"; java.sql.ResultSet rs = stmt.executeQuery(sql); String resp = ""; if (rs.next()) { resp = rs.getString("value"); rs.close(); stmt.close(); } else { rs.close(); stmt.close(); final URL url = new URL(s); final URLConnection connection = url.openConnection(); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); connection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0"); connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); try { JsonParser parser = new JsonParser(); parser.parse(resp); PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)"); stmt2.setString(1, getMD5(s)); stmt2.setString(2, resp); stmt2.executeUpdate(); stmt2.close(); } catch (Exception e) { System.out.printf("Error al insertar en la DB: " + e); } } return resp; }
From source file:org.eclipse.kura.net.admin.visitor.linux.IfcfgConfigWriter.java
private void writeDebianConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { StringBuffer sb = new StringBuffer(); File kuraFile = new File(DEBIAN_NET_CONFIGURATION_FILE); String iName = netInterfaceConfig.getName(); boolean appendConfig = true; if (kuraFile.exists()) { // found our match so load the properties Scanner scanner = null; try {// w ww .j a va 2 s .co m scanner = new Scanner(new FileInputStream(kuraFile)); // need to loop through the existing file and replace only the desired interface while (scanner.hasNextLine()) { String noTrimLine = scanner.nextLine(); String line = noTrimLine.trim(); // ignore comments and blank lines if (!line.isEmpty()) { if (line.startsWith("#!kura!")) { line = line.substring("#!kura!".length()); } if (!line.startsWith("#")) { String[] args = line.split("\\s+"); // must be a line stating that interface starts on boot if (args.length > 1) { if (args[1].equals(iName)) { s_logger.debug("Found entry in interface file..."); appendConfig = false; sb.append(debianWriteUtility(netInterfaceConfig, iName)); // remove old config lines from the scanner while (scanner.hasNextLine() && !(line = scanner.nextLine()).isEmpty()) { } sb.append("\n"); } else { sb.append(noTrimLine + "\n"); } } } else { sb.append(noTrimLine + "\n"); } } else { sb.append(noTrimLine + "\n"); } } } catch (FileNotFoundException e1) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e1); } finally { scanner.close(); scanner = null; } // If config not present in file, append to end if (appendConfig) { s_logger.debug("Appending entry to interface file..."); // append an empty line if not there String s = sb.toString(); if (!"\\n".equals(s.substring(s.length() - 1))) { sb.append("\n"); } sb.append(debianWriteUtility(netInterfaceConfig, iName)); sb.append("\n"); } FileOutputStream fos = null; PrintWriter pw = null; try { fos = new FileOutputStream(DEBIAN_TMP_NET_CONFIGURATION_FILE); pw = new PrintWriter(fos); pw.write(sb.toString()); pw.flush(); fos.getFD().sync(); } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ex) { s_logger.error("I/O Exception while closing BufferedReader!"); } } if (pw != null) { pw.close(); } } // move the file if we made it this far File tmpFile = new File(DEBIAN_TMP_NET_CONFIGURATION_FILE); File file = new File(DEBIAN_NET_CONFIGURATION_FILE); try { if (!FileUtils.contentEquals(tmpFile, file)) { if (tmpFile.renameTo(file)) { s_logger.trace("Successfully wrote network interfaces file"); } else { s_logger.error("Failed to write network interfaces file"); throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, "error while building up new configuration file for network interfaces"); } } else { s_logger.info("Not rewriting network interfaces file because it is the same"); } } catch (IOException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } }
From source file:org.goko.controller.grbl.v08.GrblControllerService.java
/** (inheritDoc) * @see org.goko.core.controller.IControllerConfigurationFileImporter#importFrom(java.io.InputStream) *//* w w w . j a v a 2s .co m*/ @Override public void importFrom(InputStream inputStream) throws GkException { GrblConfiguration cfg = getConfiguration(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] tokens = line.split("="); if (tokens != null && tokens.length == 2) { cfg.setValue(tokens[0], tokens[1]); } else { LOG.warn("Ignoring configuration line [" + line + "] because it's malformatted."); } } scanner.close(); setConfiguration(cfg); }
From source file:ca.weblite.codename1.ios.CodenameOneIOSBuildTask.java
/** * Gets a list of the XMLVM generated files that are currently registered * in the Xcode project.//from w w w.ja v a 2s . com */ protected Set<String> getCurrentXcodeFiles(String pbxprojContent) { Set<String> out = new HashSet<String>(); Scanner scanner = new Scanner(pbxprojContent); int state = 0; Pattern regex = Pattern.compile("\\d+ /\\* ([^ ]+) \\*/"); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (state == 0 && line.indexOf("/* Application */ = {") >= 0) { state = 1; } else if (state == 1) { Matcher m = regex.matcher(line); if (m.find()) { String path = m.group(1); if (path.indexOf("/") < 0) { out.add(path); } } else if (");".equals(line.trim())) { return out; } } } throw new RuntimeException("Could not find the end of the file reference section"); }
From source file:edu.cmu.lti.oaqa.framework.eval.gs.PassageGoldStandardFilePersistenceProvider.java
@Override public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { boolean ret = super.initialize(aSpecifier, aAdditionalParams); String dataset = (String) getParameterValue("DataSet"); Pattern lineSyntaxPattern = Pattern.compile((String) getParameterValue("LineSyntax")); try {//from ww w .j a va2 s .c o m Resource[] resources = resolver.getResources((String) getParameterValue("PathPattern")); for (Resource resource : resources) { Scanner scanner = new Scanner(resource.getInputStream()); while (scanner.findInLine(lineSyntaxPattern) != null) { MatchResult result = scanner.match(); DatasetSequenceId id = new DatasetSequenceId(dataset, result.group(1)); List<GoldStandardSpan> list = id2gsSpans.get(id); if (list == null) { list = new ArrayList<GoldStandardSpan>(); id2gsSpans.put(id, list); } GoldStandardSpan annotation = new GoldStandardSpan(result.group(2), Integer.parseInt(result.group(3)), Integer.parseInt(result.group(4)), result.group(5)); list.add(annotation); if (scanner.hasNextLine()) { scanner.nextLine(); } else { break; } } scanner.close(); } } catch (IOException e) { e.printStackTrace(); } return ret; }
From source file:com.joliciel.csvLearner.CSVEventListReader.java
private void scanCSVFile(InputStream inputStream, boolean closeStreamer, boolean grouped, String fileName, Map<String, GenericEvent> currentEventMap) { // add contents of the current file to the event map. if (grouped)/*from w w w. ja v a 2s. c om*/ this.groupedFiles.add(fileName); boolean firstLine = true; List<String> featureNames = null; Scanner scanner = new Scanner(inputStream, "UTF-8"); Set<String> featureSet = fileToFeatureMap.get(fileName); if (featureSet == null) { featureSet = new TreeSet<String>(); fileToFeatureMap.put(fileName, featureSet); } try { int row = 1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); List<String> cells = CSVFormatter.getCSVCells(line); if (firstLine) { featureNames = new ArrayList<String>(); for (String cell : cells) { String featureName = cell.replace(' ', '_'); featureName = featureName.replace(",", "$comma$"); featureName = featureName.replace("\"", "$double_quote$"); featureNames.add(featureName); } boolean firstColumn = true; for (String featureName : featureNames) { if (!firstColumn) { features.add(featureName); featureSet.add(featureName); if (grouped) groupedFeatures.put(featureName, fileName); featureToFileMap.put(featureName, fileName); } if (firstColumn) firstColumn = false; } firstLine = false; } else { boolean firstCell = true; GenericEvent event = null; int i = 0; for (String cell : cells) { if (firstCell) { String ref = cell; if (this.eventsToExclude.contains(ref)) { // skip this whole line break; } event = currentEventMap.get(ref); if (event == null) { if (resultFilePath != null) { if (skipUnknownEvents) { // unknown ID: skip this whole line break; } else { throw new RuntimeException("ID not found in result file: " + cell); } } else { event = new GenericEvent(ref); event.setTest(true); currentEventMap.put(ref, event); } } firstCell = false; } else { // weight cell if (i > featureNames.size() - 1) throw new RuntimeException("File: " + fileName + ". Too many cells on row: " + row); String featureName = featureNames.get(i); if (this.featuresToInclude != null && !this.featuresToInclude.contains(featureName)) { i++; continue; } float weight = 0; try { weight = Float.parseFloat(cell); } catch (NumberFormatException nfe) { // skip empty cells if (cell.length() > 0) { featureName += CSVLearner.NOMINAL_MARKER + cell; weight = 1; } } FeatureStats featureStats = this.featureStatsMap.get(featureName); if (featureStats == null) { featureStats = new FeatureStats(); this.featureStatsMap.put(featureName, featureStats); } // skip cells with an explicit weight of zero if (weight > 0) { event.addFeature(featureName, weight); if (weight > featureStats.max) featureStats.max = weight; featureStats.count = featureStats.count + 1; featureStats.total = featureStats.total + weight; } } // type of cell i++; } // next cell } // first line? row++; } // next line } finally { if (closeStreamer) scanner.close(); } }
From source file:org.ala.spatial.web.services.GDMWSController.java
@RequestMapping(value = "/step1", method = RequestMethod.POST) public @ResponseBody String processStep1(HttpServletRequest req) { try {//www. ja v a 2 s .c o m String outputdir = ""; long currTime = System.currentTimeMillis(); String envlist = req.getParameter("envlist"); //String speciesdata = req.getParameter("speciesdata"); String area = req.getParameter("area"); String taxacount = req.getParameter("taxacount"); String bs = req.getParameter("bs"); String speciesq = req.getParameter("speciesq"); OccurrenceData od = new OccurrenceData(); String[] s = od.getSpeciesData(speciesq, bs, null); String speciesdata = s[0]; //Layer[] layers = getEnvFilesAsLayers(envlist); LayerFilter[] filter = null; SimpleRegion region = null; if (area != null && area.startsWith("ENVELOPE")) { filter = LayerFilter.parseLayerFilters(area); } else { region = SimpleShapeFile.parseWKT(area); } // 1. create work/output directory //outputdir = TabulationSettings.base_output_dir + currTime + "/"; outputdir = AlaspatialProperties.getBaseOutputDir() + "output" + File.separator + "gdm" + File.separator + currTime + File.separator; File outdir = new File(outputdir); outdir.mkdirs(); System.out.println("gdm.outputpath: " + outputdir); // 2. generate species file //String speciesFile = generateSpeciesFile(outputdir, taxons, region); String speciesFile = generateSpeciesFile(outputdir, speciesdata); System.out.println("gdm.speciesFile: " + speciesFile); // 3. cut environmental layers //String cutDataPath = GridCutter.cut(layers, region, filter, null); //SpatialSettings ssets = new SpatialSettings(); //String cutDataPath = ssets.getEnvDataPath(); String resolution = req.getParameter("res"); if (resolution == null) { resolution = "0.01"; } String cutDataPath = GridCutter.cut2(envlist.split(":"), resolution, region, filter, null); System.out.println("CUTDATAPATH: " + region + " " + cutDataPath); System.out.println("gdm.cutDataPath: " + cutDataPath); // 4. produce domain grid //DomainGrid.generate(cutDataPath, layers, region, outputdir); // 5. build parameters files for GDM String params = generateStep1Paramfile(envlist.split(":"), cutDataPath, speciesFile, outputdir); // 6. run GDM int exit = runGDM(1, params); System.out.println("gdm.exit: " + exit); String output = ""; output += Long.toString(currTime) + "\n"; // BufferedReader cutpoint = new BufferedReader(new FileReader(outputdir + "Cutpoint.csv")); // String line = ""; // while ((line = cutpoint.readLine()) != null) { // output += line; // } Scanner sc = new Scanner(new File(outputdir + "Cutpoint.csv")); while (sc.hasNextLine()) { output += sc.nextLine() + "\n"; } // write the properties to a file so we can grab them back later Properties props = new Properties(); props.setProperty("pid", Long.toString(currTime)); props.setProperty("envlist", envlist); props.setProperty("area", area); props.setProperty("taxacount", taxacount); //props.store(new PrintWriter(new BufferedWriter(new FileWriter(outputdir + "ala.properties"))), ""); props.store(new FileOutputStream(outputdir + "ala.properties"), "ALA GDM Properties"); return output; } catch (Exception e) { System.out.println("Error processing gdm request"); e.printStackTrace(System.out); } return ""; }