Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

In this page you can find the example usage for java.io LineNumberReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

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 w w w . j ava2s.  co m
 * @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:org.agnitas.web.ImportWizardForm.java

/**
 * check in the columnMapping for the key column, and eventually for gender
 * and mailtype read first csv line again; do not parse (allready parsed in
 * parseFirstline) prepare download-files for errors and parsed data read
 * the rest of the csv-file//from   w  w  w .  j  av a 2s  .c o m
 */
protected ActionErrors parseContent(HttpServletRequest req) {
    ApplicationContext aContext = this.getWebApplicationContext();
    JdbcTemplate jdbc = new JdbcTemplate((DataSource) aContext.getBean("dataSource"));
    LinkedList aLineContent = null;
    String firstline = null;
    String csvString = new String("");
    ActionErrors errors = new ActionErrors();
    boolean hasGENDER = false;
    boolean hasMAILTYPE = false;
    boolean hasKeyColumn = false;

    this.uniqueValues = new HashSet();
    this.parsedContent = new LinkedList();
    this.linesOK = 0;
    // this.csvMaxUsedColumn=0;

    this.dbInsertStatus = 0;

    try {
        csvString = new String(this.getCsvFile().getFileData(), status.getCharset());
    } catch (Exception e) {
        AgnUtils.logger().error("parseContent: " + e);
        errors.add("global", new ActionMessage("error.import.charset"));
        return errors;
    }

    try {
        this.loadBlacklist(this.getCompanyID(req), jdbc);
    } catch (Exception e) {
        errors.add("global", new ActionMessage("import.blacklist.read"));
        return errors;
    }

    LineNumberReader aReader = new LineNumberReader(new StringReader(csvString));

    String myline = null;

    // check in the columnMapping for the key column,
    // and eventually for gender and mailtype:
    String aKey = "";
    CsvColInfo aCol = null;

    Enumeration aMapEnu = this.columnMapping.keys();

    while (aMapEnu.hasMoreElements()) {
        aKey = (String) aMapEnu.nextElement();
        aCol = (CsvColInfo) this.columnMapping.get(aKey);

        if (aCol.getName().equalsIgnoreCase(GENDER_KEY)) {
            hasGENDER = true;
        }

        if (aCol.getName().equalsIgnoreCase(MAILTYPE_KEY)) {
            hasMAILTYPE = true;
        }

        if (aCol.getName().equalsIgnoreCase(this.status.getKeycolumn())) {
            hasKeyColumn = true;
        }
    }

    if (!hasKeyColumn) {
        errors.add("global", new ActionMessage("error.import.no_keycolumn_mapping"));
    }

    if (this.getMode() == ImportWizardForm.MODE_ADD || this.getMode() == ImportWizardForm.MODE_ADD_UPDATE) {
        if (!hasGENDER) {
            errors.add("global", new ActionMessage("error.import.no_gender_mapping"));
        }
        if (!hasMAILTYPE) {
            errors.add("global", new ActionMessage("error.import.no_mailtype_mapping"));
        }
    }

    try {

        // read first csv line again; do not parse (allready parsed in
        // parseFirstline):
        if ((myline = aReader.readLine()) != null) {
            firstline = myline;
        }

        // prepare download-files for errors and parsed data
        errorData.put(DATE_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(EMAIL_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(EMAILDOUBLE_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(GENDER_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(MAILTYPE_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(NUMERIC_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(STRUCTURE_ERROR, new StringBuffer(firstline + '\n'));
        errorData.put(BLACKLIST_ERROR, new StringBuffer(firstline + '\n'));
        parsedData = new StringBuffer(firstline + '\n');

        // read the rest of the csv-file:
        // StringTokenizer file = new StringTokenizer(csvString, "\n");

        if (errors.isEmpty()) {
            readlines = 0;
            int maxrows = BLOCK_SIZE;
            this.linesOK = 0;
            while ((myline = aReader.readLine()) != null && this.linesOK < maxrows) { // Bug-Fix just read the first 1000 lines to avoid trouble with heap space 
                if (myline.trim().length() > 0) {
                    aLineContent = parseLine(myline,
                            (Locale) req.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY));
                    if (aLineContent != null) {
                        parsedContent.add(aLineContent);
                        this.parsedData.append(myline + "\n");
                        this.linesOK++;
                    }
                }
                readlines++;
            }

            aReader.close();
        }
    } catch (Exception e) {
        AgnUtils.logger().error("parseContent: " + e);
    }
    return errors;
}

From source file:ua.utility.kfsdbupgrade.App.java

/**
 * From the {@link #upgradeRoot}/* w w w. j a va 2 s  .  c o  m*/
 * <code>/post-upgrade/sql/kfs-indexes.sql</code> file, create any indices
 * that are present in the SQL file but in the database that is being worked
 * against TODO there's more going on here... come back after digging
 * through submethods
 * 
 * @param conn
 * @param stmt
 */
protected boolean createExistingIndexes(Connection conn, Statement stmt, File kfsIndexesSqlFile) {
    boolean success = true;
    LineNumberReader lnr = null;

    logHeader2("creating KFS indexes that existed prior to upgrade where required ");
    try {
        lnr = new LineNumberReader(new FileReader(kfsIndexesSqlFile));

        String line = null;

        while ((line = lnr.readLine()) != null) {

            if (StringUtils.isNotBlank(line) && line.startsWith("--")) {
                // Skip lines starting with a comment
                continue;
            }

            String tableName = getIndexTableName(line);
            String indexName = getIndexName(line);
            if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(indexName)) {
                if (tableExists(conn, stmt, tableName)) {
                    boolean unique = line.contains(" UNIQUE ");
                    List<String> columnNames = getIndexColumnNames(line);

                    if (!indexExists(conn, stmt, tableName, columnNames)) {
                        if (indexNameExists(conn, stmt, tableName, indexName)) {
                            indexName = getNextTableIndexName(conn, stmt, tableName);
                        }

                        StringBuilder sql = new StringBuilder(256);

                        sql.append("CREATE ");

                        if (unique) {
                            sql.append("UNIQUE ");
                        }

                        sql.append("INDEX KULOWNER.");

                        sql.append(indexName);
                        sql.append(" ON KULOWNER.");
                        sql.append(tableName);
                        sql.append("(");

                        String comma = "";
                        for (String columnName : columnNames) {
                            sql.append(comma);
                            sql.append(columnName);
                            comma = ",";
                        }

                        sql.append(")");

                        try {
                            stmt.execute(sql.toString());
                        } catch (SQLException ex) {
                            success = false;
                            LOGGER.error("failed to create index: " + sql.toString(), ex);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        success = false;
        LOGGER.error(ex);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception ex) {
        }
        ;
    }
    postUpgradeFilesProcessed.add(kfsIndexesSqlFile);

    return success;
}

From source file:ua.utility.kfsdbupgrade.App.java

/**
 * Execute the sql file {@link #upgradeRoot}
 * <code>/post-upgrade/sql/misc.sql</code> against the database
 * // w  w  w . 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./* w ww .ja  v  a  2  s .  co m*/
 * 
 * @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:org.opencms.setup.CmsSetupBean.java

/**
 * Saves the properties to a file.<p>
 * //from w w  w. j  av a  2 s  .c om
 * @param properties the properties to be saved
 * @param source the source file to get the keys from
 * @param target the target file to save the properties to
 * @param forceWrite the keys of the properties which should always be written, even if they don't exist in the configuration file 
 */
private void save(CmsParameterConfiguration properties, String source, String target, Set<String> forceWrite) {

    try {
        Set<String> alreadyWritten = new HashSet<String>();

        LineNumberReader lnr = new LineNumberReader(new FileReader(new File(m_configRfsPath + source)));

        FileWriter fw = new FileWriter(new File(m_configRfsPath + target));

        while (true) {
            String line = lnr.readLine();
            if (line == null) {
                break;
            }
            line = line.trim();

            if ("".equals(line)) {
                // output empty line
                fw.write("\n");
            } else if (line.startsWith("#")) {
                // output comment
                fw.write(line);
                fw.write("\n");
            } else {

                int index = line.indexOf('=');
                int index1 = line.indexOf("\\=");
                if ((line.indexOf('=') > -1) && (index1 != (index - 1))) {

                    String key = line.substring(0, line.indexOf('=')).trim();
                    if (alreadyWritten.contains(key)) {
                        continue;
                    }
                    // write key
                    fw.write((key + "="));
                    try {
                        Object obj = properties.getObject(key);
                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }

                    } catch (NullPointerException e) {
                        // no value found - do nothing 
                    }
                    // add trailing line feed
                    fw.write("\n");

                    // remember that this properties is already written (multi values)
                    alreadyWritten.add(key);
                }
            }
        }
        if (forceWrite != null) {
            for (String forced : forceWrite) {
                if (!alreadyWritten.contains(forced) && properties.containsKey(forced)) {
                    fw.write("\n\n");
                    fw.write(forced + "=");
                    try {
                        Object obj = properties.getObject(forced);

                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }
                    } catch (NullPointerException e) {
                        // no value found - do nothing
                    }
                    fw.write("\n");

                }
            }
        }

        lnr.close();
        fw.close();
    } catch (Exception e) {
        m_errors.add("Could not save properties to " + target + " \n");
        m_errors.add(e.toString() + "\n");
    }
}

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 ava  2  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:de.innovationgate.wgpublisher.WGPDispatcher.java

/**
 * @param request//from w  ww  .  j  a  va 2  s.  c  o m
 * @param response
 * @param session
 */
private void sendJobLog(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {

    if (!isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "You must be logged in as WGA administrator!");
        return;
    }

    String jobToShow = request.getParameter("name");
    Job job = getCore().getScheduler().getJob(jobToShow);
    if (job == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown job: " + jobToShow);
        return;
    }

    response.setContentType("text/html");
    Writer out = response.getWriter();
    out.write("<HTML><HEAD>");

    out.write("\n<script>\nvar running=" + Boolean.valueOf(job.isRunning()).toString() + ";\n</script>\n");

    /*
     * if (job.isRunning()) {
     * out.write("<META HTTP-EQUIV=\"refresh\" CONTENT=\"3\"/>"); } else {
     * out.write("<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\"/>"); }
     */
    out.write("</HEAD>");
    out.write("<BODY style=\"background-color:white; font-family:sans-serif; font-size:10pt\">");
    String log = job.getLog();
    LineNumberReader reader = new LineNumberReader(new StringReader(log));
    String line;
    while ((line = reader.readLine()) != null) {
        out.write(line);
        out.write("<BR/>");
    }

    if (!job.isRunning() && job.getEndMessage() != null) {
        out.write("<p>");
        out.write("<table border=\"1\" cellpadding=\"5\"><tr><td>");
        out.write(job.getEndMessage());
        out.write("</td></tr></table>");
        out.write("</p>");
    }
    out.write("<a id=\"bottomLink\" name=\"bottom\">&nbsp;</a></BODY></HTML>");

}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *//*from  ww  w.j a  v a2  s  . c om*/
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable 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 = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.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, "UTF-8"));
                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:edu.stanford.muse.util.ThunderbirdUtils.java

/** returns a list of thunderbird accounts.
   each list is in turn a list of length exactly 4:
   account name, hostname, server type, user name
*///from ww w  .ja va  2  s . c om
public static List<List<String>> getThunderbirdAccounts() {
    try {
        List<List<String>> newResult = getThunderbirdAccountsNew();
        if (newResult != null)
            return newResult;
    } catch (Exception e) {
        log.warn("unable to process thunderbird profile with new thunderbird parser");
        Util.print_exception(e, log);
    }

    List<List<String>> result = new ArrayList<List<String>>();

    try {
        String rootDir = ThunderbirdUtils.getThunderbirdProfileDir();
        String prefs = rootDir + File.separator + "prefs.js";
        File f = new File(prefs);
        if (!f.exists() || !f.canRead()) {
            EmailUtils.log.info("Thunderbird probably not installed: no prefs.js in directory: " + prefs);
            return result;
        }

        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(prefs), "UTF-8"));

        // example fragment of input
        //        user_pref("mail.server.server2.capability", 21520929);
        //        user_pref("mail.server.server2.directory", "AAAAAAH0AAIAAQxNYWNpbnRvc2ggSEQAAAAAAAAAAAAAAAAAAADGqxmGSCsAAAAJi1ASeGVub24uc3RhbmZvcmQuZWR1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmLUcbnohEAAAAAAAAAAP////8AAAkgAAAAAAAAAAAAAAAAAAAACEltYXBNYWlsABAACAAAxqt79gAAABEACAAAxugEgQAAAAEAHAAJi1AACYsXAAmLFQAJiw8AB/mpAAf5qAAAkOcAAgBjTWFjaW50b3NoIEhEOlVzZXJzOmhhbmdhbDpMaWJyYXJ5OlRodW5kZXJiaXJkOlByb2ZpbGVzOjcyeHZzMXd3LmRlZmF1bHQ6SW1hcE1haWw6eGVub24uc3RhbmZvcmQuZWR1AAAOACYAEgB4AGUAbgBvAG4ALgBzAHQAYQBuAGYAbwByAGQALgBlAGQAdQAPABoADABNAGEAYwBpAG4AdABvAHMAaAAgAEgARAASAFZVc2Vycy9oYW5nYWwvTGlicmFyeS9UaHVuZGVyYmlyZC9Qcm9maWxlcy83Mnh2czF3dy5kZWZhdWx0L0ltYXBNYWlsL3hlbm9uLnN0YW5mb3JkLmVkdQATAAEvAAAVAAIADf//AAA=");
        //        user_pref("mail.server.server2.directory-rel", "[ProfD]ImapMail/xenon.stanford.edu");
        //        user_pref("mail.server.server2.download_on_biff", true);
        //        user_pref("mail.server.server2.hostname", "xenon.stanford.edu");
        //        user_pref("mail.server.server2.login_at_startup", true);
        //        user_pref("mail.server.server2.max_cached_connections", 5);
        //        user_pref("mail.server.server2.name", "Stanford CS");
        //        user_pref("mail.server.server2.namespace.other_users", "\"~\"");
        //        user_pref("mail.server.server2.namespace.personal", "\"#mh/\",\"#mhinbox\",\"\"");
        //        user_pref("mail.server.server2.namespace.public", "\"#public/\",\"#news.\",\"#ftp/\",\"#shared/\"");
        //        user_pref("mail.server.server2.timeout", 29);
        //        user_pref("mail.server.server2.type", "imap");
        //        user_pref("mail.server.server2.userName", "hangal");

        // be careful not to match a ...hostname line or a ...namespace line with the .name pattern
        //
        // that's why we need an explicit dot before and a quote after the type of field in the pattern

        // note: there are 2 fields: hostname and realhostname - realhostname has precedence if it exists
        // see: http://forums.mozillazine.org/viewtopic.php?f=39&t=1697195
        Pattern accountNamePat = Pattern.compile(".*\"mail.server.server.*\\.name\".*");
        Pattern hostnamePat = Pattern.compile(".*\"mail.server.server.*\\.hostname\".*");
        Pattern realHostnamePat = Pattern.compile(".*\"mail.server.server.*\\.realhostname\".*");
        Pattern serverTypePat = Pattern.compile(".*\"mail.server.server.*\\.type\".*");
        Pattern usernamePat = Pattern.compile(".*\"mail.server.server.*\\.userName\".*");
        Pattern userRealNamePat = Pattern.compile(".*\"mail.identity.id.*\\.fullName\".*");
        Pattern userEmailPat = Pattern.compile(".*\"mail.identity.id.*\\.useremail\".*");
        Pattern directoryRelPat = Pattern.compile(".*\"mail.server.server.*\\.directory-rel\".*");
        Pattern fccFolderPat = Pattern.compile(".*\"mail.identity.id.*\\.fcc_folder\".*");

        Map<String, String> accountNameMap = new LinkedHashMap<String, String>();
        Map<String, String> hostnameMap = new LinkedHashMap<String, String>();
        Map<String, String> realHostnameMap = new LinkedHashMap<String, String>();
        Map<String, String> serverTypeMap = new LinkedHashMap<String, String>();
        Map<String, String> usernameMap = new LinkedHashMap<String, String>();
        Map<String, String> userEmailMap = new LinkedHashMap<String, String>();
        Map<String, String> userRealNameMap = new LinkedHashMap<String, String>();
        Map<String, String> directoryRelMap = new LinkedHashMap<String, String>();
        Map<String, String> fccFolderMap = new LinkedHashMap<String, String>();

        while (true) {
            String line = lnr.readLine();
            if (line == null) {
                lnr.close();
                break;
            }

            if (accountNamePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                accountNameMap.put(pair.getFirst(), pair.getSecond());
            }
            if (hostnamePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                hostnameMap.put(pair.getFirst(), pair.getSecond());
            }
            if (realHostnamePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                realHostnameMap.put(pair.getFirst(), pair.getSecond());
            } else if (serverTypePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                String serverType = pair.getSecond();
                if ("imap".equals(serverType))
                    serverType = "imaps";
                if ("pop".equals(serverType))
                    serverType = "pops";
                serverTypeMap.put(pair.getFirst(), serverType);
            } else if (usernamePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                usernameMap.put(pair.getFirst(), pair.getSecond());
            } else if (userEmailPat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id");
                userEmailMap.put(pair.getFirst(), pair.getSecond());
            } else if (userRealNamePat.matcher(line).matches()) {
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id");
                userRealNameMap.put(pair.getFirst(), pair.getSecond());
            } else if (directoryRelPat.matcher(line).matches()) {
                // for local folders the line is like user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
                // Convert [ProfD]../../../../../../tmp/tb to the correct path by replacing [ProfD] with the profile dir
                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server");
                String directoryRel = pair.getSecond();
                if (directoryRel != null) {
                    if (directoryRel.startsWith("[ProfD]"))
                        directoryRel = directoryRel.replace("[ProfD]",
                                ThunderbirdUtils.getThunderbirdProfileDir() + File.separator);
                    // we also have to correct the ../../ to \..\... for windows
                    directoryRel = directoryRel.replaceAll("/", File.separator);
                    directoryRelMap.put(pair.getFirst(), directoryRel);
                }
            } else if (fccFolderPat.matcher(line).matches()) {
                // the line looks like user_pref("mail.identity.id1.fcc_folder", "imap://hangal@xenon.stanford.edu/Sent");

                Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id");
                String fccFolderFull = pair.getSecond();
                if (fccFolderFull != null) {
                    // fccFolder imap://hangal@xenon.stanford.edu/Sent
                    String fccFolder = fccFolderFull.replaceAll("[^/]*/+[^/]*/+(.*$)", "$1"); // skip the first 2 tokens, split by /
                    if (!fccFolderFull.equals(fccFolder)) // only if not equal is it valid
                        fccFolderMap.put(pair.getFirst(), fccFolder);
                }
            }
        }

        for (String key : serverTypeMap.keySet()) {
            String s = serverTypeMap.get(key).toLowerCase();
            // we only know how to handle imap and pop and local folders
            // other things like smart folders, don't list.
            if (!s.startsWith("imap") && !s.startsWith("pop")
                    && !"Local Folders".equals(accountNameMap.get(key)))
                continue;

            List<String> params = new ArrayList<String>();
            params.add(accountNameMap.get(key));
            String hostnameToUse = realHostnameMap.get(key);
            if (hostnameToUse == null)
                hostnameToUse = hostnameMap.get(key);
            params.add(hostnameToUse);
            params.add(serverTypeMap.get(key));
            params.add(usernameMap.get(key));
            params.add(userEmailMap.get(key));
            params.add(userRealNameMap.get(key));
            params.add(directoryRelMap.get(key));
            params.add(fccFolderMap.get(key));

            String str = "Tbird accountname=\"" + accountNameMap.get(key) + "\" " + "hostname=\""
                    + hostnameMap.get(key) + "\" " + "serverType=\"" + serverTypeMap.get(key) + "\" "
                    + "username=\"" + usernameMap.get(key) + "\" " + "userEmail=\"" + userEmailMap.get(key)
                    + "\" " + "userRealName=\"" + userRealNameMap.get(key) + "\" " + "directoryRel=\""
                    + directoryRelMap.get(key) + "\"" + "fccFolder=\"" + fccFolderMap.get(key) + "\"";

            EmailUtils.log.debug(str);
            // System.out.println(str);
            result.add(params);
        }

        lnr.close();
    } catch (Exception e) {
        System.err.println("REAL WARNING: exception trying to read thunderbird prefs" + Util.stackTrace(e));
    }

    return Collections.unmodifiableList(result);
}