List of usage examples for java.io LineNumberReader close
public void close() throws IOException
From source file:ua.utility.kfsdbupgrade.App.java
/** * Execute the sql file {@link #upgradeRoot} * <code>/post-upgrade/sql/misc.sql</code> against the database * /*from www .ja v a 2 s . c om*/ * @param conn * {@link Connection} to the database * @param stmt * {@link Statement} to use to execute SQL */ private void runMiscSql(Connection conn, Statement stmt) { LineNumberReader lnr = null; logHeader2("Executing miscellaneous post-upgrade sql"); File miscSqlFile = new File(postUpgradeDirectory + File.separator + MISC_SQL_PATH); try { lnr = new LineNumberReader(new FileReader(miscSqlFile)); String sql = null; while ((sql = lnr.readLine()) != null) { if (StringUtils.isNotBlank(sql)) { try { if (sql.trim().endsWith(";")) { int pos = sql.lastIndexOf(";"); sql = sql.substring(0, pos); } if (isDDL(sql)) { stmt.execute(sql); } else { stmt.executeUpdate(sql); } LOGGER.info(sql); } catch (SQLException ex) { LOGGER.error("sql execution failed: " + sql, ex); } } } } catch (Exception ex) { LOGGER.error(ex); } finally { try { if (lnr != null) { lnr.close(); } } catch (Exception ex) { LOGGER.error(ex); } ; } postUpgradeFilesProcessed.add(miscSqlFile); }
From source file:ua.utility.kfsdbupgrade.App.java
/** * Create the public synonyms specified in {@link #upgradeRoot} * <code>/post-upgrade/sql/kfs-public-synonyms.sql</code> that do not * already exist./*from w ww. j a v a 2s . com*/ * * @param conn * {@link Connection} to a database * @param stmt * {@link Statement} to use to execute SQL statements */ private void createPublicSynonyms(Connection conn, Statement stmt) { LineNumberReader lnr = null; logHeader2("creating KFS public synonyms that existed prior to upgrade where required "); File kfsPublicSynonymsSqlFile = new File( postUpgradeDirectory + File.separator + KFS_PUBLIC_SYNONYMS_SQL_PATH); try { lnr = new LineNumberReader(new FileReader(kfsPublicSynonymsSqlFile)); String line = null; while ((line = lnr.readLine()) != null) { String synonymName = getSynonymName(line); if (!synonymExists(conn, stmt, synonymName)) { try { // if there is a trailing semicolon, remove it int pos = line.lastIndexOf(';'); if (pos == line.length() - 1) { line = line.substring(0, line.length() - 1); } stmt.execute(line); } catch (SQLException ex) { LOGGER.error("failed to create public synonym: " + line, ex); } } } } catch (Exception ex) { LOGGER.error(ex); } finally { try { if (lnr != null) { lnr.close(); } } catch (Exception ex) { LOGGER.error(ex); } ; } postUpgradeFilesProcessed.add(kfsPublicSynonymsSqlFile); }
From source file:massbank.BatchJobWorker.java
/** * Ytt@C???ieLXg`?j/*from w ww.j ava2 s .c om*/ * @param time NGXg * @param resultFile t@C * @param textFile YtpeLXgt@C */ private void createTextFile(String time, File resultFile, File textFile) { NumberFormat nf = NumberFormat.getNumberInstance(); LineNumberReader in = null; PrintWriter out = null; try { in = new LineNumberReader(new FileReader(resultFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(textFile))); // wb_?[?o String reqIonStr = "Both"; try { if (Integer.parseInt(this.ion) > 0) { reqIonStr = "Positive"; } else if (Integer.parseInt(this.ion) < 0) { reqIonStr = "Negative"; } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } out.println("***** MassBank Batch Service Results *****"); out.println(); out.println("Request Date: " + time); out.println("# Instrument Type: " + this.inst); out.println("# Ion Mode: " + reqIonStr); out.println(); out.println(); // ?o String line; long queryCnt = 0; boolean readName = false; boolean readHit = false; boolean readNum = false; boolean isFinalLine = false; while ((line = in.readLine()) != null) { isFinalLine = false; if (in.getLineNumber() < 4) { continue; } if (!readName) { queryCnt++; out.println("### Query " + nf.format(queryCnt) + " ###"); out.println("# Name: " + line.trim()); readName = true; } else if (!readHit) { out.println("# Hit: " + nf.format(Integer.parseInt(line.trim()))); out.println(); readHit = true; } else if (!readNum) { out.println("Top " + line.trim() + " List"); out.println("Accession\tTitle\tFormula\tIon\tScore\tHit"); out.println(); readNum = true; } else { if (!line.trim().equals("")) { String[] data = formatLine(line); StringBuilder sb = new StringBuilder(); sb.append(data[0]).append("\t").append(data[1]).append("\t").append(data[2]).append("\t") .append(data[3]).append("\t").append(data[4]).append("\t").append(data[5]); out.println(sb.toString()); } else { out.println(); out.println(); readName = false; readHit = false; readNum = false; isFinalLine = true; } } } if (!isFinalLine) { out.println(); out.println(); } out.println("##### END #####"); out.println(); out.println("**********************************************************"); out.println("* MassBank.jp - High Resolution Mass Spectral Database *"); out.println("* URL: http://www.massbank.jp/ *"); out.println("**********************************************************"); out.println(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } if (out != null) { out.flush(); out.close(); } } }
From source file:ua.utility.kfsdbupgrade.App.java
/** * Read SQL statements from the provided {@link File} into a {@link List} of * {@link String}s. Blank lines and comment lines (lines beginning with * "<code>--</code>") are skipped. * //from ww w.ja va2 s . c om * @param f * {@link File} to read SQL statements from * @return {@link List} of {@link String}s representing the SQL statements * to execute read from the provided {@link File} */ private List<String> getSqlStatements(File f) { List<String> retval = new ArrayList<String>(); LineNumberReader lnr = null; try { lnr = new LineNumberReader(new FileReader(f)); String line = null; StringBuilder sql = new StringBuilder(512); while ((line = lnr.readLine()) != null) { if (StringUtils.isNotBlank(line) && !line.trim().startsWith("--")) { line = line.trim(); // FIXME hardcoded delimiters if (line.equals("/") || line.equals(";")) { if (sql.length() > 0) { retval.add(sql.toString()); sql.setLength(0); } } else if (line.endsWith("/") || line.endsWith(";")) { sql.append(" "); sql.append(line.substring(0, line.length() - 1)); retval.add(sql.toString()); sql.setLength(0); } else { sql.append(" "); sql.append(line); } } } if (sql.length() > 0) { retval.add(sql.toString()); } } catch (Exception ex) { LOGGER.error(ex); } finally { try { if (lnr != null) { lnr.close(); } } catch (Exception ex) { } } return retval; }
From source file:massbank.BatchSearchWorker.java
/** * Ytt@C???ieLXg`?j//from w ww .ja v a 2 s . c o m * @param resultFile t@C * @param textFile YtpeLXgt@C */ private void createTextFile(File resultFile, File textFile) { NumberFormat nf = NumberFormat.getNumberInstance(); LineNumberReader in = null; PrintWriter out = null; try { in = new LineNumberReader(new FileReader(resultFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(textFile))); // wb_?[?o String reqIonStr = "Both"; try { if (Integer.parseInt(this.ion) > 0) { reqIonStr = "Positive"; } else if (Integer.parseInt(this.ion) < 0) { reqIonStr = "Negative"; } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } out.println("***** MassBank Batch Service Results *****"); out.println(); out.println("Request Date: " + this.time); out.println("# Instrument Type: " + this.inst); out.println("# MS Type: " + this.ms); out.println("# Ion Mode: " + reqIonStr); out.println(); out.println(); // ?o String line; long queryCnt = 0; boolean readName = false; boolean readHit = false; boolean readNum = false; boolean isFinalLine = false; while ((line = in.readLine()) != null) { line = line.trim(); isFinalLine = false; if (!readName) { queryCnt++; out.println("### Query " + nf.format(queryCnt) + " ###"); out.println("# Name: " + line); readName = true; } else if (!readHit) { int num = Integer.parseInt(line); if (num == -1) { out.println("[ERROR] Invalid query\n"); break; } out.println("# Hit: " + nf.format(num)); out.println(); readHit = true; } else if (!readNum) { out.println("Top " + line + " List"); out.println("Accession\tTitle\tFormula\tMass\tScore\tHit"); out.println(); readNum = true; } else { if (!line.equals("")) { String[] data = formatLine(line); StringBuilder sb = new StringBuilder(); sb.append(data[0]).append("\t").append(data[1]).append("\t").append(data[2]).append("\t") .append(data[3]).append("\t").append(data[4]).append("\t").append(data[5]); out.println(sb.toString()); } else { out.println(); out.println(); readName = false; readHit = false; readNum = false; isFinalLine = true; } } } if (!isFinalLine) { out.println(); out.println(); } out.println("***** END ********************************"); out.println(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } if (out != null) { out.flush(); out.close(); } } }
From source file:massbank.BatchJobWorker.java
/** * Ytt@C???iHTML`?j/*from w w w. java 2 s . c o m*/ * @param time NGXg * @param resultFile t@C * @param htmlFile YtpHTMLt@C */ private void createHtmlFile(String time, File resultFile, File htmlFile) { NumberFormat nf = NumberFormat.getNumberInstance(); LineNumberReader in = null; PrintWriter out = null; try { in = new LineNumberReader(new FileReader(resultFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile))); // wb_?[?o String reqIonStr = "Both"; try { if (Integer.parseInt(this.ion) > 0) { reqIonStr = "Positive"; } else if (Integer.parseInt(this.ion) < 0) { reqIonStr = "Negative"; } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } out.println("<html>"); out.println("<head><title>MassBank Batch Service Results</title></head>"); out.println("<body>"); out.println( "<h1><a href=\"http://www.massbank.jp/\" target=\"_blank\">MassBank</a> Batch Service Results</h1>"); out.println("<hr>"); out.println("<h2>Request Date : " + time + "<h2>"); out.println("Instrument Type : " + this.inst + "<br>"); out.println("Ion Mode : " + reqIonStr + "<br>"); out.println("<br><hr>"); // ?o String line; long queryCnt = 0; boolean readName = false; boolean readHit = false; boolean readNum = false; while ((line = in.readLine()) != null) { if (in.getLineNumber() < 4) { continue; } if (!readName) { queryCnt++; out.println("<h2>Query " + nf.format(queryCnt) + "</h2><br>"); out.println("Name: " + line.trim() + "<br>"); readName = true; } else if (!readHit) { out.println("Hit: " + nf.format(Integer.parseInt(line.trim())) + "<br>"); readHit = true; } else if (!readNum) { out.println("<table border=\"1\">"); out.println("<tr><td colspan=\"6\">Top " + line.trim() + " List</td></tr>"); out.println( "<tr><th>Accession</th><th>Title</th><th>Formula</th><th>Ion</th><th>Score</th><th>Hit</th></tr>"); readNum = true; } else { if (!line.trim().equals("")) { String[] data = formatLine(line); String acc = data[0]; String title = data[1]; String formula = data[2]; String ion = data[3]; String score = data[4]; String hit = data[5]; out.println("<tr>"); out.println("<td><a href=\"http://www.massbank.jp/jsp/FwdRecord.jsp?id=" + acc + "\" target=\"_blank\">" + acc + "</td>"); out.println("<td>" + title + "</td>"); out.println("<td>" + formula + "</td>"); out.println("<td>" + ion + "</td>"); out.println("<td>" + score + "</td>"); out.println("<td align=\"right\">" + hit + "</td>"); out.println("</tr>"); } else { out.println("</table>"); out.println("<hr>"); readName = false; readHit = false; readNum = false; } } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } if (out != null) { out.flush(); out.close(); } } }
From source file:net.pms.dlna.RootFolder.java
private void addWebFolder(File webConf) { if (webConf.exists()) { try {/*w w w. j ava2 s . co m*/ 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:com.autentia.tnt.manager.data.MigrationManager.java
/** * @return the original database version * @throws com.autentia.tnt.manager.data.exception.DataException *//*from w w w . ja v a2 s. c o m*/ public Version upgradeDatabase() throws DataException { Version ret = null; Version db = null; Version code = Version.getApplicationVersion(); Session ses = HibernateUtil.getSessionFactory().openSession(); Connection con = ses.connection(); Statement stmt = null; LineNumberReader file = null; String delimiter = ";"; try { db = Version.getDatabaseVersion(); ret = db.clone(); log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<"); // Disable auto-commit (just in case...) log.info("upgradeDatabase - disabling auto commit"); con.setAutoCommit(false); // Create statement stmt = con.createStatement(); // While necessary, upgrade database while (db.compareTo(code, Version.MINOR) < 0) { log.info("upgradeDatabase - " + db); // Compose script name and open it String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX; log.info("upgradeDatabase - loading script " + script); InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script); if (sqlScript == null) { throw FileNotFoundException(script); } file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8")); int _c; // Add batched SQL sentences to statement StringBuilder sentence = new StringBuilder(); String line; while ((line = file.readLine()) != null) { line = line.trim(); if (!line.startsWith("--")) { // Interpret "DELIMITER" sentences if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) { delimiter = line.trim().substring("DELIMITER".length()).trim(); } else { // Add line to sentence if (line.endsWith(delimiter)) { // Remove delimiter String lastLine = line.substring(0, line.length() - delimiter.length()); // Append line to sentence sentence.append(lastLine); // Execute sentence log.info(" " + sentence.toString()); stmt.addBatch(sentence.toString()); // Prepare new sentence sentence = new StringBuilder(); } else { // Append line to sentence sentence.append(line); // Append separator for next line sentence.append(" "); } } } } // Execute batch log.info("upgradeDatabase - executing batch of commands"); stmt.executeBatch(); // Re-read database version Version old = db; db = Version.getDatabaseVersion(con); if (old.equals(db)) { throw new DataException("Script was applied but did not upgrade database: " + script); } log.info("upgradeDatabase - database upgraded to version " + db); } // Commit transaction log.info("upgradeDatabase - commiting changes to database"); con.commit(); // Report end of migration log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<"); } catch (Exception e) { log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e); try { con.rollback(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al realizar el rollback"); } throw new DataException("Script was applied but did not upgrade database: ", e); } finally { if (file != null) { try { file.close(); } catch (IOException e2) { log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al cerrar el statement"); } } ses.close(); } return ret; }
From source file:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException.java
/** * @param servletContext The ServletContext instance * @param t The exception that was thrown *///from w w w . j a va2 s.co 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.netcrest.pado.tools.pado.PadoShell.java
public void runScript(File scriptFile) throws IOException { LineNumberReader reader = null; try {//from w ww .ja v a 2s .co m reader = new LineNumberReader(new FileReader(scriptFile)); String line = reader.readLine(); String command; ArrayList<String> propertyCommandList = new ArrayList<String>(); ArrayList<String> commandList = new ArrayList<String>(); StringBuffer buffer = new StringBuffer(); while (line != null) { command = line.trim(); if (command.length() > 0 && command.startsWith("#") == false) { if (command.endsWith("\\")) { buffer.append(command.substring(0, command.length() - 1)); } else { buffer.append(command); StringTokenizer strToken = new StringTokenizer(command); if (strToken.hasMoreTokens()) { String commandName = strToken.nextToken(); // if (PROPERTIES_CMD_LIST.contains(commandName)) { // propertyCommandList.add(buffer.toString().trim()); // } /* * else if (commandName != null && commandName * .startsWith("historyPerSession")) { try { String * value = command .substring("historyPerSession" * .length() + 1); * setMultiSessionPerUser(Boolean.valueOf(value)); } * catch (Exception ex) { // do nothing } } */ // else { commandList.add(buffer.toString().trim()); // } } buffer = new StringBuffer(); } } line = reader.readLine(); } command = null; // Execute properties set commands // for (String propertyCommand : PROPERTIES_CMD_LIST) { // for (int i = 0; i < propertyCommandList.size(); i++) { // command = propertyCommandList.get(i); // StringTokenizer strToken = new StringTokenizer(command); // if (strToken.hasMoreTokens()) { // String commandName = strToken.nextToken(); // if (commandName.equals(propertyCommand)) { // runCommand(command); // propertyCommandList.remove(i); // i--; // } // } // } // } // Execute commands for (int i = 0; i < commandList.size(); i++) { command = commandList.get(i); runCommand(command, false); } } finally { if (reader != null) { reader.close(); } } }