Example usage for java.io LineNumberReader getLineNumber

List of usage examples for java.io LineNumberReader getLineNumber

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

Get the current line number.

Usage

From source file:org.yccheok.jstock.gui.Utils.java

/**
 * Returns number of lines in a file./*w  w  w  .  j a  v a2s  .  c  o m*/
 * 
 * @param file The file
 * @return number of lines in a file
 */
public static int numOfLines(File file, boolean skipMetadata) {
    int line = 0;
    int metaLineNumber = 0;

    LineNumberReader lnr = null;
    try {
        lnr = new LineNumberReader(new FileReader(file));

        if (skipMetadata) {
            String nextLine = lnr.readLine();
            // Metadata handling.
            while (nextLine != null) {
                String[] tokens = nextLine.split("=", 2);
                if (tokens.length == 2) {
                    String key = tokens[0].trim();
                    if (key.length() > 0) {
                        // Is OK for value to be empty.
                        metaLineNumber++;
                        nextLine = lnr.readLine();
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        lnr.skip(Long.MAX_VALUE);
        line = lnr.getLineNumber();
    } catch (IOException ex) {
        log.error(null, ex);
    } finally {
        org.yccheok.jstock.file.Utils.close(lnr);
    }

    return line - metaLineNumber;
}

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

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 */// w  w w  . j a  va2  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:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *//*from  w ww .ja v a 2  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:net.pms.dlna.RootFolder.java

private void addWebFolder(File webConf) {
    if (webConf.exists()) {
        try {/*www  .java 2  s.c o  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.castis.sysComp.PoisConverterSysComp.java

public void parseViewCountFile(File file) throws Exception {
    String line = "";
    FileInputStream in = null;//  www. j a  v a2  s . c  o  m
    Reader isReader = null;
    LineNumberReader bufReader = null;
    if (file.getName().contains("channel")) {
        type = "channel";
    } else {
        type = "vod";
    }

    try {
        String encodingCharset = FILE_CHARSET;

        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;

        while ((line = bufReader.readLine()) != null) {
            if (line.length() == 0) {
                continue;
            }

            InputDataDTO data = new InputDataDTO();
            String result[] = line.split("\\|");
            if (first == true && result.length <= 1) {
                first = false;
                continue;
            }

            if (result[0] == null || result[0].equals("")) {
                throw new DataParsingException("data parsing error(region)");
            }

            if (result[1] == null || result[1].equals("")) {
                throw new DataParsingException("data parsing error(category)");
            }

            if (result[2] == null || result[2].equals("")) {
                throw new DataParsingException("data parsing error(weekday)");
            }

            if (result[3] == null || result[3].equals("")) {
                throw new DataParsingException("data parsing error(hour)");
            }

            if (result[4] == null || result[4].equals("")) {
                throw new DataParsingException("data parsing error(platform)");
            }

            if (result[5] == null || result[5].equals("")) {
                throw new DataParsingException("data parsing error(count)");
            }

            String platform = result[4];

            if (platform != null && platform.equalsIgnoreCase("stb"))
                platform = "STB";
            else if (platform != null && platform.equalsIgnoreCase("mobile")) {
                platform = "Mobile";
            }
            data.setPlatform(platform);

            List<TreeNodeDTO> tree = treeMap.get(platform);

            if (tree == null) {
                tree = getAxis(platform);
                treeMap.put(platform, tree);
            }

            String fullpath = getFullPath(tree, result[0]);

            if (fullpath == "") {
                throw new DataParsingException("region ID[" + result[0] + "] can't find fullpath.");
            }

            data.setRegion(fullpath);
            data.setCategory(result[1]);
            data.setWeekday(result[2]);
            data.setHour(result[3]);
            data.setCount(Integer.parseInt(result[5]));

            insertTreeNode(data);
        }

        for (WeekHourPair key : trees.keySet()) {
            Map<String, TreeNodeForCount> map = trees.get(key);
            calculateCount(map);
        }

        writeFile(file);

    } catch (Exception e) {
        String errorMsg = "Fail to parsing Line.[current line(" + bufReader.getLineNumber() + ") :" + line
                + "] : ";
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

private void writeFile(File file) throws IOException {

    Map<String, String> middleNodeMap = new HashMap<String, String>();

    String line = "";
    FileInputStream in = null;/* www . java 2  s . c o m*/
    Reader isReader = null;
    LineNumberReader bufReader = null;

    FileOutputStream fos = null;
    String dir = filePolling.getValidFileDirectory(resultDir);

    String fileName = file.getName();

    int index = fileName.indexOf("-");
    if (index != -1) {
        fileName = fileName.substring(index + 1, fileName.length());
    }

    String tempDir = dir + "/temp/";
    File targetDirectory = new File(CiFileUtil.getReplaceFullPath(tempDir));
    if (!targetDirectory.isDirectory()) {
        CiFileUtil.createDirectory(tempDir);
    }

    fos = new FileOutputStream(tempDir + fileName);
    int byteSize = 2048;
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(byteSize);
    GatheringByteChannel outByteCh = fos.getChannel();

    try {
        String encodingCharset = FILE_CHARSET;
        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;
        while ((line = bufReader.readLine()) != null) {

            if (line.length() == 0) {
                continue;
            }

            InputDataDTO data = new InputDataDTO();
            String result[] = line.split("\\|");

            if (first == true && result.length <= 1) {
                first = false;
                continue;
            }
            String platform = result[4];

            if (platform != null && platform.equalsIgnoreCase("stb"))
                platform = "STB";
            else if (platform != null && platform.equalsIgnoreCase("mobile")) {
                platform = "Mobile";
            }
            data.setPlatform(platform);

            List<TreeNodeDTO> tree = treeMap.get(platform);

            if (tree == null) {
                tree = getAxis(platform);
                treeMap.put(platform, tree);
            }

            String fullpath = getFullPath(tree, result[0]);

            data.setRegion(fullpath);
            data.setCategory(result[1]);
            data.setWeekday(result[2]);
            data.setHour(result[3]);
            data.setCount(Integer.parseInt(result[5]));

            List<subDataDTO> subDataList = writeNodeInfoOnFile(byteSize, byteBuffer, outByteCh, data, "Y");
            if (subDataList != null && subDataList.size() > 0) {
                writeMiddleNode(byteSize, byteBuffer, outByteCh, data, middleNodeMap, subDataList, "N");
            }
        }

        fos.close();

        index = fileName.indexOf("_");

        String targetDir = resultDir;
        File sourceFile = new File(tempDir + fileName);
        if (index != -1) {
            String directory = fileName.substring(0, index);
            targetDir += "/viewCount/" + directory;
        }

        try {

            File resultTargetDir = new File(CiFileUtil.getReplaceFullPath(targetDir));
            if (!resultTargetDir.isDirectory()) {
                CiFileUtil.createDirectory(targetDir);
            }

            CiFileUtil.renameFile(sourceFile, targetDir, fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    } catch (Exception e) {
        String errorMsg = "Fail to parsing Line.[current line(" + bufReader.getLineNumber() + ") :" + line
                + "] : ";
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseRegionFile(File file) throws Exception {
    String line = "";
    FileInputStream in = null;/*from w  ww .j a va2s.c  o m*/
    Reader isReader = null;
    LineNumberReader bufReader = null;

    FileOutputStream fos = null;
    String fileName = file.getName();

    int index = fileName.indexOf("-");
    if (index != -1) {
        fileName = fileName.substring(index + 1, fileName.length());
    }

    String dir = filePolling.getValidFileDirectory(resultDir);

    String tempDir = dir + "/temp/";
    File targetDirectory = new File(CiFileUtil.getReplaceFullPath(tempDir));
    if (!targetDirectory.isDirectory()) {
        CiFileUtil.createDirectory(tempDir);
    }

    fos = new FileOutputStream(tempDir + fileName);

    int byteSize = 2048;
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(byteSize);
    GatheringByteChannel outByteCh = fos.getChannel();

    try {
        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, "UTF-16LE");
        bufReader = new LineNumberReader(isReader);

        boolean first = true;
        while ((line = bufReader.readLine()) != null) {

            byte[] utf8 = line.getBytes("UTF-8");
            String string = new String(utf8, "UTF-8");

            String data[] = string.split("\t");

            if (first == true) {
                first = false;

                if (data[0] == null || data[0].contains("region") == false) {
                    throw new DataParsingException("data parsing error(not formatted)");
                }
                continue;
            }

            if (data[0] == null || data[0].equals("")) {
                throw new DataParsingException("data parsing error(region id)");
            }
            if (data[1] == null || data[1].equals("")) {
                throw new DataParsingException("data parsing error(region name)");
            }
            if (data[2] == null || data[2].equals("")) {
                throw new DataParsingException("data parsing error(parent id)");
            }

            StringBuffer strBuffer = new StringBuffer();
            strBuffer.append(data[0]);
            strBuffer.append("\t");
            strBuffer.append(data[1]);
            strBuffer.append("\t");
            strBuffer.append(data[2]);

            strBuffer.append("\r\n");

            byte[] outByte = null;
            try {
                outByte = strBuffer.toString().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e2) {
                e2.printStackTrace();
            }
            byteBuffer.put(outByte);
            byteBuffer.flip();
            try {
                outByteCh.write(byteBuffer);
            } catch (IOException e) {
            }
            byteBuffer.clear();
        }

        fos.close();

        index = fileName.indexOf("_");

        String targetDir = resultDir;
        File sourceFile = new File(tempDir + fileName);
        if (index != -1) {
            String directory = fileName.substring(0, index);
            targetDir += "/" + directory;
        }

        try {

            File resultTargetDir = new File(CiFileUtil.getReplaceFullPath(targetDir));
            if (!resultTargetDir.isDirectory()) {
                CiFileUtil.createDirectory(targetDir);
            }

            CiFileUtil.renameFile(sourceFile, targetDir, fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    } catch (Exception e) {
        String errorMsg = "Fail to parsing Line.[current line(" + bufReader.getLineNumber() + ") :" + line
                + "] : ";
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }
}