Search in sources :

Example 81 with LineNumberReader

use of java.io.LineNumberReader in project ranger by apache.

the class MySQLPLRunner method runScript.

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in
 *
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuilder command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuilder();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.length() < 1 || trimmedLine.startsWith("--") || trimmedLine.startsWith("//")) {
            // NOPMD
            // println(trimmedLine);
            // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
                Matcher matcher = pattern.matcher(trimmedLine);
                if (matcher.matches()) {
                    setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
                    continue;
                /*line = lineReader.readLine();
                        if (line == null) {
                            break;
                        }
                        trimmedLine = line.trim();*/
                }
                if (line != null && line.endsWith(getDelimiter()) && !DEFAULT_DELIMITER.equalsIgnoreCase(getDelimiter())) {
                    command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                } else {
                    command.append(line);
                }
                command.append(" ");
                Statement statement = conn.createStatement();
                if (printDebug)
                    println(command);
                // System.out.println(getDelimiter());
                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }
                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }
                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 1; i <= cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 1; i <= cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }
                command = null;
                try {
                    if (rs != null) {
                        rs.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
                Matcher matcher = pattern.matcher(trimmedLine);
                if (matcher.matches()) {
                    setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
                    continue;
                /*line = lineReader.readLine();
                        if (line == null) {
                            break;
                        }
                        trimmedLine = line.trim();*/
                }
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) SQLException(java.sql.SQLException) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) IOException(java.io.IOException) IOException(java.io.IOException) SQLException(java.sql.SQLException) LineNumberReader(java.io.LineNumberReader)

Example 82 with LineNumberReader

use of java.io.LineNumberReader in project iaf by ibissource.

the class FileViewerServlet method showReaderContents.

public static void showReaderContents(Reader reader, String filename, String type, HttpServletResponse response, String title) throws DomBuilderException, TransformerException, IOException {
    PrintWriter out = response.getWriter();
    if (type == null) {
        response.setContentType("text/html");
        out.println("resultType not specified");
        return;
    }
    if (type.equalsIgnoreCase("html")) {
        response.setContentType("text/html");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>" + AppConstants.getInstance().getResolvedProperty("instance.name.lc") + "@" + Misc.getHostname() + " - " + title + "</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + AppConstants.getInstance().getProperty(fvConfigKey + ".css") + "\">");
        out.println("</head>");
        out.println("<body>");
        LineNumberReader lnr = new LineNumberReader(reader);
        String line;
        while ((line = lnr.readLine()) != null) {
            out.println(makeConfiguredReplacements(XmlUtils.encodeChars(line)) + "<br/>");
        }
        out.println("</body>");
        out.println("</html>");
    }
    if (type.equalsIgnoreCase("text")) {
        response.setContentType("text/plain");
        String lastPart;
        try {
            File f = new File(filename);
            lastPart = f.getName();
        } catch (Throwable t) {
            lastPart = filename;
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + lastPart + "\"");
        Misc.readerToWriter(reader, out);
    }
    if (type.equalsIgnoreCase("xml")) {
        response.setContentType("application/xml");
        String lastPart;
        try {
            File f = new File(filename);
            lastPart = f.getName();
        } catch (Throwable t) {
            lastPart = filename;
        }
        response.setHeader("Content-Disposition", "inline; filename=\"" + lastPart + "\"");
        LineNumberReader lnr;
        if (filename.indexOf("_xml.log") >= 0) {
            Reader fileReader = new EncapsulatingReader(reader, log4j_prefix, log4j_postfix, true);
            lnr = new LineNumberReader(fileReader);
        } else {
            if (filename.indexOf("-stats_") >= 0) {
                Reader fileReader = new EncapsulatingReader(reader, stats_prefix, stats_postfix, true);
                lnr = new LineNumberReader(fileReader);
            } else {
                lnr = new LineNumberReader(reader);
            }
        }
        String line;
        while ((line = lnr.readLine()) != null) {
            out.println(line + "\n");
        }
    }
    out.close();
}
Also used : EncapsulatingReader(nl.nn.adapterframework.util.EncapsulatingReader) EncapsulatingReader(nl.nn.adapterframework.util.EncapsulatingReader) LineNumberReader(java.io.LineNumberReader) Reader(java.io.Reader) FileReader(java.io.FileReader) File(java.io.File) PrintWriter(java.io.PrintWriter) LineNumberReader(java.io.LineNumberReader)

Example 83 with LineNumberReader

use of java.io.LineNumberReader in project JikesRVM by JikesRVM.

the class EdgeCounts method readCounts.

public static void readCounts(String fn) {
    LineNumberReader in = null;
    try {
        in = new LineNumberReader(new FileReader(fn));
    } catch (IOException e) {
        e.printStackTrace();
        VM.sysFail("Unable to open input edge counter file " + fn);
    }
    try {
        int[] cur = null;
        int curIdx = 0;
        for (String s = in.readLine(); s != null; s = in.readLine()) {
            // strip classloader cruft we can't parse
            s = s.replaceAll("\\{urls[^\\}]*\\}", "");
            StringTokenizer parser = new StringTokenizer(s, " \t\n\r\f,{}");
            String firstToken = parser.nextToken();
            if (firstToken.equals("M")) {
                int numCounts = Integer.parseInt(parser.nextToken());
                MemberReference key = MemberReference.parse(parser);
                int id = key.getId();
                allocateCounters(id, numCounts);
                cur = data[id];
                curIdx = 0;
                if (Controller.options.BULK_COMPILATION_VERBOSITY >= 1) {
                    VM.sysWrite("M");
                }
            } else {
                // discard bytecode index, we don't care.
                String type = parser.nextToken();
                if (type.equals("switch")) {
                    // discard '<'
                    parser.nextToken();
                    for (String nt = parser.nextToken(); !nt.equals(">"); nt = parser.nextToken()) {
                        cur[curIdx++] = Integer.parseInt(nt);
                    }
                    if (Controller.options.BULK_COMPILATION_VERBOSITY >= 1) {
                        VM.sysWrite("S");
                    }
                } else if (type.equals("forwbranch") || type.equals("backbranch")) {
                    // discard '<'
                    parser.nextToken();
                    cur[curIdx + TAKEN] = Integer.parseInt(parser.nextToken());
                    cur[curIdx + NOT_TAKEN] = Integer.parseInt(parser.nextToken());
                    curIdx += 2;
                    if (Controller.options.BULK_COMPILATION_VERBOSITY >= 1) {
                        VM.sysWrite("B");
                    }
                } else {
                    VM.sysFail("Format error in edge counter input file");
                }
            }
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
        VM.sysFail("Error parsing input edge counter file" + fn);
    }
    // Enable debug of input by dumping file as we exit the VM.
    if (false) {
        Callbacks.addExitMonitor(new EdgeCounts());
        BaselineCompiler.processCommandLineArg("-X:base:", "edge_counter_file=DebugEdgeCounters");
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) MemberReference(org.jikesrvm.classloader.MemberReference) FileReader(java.io.FileReader) IOException(java.io.IOException) Entrypoint(org.vmmagic.pragma.Entrypoint) LineNumberReader(java.io.LineNumberReader)

Example 84 with LineNumberReader

use of java.io.LineNumberReader in project JikesRVM by JikesRVM.

the class CompilerDNA method readDNA.

/**
 * Read a serialized representation of the DNA info
 * @param filename DNA filename
 */
private static void readDNA(String filename) {
    try {
        LineNumberReader in = new LineNumberReader(new FileReader(filename));
        // Expected Format
        // CompilationRates  aaa.a  bbbb.b cccc.c dddd.d ....
        // SpeedupRates      aaa.a  bbbb.b cccc.c dddd.d ....
        processOneLine(in, "CompilationRates", compilationRates);
        processOneLine(in, "SpeedupRates", speedupRates);
    } catch (Exception e) {
        e.printStackTrace();
        VM.sysFail("Failed to open controller DNA file");
    }
}
Also used : FileReader(java.io.FileReader) IOException(java.io.IOException) LineNumberReader(java.io.LineNumberReader)

Example 85 with LineNumberReader

use of java.io.LineNumberReader in project JikesRVM by JikesRVM.

the class GenerateFromTemplate method processEvalRegion.

void processEvalRegion(Vector<Object> region) throws IOException {
    if (DEBUG)
        System.out.println("doing eval");
    PrintWriter old_out = out;
    StringWriter sw = new StringWriter();
    out = new PrintWriter(sw);
    // Count through each line in region.
    for (int j = 1; j < region.size(); j++) {
        try {
            String currentLine = (String) region.elementAt(j);
            out.print(currentLine + "\n");
        } catch (ClassCastException e) {
            // Suppress complaints that we are casting to an erased type
            @SuppressWarnings("unchecked") Vector<Object> tmpRegion = (Vector<Object>) region.elementAt(j);
            processTemplateRegion(tmpRegion);
        }
    }
    // for j
    out = old_out;
    if (DEBUG)
        System.out.println("doing eval: evaluating\n" + sw);
    LineNumberReader old_in = in;
    in = new LineNumberReader(new StringReader(sw.toString()));
    String inLine;
    // loop over strings in the newly created region
    for (inLine = readLine(); inLine != null; inLine = readLine()) {
        if (DEBUG)
            System.out.println("from input:" + inLine);
        if (!isTemplateLine(inLine)) {
            if (DEBUG)
                System.out.println("not template line, continuing...");
            out.print(inLine + "\n");
            continue;
        }
        Vector<Object> newRegion = buildTemplateRegion(inLine);
        processTemplateRegion(newRegion);
    }
    in.close();
    in = old_in;
}
Also used : StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) Vector(java.util.Vector) PrintWriter(java.io.PrintWriter) LineNumberReader(java.io.LineNumberReader)

Aggregations

LineNumberReader (java.io.LineNumberReader)401 IOException (java.io.IOException)203 InputStreamReader (java.io.InputStreamReader)167 FileReader (java.io.FileReader)102 File (java.io.File)79 InputStream (java.io.InputStream)64 StringReader (java.io.StringReader)64 ArrayList (java.util.ArrayList)54 FileInputStream (java.io.FileInputStream)33 BufferedReader (java.io.BufferedReader)27 PrintWriter (java.io.PrintWriter)25 HashMap (java.util.HashMap)22 FileNotFoundException (java.io.FileNotFoundException)20 BufferedWriter (java.io.BufferedWriter)16 FileWriter (java.io.FileWriter)16 Pattern (java.util.regex.Pattern)16 Test (org.junit.jupiter.api.Test)16 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 Reader (java.io.Reader)14