List of usage examples for java.io LineNumberReader LineNumberReader
public LineNumberReader(Reader in)
From source file:com.quartzdesk.executor.common.db.DatabaseScriptExecutor.java
/** * Read a script from the given resource and build a String containing the lines. * * @param scriptUrl the SQL script URL to be read from. * @return {@code String} containing the script lines. * @throws IOException in case of I/O errors. *//* w w w. jav a 2 s .c om*/ private String readScript(URL scriptUrl) throws IOException { String statementSeparatorStart = commentPrefix + ' ' + STATEMENT_SEPARATOR_START; String statementSeparatorEnd = commentPrefix + ' ' + STATEMENT_SEPARATOR_END; LineNumberReader lnr = new LineNumberReader( new InputStreamReader(scriptUrl.openStream(), sqlScriptEncoding)); try { String currentStatement = lnr.readLine(); StringBuilder scriptBuilder = new StringBuilder(); while (currentStatement != null) { if (StringUtils.isNotBlank(currentStatement)) { if (commentPrefix != null && !currentStatement.startsWith(commentPrefix)) { if (scriptBuilder.length() > 0) { scriptBuilder.append('\n'); } scriptBuilder.append(currentStatement); } if (commentPrefix != null && (currentStatement.startsWith(statementSeparatorStart) || currentStatement.startsWith(statementSeparatorEnd))) { if (scriptBuilder.length() > 0) { scriptBuilder.append('\n'); } scriptBuilder.append(currentStatement); } } currentStatement = lnr.readLine(); } maybeAddSeparatorToScript(scriptBuilder); return scriptBuilder.toString(); } finally { IOUtils.close(lnr); } }
From source file:com.l2jfree.gameserver.instancemanager.leaderboards.ArenaManager.java
public void engineInit() { _ranks = new FastMap<Integer, ArenaRank>(); String line = null;/* w ww .j a va2s .com*/ LineNumberReader lnr = null; String lineId = ""; ArenaRank rank = null; File file = new File(Config.DATAPACK_ROOT, "data/arena.dat"); try { boolean created = file.createNewFile(); if (created) _log.info("ArenaManager: arena.dat was not existing and has been created."); } catch (IOException e) { e.printStackTrace(); } finally { try { lnr = new LineNumberReader(new BufferedReader(new FileReader(file))); while ((line = lnr.readLine()) != null) { if (line.trim().length() == 0 || line.startsWith("#")) continue; lineId = line; line = line.replaceAll(" ", ""); String t[] = line.split(":"); int owner = Integer.parseInt(t[0]); rank = new ArenaRank(); rank.kills = Integer.parseInt(t[1].split("-")[0]); rank.death = Integer.parseInt(t[1].split("-")[1]); rank.name = t[2]; _ranks.put(owner, rank); } } catch (Exception e) { _log.warn("ArenaManager.engineInit() >> last line parsed is \n[" + lineId + "]\n", e); } finally { IOUtils.closeQuietly(lnr); } startSaveTask(); _log.info("ArenaManager: Loaded " + _ranks.size() + " player(s)."); } }
From source file:com.github.magicsky.sya.checkers.TestSourceReader.java
/** * Reads a section in comments form the source of the given class. The section * is started with '// {tag}' and ends with the first line not started by '//' * * @since 4.0/*w w w .ja v a2 s . co m*/ */ public static String readTaggedComment(Bundle bundle, String srcRoot, Class clazz, final String tag) throws IOException { IPath filePath = new Path(srcRoot + '/' + clazz.getName().replace('.', '/') + ".java"); InputStream in = FileLocator.openStream(bundle, filePath, false); LineNumberReader reader = new LineNumberReader(new InputStreamReader(in)); boolean found = false; final StringBuilder content = new StringBuilder(); try { String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.startsWith("//")) { line = line.substring(2); if (found) { content.append(line); content.append('\n'); } else { line = line.trim(); if (line.startsWith("{" + tag)) { if (line.length() == tag.length() + 1 || !Character.isJavaIdentifierPart(line.charAt(tag.length() + 1))) { found = true; } } } } else if (found) { break; } line = reader.readLine(); } } finally { reader.close(); } Assert.assertTrue("Tag '" + tag + "' is not defined inside of '" + filePath + "'.", found); return content.toString(); }
From source file:com.l2jfree.gameserver.instancemanager.leaderboards.FishermanManager.java
public void engineInit() { _ranks = new FastMap<Integer, FishRank>(); String line = null;/*from www . ja va 2 s . c o m*/ LineNumberReader lnr = null; String lineId = ""; FishRank rank = null; File file = new File(Config.DATAPACK_ROOT, "data/fish.dat"); try { boolean created = file.createNewFile(); if (created) _log.info("FishManager: fish.dat was not existing and has been created."); } catch (IOException e) { e.printStackTrace(); } finally { try { lnr = new LineNumberReader(new BufferedReader(new FileReader(file))); while ((line = lnr.readLine()) != null) { if (line.trim().length() == 0 || line.startsWith("#")) continue; lineId = line; line = line.replaceAll(" ", ""); String t[] = line.split(":"); int owner = Integer.parseInt(t[0]); rank = new FishRank(); rank.cought = Integer.parseInt(t[1].split("-")[0]); rank.escaped = Integer.parseInt(t[1].split("-")[1]); rank.name = t[2]; _ranks.put(owner, rank); } } catch (Exception e) { _log.warn("FishManager.engineInit() >> last line parsed is \n[" + lineId + "]\n", e); } finally { IOUtils.closeQuietly(lnr); } startSaveTask(); _log.info("FishManager: Loaded " + _ranks.size() + " player(s)."); } }
From source file:org.apache.cocoon.generation.TextGenerator2.java
/** * Generate XML data./*from ww w .j a va 2 s. c o m*/ * * @throws IOException * @throws ProcessingException * @throws SAXException */ public void generate() throws IOException, SAXException, ProcessingException { InputStreamReader in = null; try { final InputStream sis = this.inputSource.getInputStream(); if (sis == null) { throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found"); } if (encoding != null) { in = new InputStreamReader(sis, encoding); } else { in = new InputStreamReader(sis); } } catch (SourceException se) { throw new ProcessingException("Error during resolving of '" + this.source + "'.", se); } LocatorImpl locator = new LocatorImpl(); locator.setSystemId(this.inputSource.getURI()); locator.setLineNumber(1); locator.setColumnNumber(1); /* Do not pass the source URI to the contentHandler, assuming that that is the LexicalTransformer. It does not have to be. contentHandler.setDocumentLocator(locator); */ contentHandler.startDocument(); AttributesImpl atts = new AttributesImpl(); if (localizable) { atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId()); atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber())); atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber())); } String nsPrefix = this.element.contains(":") ? this.element.replaceFirst(":.+$", "") : ""; String localName = this.element.replaceFirst("^.+:", ""); if (this.namespace.length() > 1) contentHandler.startPrefixMapping(nsPrefix, this.namespace); contentHandler.startElement(this.namespace, localName, this.element, atts); LineNumberReader reader = new LineNumberReader(in); String line; String newline = null; while (true) { if (newline == null) { line = convertNonXmlChars(reader.readLine()); } else { line = newline; } if (line == null) { break; } newline = convertNonXmlChars(reader.readLine()); if (newline != null) { line += SystemUtils.LINE_SEPARATOR; } locator.setLineNumber(reader.getLineNumber()); locator.setColumnNumber(1); contentHandler.characters(line.toCharArray(), 0, line.length()); if (newline == null) { break; } } reader.close(); contentHandler.endElement(this.namespace, localName, this.element); if (this.namespace.length() > 1) contentHandler.endPrefixMapping(nsPrefix); contentHandler.endDocument(); }
From source file:org.marketcetera.strategyagent.StrategyAgent.java
/** * Parses the commands from the supplied commands file. * * @param inFile the file path/*from w ww .ja v a 2s . c o m*/ * * @throws IOException if there were errors parsing the file. * * @return the number of errors encountered when parsing the command file. */ private int parseCommands(String inFile) throws IOException { int numErrors = 0; LineNumberReader reader = new LineNumberReader(new UnicodeFileReader(inFile)); try { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#") || line.trim().isEmpty()) { //$NON-NLS-1$ //Ignore comments and empty lines. continue; } int idx = line.indexOf(';'); //$NON-NLS-1$ if (idx > 0) { String key = line.substring(0, idx); CommandRunner runner = sRunners.get(key); if (runner == null) { numErrors++; Messages.INVALID_COMMAND_NAME.error(this, key, reader.getLineNumber()); continue; } mCommands.add(new Command(runner, line.substring(++idx), reader.getLineNumber())); } else { numErrors++; Messages.INVALID_COMMAND_SYNTAX.error(this, line, reader.getLineNumber()); } } return numErrors; } finally { reader.close(); } }
From source file:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException.java
/** * @param servletContext The ServletContext instance * @param t The exception that was thrown *//*from www . j ava2 s. c o m*/ public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) { super(t.getMessage(), t); cause = t; FastStringPrintWriter pw = FastStringPrintWriter.newInstance(); cause.printStackTrace(pw); stackTrace = pw.toString(); while (cause.getCause() != cause) { if (cause.getCause() == null) { break; } cause = cause.getCause(); } stackTraceLines = stackTrace.split("\\n"); if (cause instanceof MultipleCompilationErrorsException) { MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause; Object message = mcee.getErrorCollector().getErrors().iterator().next(); if (message instanceof SyntaxErrorMessage) { SyntaxErrorMessage sem = (SyntaxErrorMessage) message; lineNumber = sem.getCause().getLine(); className = sem.getCause().getSourceLocator(); sem.write(pw); } } else { Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace); Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace); Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace); try { if (gsp.find()) { className = gsp.group(2); lineNumber = Integer.parseInt(gsp.group(3)); gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className; } else { if (m1.find()) { do { className = m1.group(1); lineNumber = Integer.parseInt(m1.group(2)); } while (m1.find()); } else { while (m2.find()) { className = m2.group(1); lineNumber = Integer.parseInt(m2.group(2)); } } } } catch (NumberFormatException nfex) { // ignore } } LineNumberReader reader = null; try { checkIfSourceCodeAware(t); checkIfSourceCodeAware(cause); if (getLineNumber() > -1) { String fileLocation; String url = null; if (fileName != null) { fileLocation = fileName; } else { String urlPrefix = ""; if (gspFile == null) { fileName = className.replace('.', '/') + ".groovy"; GrailsApplication application = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext) .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); // @todo Refactor this to get the urlPrefix from the ArtefactHandler if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) { urlPrefix += "/controllers/"; } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) { urlPrefix += "/taglib/"; } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) { urlPrefix += "/services/"; } url = URL_PREFIX + urlPrefix + fileName; } else { url = gspFile; GrailsApplicationAttributes attrs = new DefaultGrailsApplicationAttributes(servletContext); GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine(); int[] lineNumbers = engine.calculateLineNumbersForPage(servletContext, url); if (lineNumber < lineNumbers.length) { lineNumber = lineNumbers[lineNumber - 1]; } } fileLocation = "grails-app" + urlPrefix + fileName; } InputStream in = null; if (!StringUtils.isBlank(url)) { in = servletContext.getResourceAsStream(url); LOG.debug("Attempting to display code snippet found in url " + url); } if (in == null) { Resource r = null; try { r = resolver.getResource(fileLocation); in = r.getInputStream(); } catch (Throwable e) { r = resolver.getResource("file:" + fileLocation); if (r.exists()) { try { in = r.getInputStream(); } catch (IOException e1) { // ignore } } } } if (in != null) { reader = new LineNumberReader(new InputStreamReader(in)); String currentLine = reader.readLine(); StringBuilder buf = new StringBuilder(); while (currentLine != null) { int currentLineNumber = reader.getLineNumber(); if ((lineNumber > 0 && currentLineNumber == lineNumber - 1) || (currentLineNumber == lineNumber)) { buf.append(currentLineNumber).append(": ").append(currentLine).append("\n"); } else if (currentLineNumber == lineNumber + 1) { buf.append(currentLineNumber).append(": ").append(currentLine); break; } currentLine = reader.readLine(); } codeSnippet = buf.toString().split("\n"); } } } catch (IOException e) { LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } } }
From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.WriteTagCheckTest.java
@Override protected void verify(Checker checker, File[] processedFiles, String messageFileName, String... expected) throws Exception { stream.flush();// w ww . ja va 2 s.c om final List<File> theFiles = Lists.newArrayList(); Collections.addAll(theFiles, processedFiles); final int errs = checker.process(theFiles); // process each of the lines final ByteArrayInputStream localStream = new ByteArrayInputStream(stream.toByteArray()); try (final LineNumberReader lnr = new LineNumberReader( new InputStreamReader(localStream, StandardCharsets.UTF_8))) { for (int i = 0; i < expected.length; i++) { final String expectedResult = messageFileName + ":" + expected[i]; final String actual = lnr.readLine(); assertEquals("error message " + i, expectedResult, actual); } assertTrue("unexpected output: " + lnr.readLine(), expected.length >= errs); } checker.destroy(); }
From source file:net.pms.dlna.RootFolder.java
private void addWebFolder(File webConf) { if (webConf.exists()) { try {/*from www .java2 s . c om*/ LineNumberReader br = new LineNumberReader( new InputStreamReader(new FileInputStream(webConf), "UTF-8")); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() > 0 && !line.startsWith("#") && line.indexOf("=") > -1) { String key = line.substring(0, line.indexOf("=")); String value = line.substring(line.indexOf("=") + 1); String[] keys = parseFeedKey(key); try { if (keys[0].equals("imagefeed") || keys[0].equals("audiofeed") || keys[0].equals("videofeed") || keys[0].equals("audiostream") || keys[0].equals("videostream")) { String[] values = parseFeedValue(value); DLNAResource parent = null; if (keys[1] != null) { StringTokenizer st = new StringTokenizer(keys[1], ","); DLNAResource currentRoot = this; while (st.hasMoreTokens()) { String folder = st.nextToken(); parent = currentRoot.searchByName(folder); if (parent == null) { parent = new VirtualFolder(folder, ""); currentRoot.addChild(parent); } currentRoot = parent; } } if (parent == null) { parent = this; } if (keys[0].equals("imagefeed")) { parent.addChild(new ImagesFeed(values[0])); } else if (keys[0].equals("videofeed")) { parent.addChild(new VideosFeed(values[0])); } else if (keys[0].equals("audiofeed")) { parent.addChild(new AudiosFeed(values[0])); } else if (keys[0].equals("audiostream")) { parent.addChild(new WebAudioStream(values[0], values[1], values[2])); } else if (keys[0].equals("videostream")) { parent.addChild(new WebVideoStream(values[0], values[1], values[2])); } } } catch (ArrayIndexOutOfBoundsException e) { // catch exception here and go with parsing logger.info("Error at line " + br.getLineNumber() + " of WEB.conf: " + e.getMessage()); logger.debug(null, e); } } } br.close(); } catch (IOException e) { logger.info("Unexpected error in WEB.conf" + e.getMessage()); logger.debug(null, e); } } }
From source file:org.diffkit.diff.sns.DKFileSource.java
private void open() throws IOException { if (_isOpen)//w ww . j a v a 2s .c o m return; _isOpen = true; this.validateFile(); _lineReader = new LineNumberReader(new BufferedReader(new FileReader(_file))); this.readHeader(); }