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:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java

/** See if we have a url for the service. If not discover the real one.
 *
 * @param hi//from   w  w w .  ja v a 2  s. co  m
 */
private void discover(final HostInfo hi) throws CalFacadeException {
    if (hi.getIScheduleUrl() != null) {
        return;
    }

    /* For the moment we'll try to find it via .well-known. We may have to
     * use DNS SRV lookups
     */
    //    String domain = hi.getHostname();

    //  int lpos = domain.lastIndexOf(".");
    //int lpos2 = domain.lastIndexOf(".", lpos - 1);

    //    if (lpos2 > 0) {
    //    domain = domain.substring(lpos2 + 1);
    //}

    int rcode = 0;

    BasicHttpClient cio = null;

    try {
        /*
        // XXX ioptest fix - remove
        String url;
        if ("example.com".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else if ("ken.name".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else {
          url = "https://" + hi.getHostname() + "/.well-known/ischedule";
        }
        */

        final String scheme;
        final String port;

        if (hi.getPort() == 0) {
            port = "";
        } else {
            port = ":" + hi.getPort();
        }

        if (hi.getSecure()) {
            scheme = "https://";
        } else {
            scheme = "http://";
        }

        String url = scheme + hi.getHostname() + port + "/.well-known/ischedule";

        cio = getCio(url);

        for (int redirects = 0; redirects < 10; redirects++) {
            rcode = cio.sendRequest("GET", url + "?action=capabilities", null, "application/xml", 0, null);

            if ((rcode == HttpServletResponse.SC_MOVED_PERMANENTLY)
                    || (rcode == HttpServletResponse.SC_MOVED_TEMPORARILY)
                    || (rcode == HttpServletResponse.SC_TEMPORARY_REDIRECT)) {
                //boolean permanent = rcode == HttpServletResponse.SC_MOVED_PERMANENTLY;

                Header locationHeader = cio.getFirstHeader("location");
                if (locationHeader != null) {
                    if (debug) {
                        debugMsg("Got redirected to " + locationHeader.getValue() + " from " + url);
                    }

                    String newLoc = locationHeader.getValue();
                    int qpos = newLoc.indexOf("?");

                    cioTable.remove(url);

                    if (qpos < 0) {
                        url = newLoc;
                    } else {
                        url = newLoc.substring(0, qpos);
                    }

                    cio.release();

                    // Try again
                    continue;
                }
            }

            if (rcode != HttpServletResponse.SC_OK) {
                // The response is invalid and did not provide the new location for
                // the resource.  Report an error or possibly handle the response
                // like a 404 Not Found error.
                if (debug) {
                    error("Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);

                    if (cio.getResponseContentLength() != 0) {
                        InputStream is = cio.getResponseBodyAsStream();

                        LineNumberReader in = new LineNumberReader(new InputStreamReader(is));

                        error("Content: ==========================");
                        while (true) {
                            String l = in.readLine();
                            if (l == null) {
                                break;
                            }

                            error(l);
                        }
                        error("End content: ==========================");
                    }
                }

                throw new CalFacadeException(
                        "Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);
            }

            /* Should have a capabilities record. */

            hi.setIScheduleUrl(url);
            return;
        }

        if (debug) {
            error("Too many redirects: Got response " + rcode + ", host " + hi.getHostname() + " and url "
                    + url);
        }

        throw new CalFacadeException("Too many redirects on " + url);
    } catch (CalFacadeException cfe) {
        throw cfe;
    } catch (Throwable t) {
        if (debug) {
            error(t);
        }

        throw new CalFacadeException(t);
    } finally {
        try {
            if (cio != null) {
                cio.release();
            }
        } catch (Throwable t) {
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Check if file has persisted state defined line and returns corresponding line number in file.
 *
 * @param file//from   w ww.  j a  v  a  2 s  . c om
 *            file to find line matching CRC
 * @param fileAccessState
 *            persisted streamed files access state
 *
 * @return line number matching CRC, or {@code 0} if line not found
 *
 * @throws IOException
 *             if I/O exception occurs
 */
int checkLine(T file, FileAccessState fileAccessState) throws IOException {
    LineNumberReader reader = null;
    try {
        reader = new LineNumberReader(openFile(file));
        // skip lines until reaching line with number: persisted line number
        // - LINE_SHIFT_TOLERANCE
        int lastAccessedLine = getLastReadLineNumber();

        int startCompareLineIndex = lastAccessedLine - LINE_SHIFT_TOLERANCE;
        int endCompareLineIndex = lastAccessedLine + LINE_SHIFT_TOLERANCE;
        String line;
        int li = 0;
        while (((line = reader.readLine()) != null) && (li <= endCompareLineIndex)) {
            li = reader.getLineNumber();

            if (li >= startCompareLineIndex) {
                if (checkCrc(line, fileAccessState.currentLineCrc)) {
                    return li;
                }
            }
        }
    } finally {
        Utils.close(reader);
    }

    return 0;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Read lines from an inputstream.// w  w w.  java  2  s.c  om
 * @param is the InputStream
 * @param close if set to true, after reading the input stream would be closed.
 * @param start the line of the file to read from. Line starts from 0. 
 * If count is 1, 1 line would be skipped.
 * @param end the line of the file to stop reading. The end line is included.
 * @return an collection of the lines read
 */
public static List readLinesFromStream(InputStream is, boolean close, int start, int end) {
    if (is == null) {
        return null;
    }
    ArrayList a = new ArrayList();
    Reader r = null;
    LineNumberReader lr = null;
    try {
        r = new InputStreamReader(is);
        lr = new LineNumberReader(r);
        String line = null;
        do {
            line = lr.readLine();
            int currLine = lr.getLineNumber();
            if (start > 0 && end > 0 && currLine >= start && currLine <= end) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (start == START_OF_FILE && end == END_OF_FILE) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (end > 0 && currLine > end) {
                break;
            }
        } while (line != null);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (close) {
            try {
                lr.close();
            } catch (Exception e) {
            }
            try {
                r.close();
            } catch (Exception e) {
            }
        }
        lr = null;
        r = null;
    }
    return a;
}

From source file:org.silverpeas.core.silvertrace.DefaultSilverpeasTrace.java

@Deprecated
@Override//from w  w  w .  j av a 2s . c  o  m
public String[] getEndFileTrace(String nbLines) {
    LineNumberReader lnr = null;
    File theFile = new File(errorDir + "/traces.txt");
    List<String> ar = new ArrayList<String>();
    try {
        // Get file length
        long fileLength = theFile.length();
        if (fileLength == 0L) {
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        int nbl = Integer.parseInt(nbLines);
        lnr = new LineNumberReader(new FileReader(theFile));
        if (nbl > 0) {
            if ((nbl + 1) * 100 < fileLength) {
                lnr.skip(fileLength - ((nbl + 1) * 100));
            }
        }
        String line = lnr.readLine();
        while (line != null) {
            line = lnr.readLine();
            if (line != null) {
                ar.add(line);
            }
        }
        return ar.toArray(new String[ar.size()]);
    } catch (Exception e) {
        error("silvertrace", "SilverTrace.getEndFileTrace()", "silvertrace.ERR_RUNTIME_ERROR_OCCUR",
                "File NOT FOUND :" + errorDir + "/traces.txt", e);
        return ArrayUtils.EMPTY_STRING_ARRAY;
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}

From source file:com.stratelia.silverpeas.silvertrace.SilverTrace.java

static public String[] getEndFileTrace(String nbLines) {
    LineNumberReader lnr = null;
    File theFile = new File(errorDir + "/traces.txt");
    List<String> ar = new ArrayList<String>();
    try {/*from   ww w .  ja  v  a 2 s.  c  o  m*/
        // Get file length
        long fileLength = theFile.length();
        if (fileLength == 0L) {
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        int nbl = Integer.parseInt(nbLines);
        lnr = new LineNumberReader(new FileReader(theFile));
        if (nbl > 0) {
            if ((nbl + 1) * 100 < fileLength) {
                lnr.skip(fileLength - ((nbl + 1) * 100));
            }
        }
        String line = lnr.readLine();
        while (line != null) {
            line = lnr.readLine();
            if (line != null) {
                ar.add(line);
            }
        }
        return ar.toArray(new String[ar.size()]);
    } catch (Exception e) {
        SilverTrace.error("silvertrace", "SilverTrace.getEndFileTrace()", "silvertrace.ERR_RUNTIME_ERROR_OCCUR",
                "File NOT FOUND :" + errorDir + "/traces.txt", e);
        return ArrayUtils.EMPTY_STRING_ARRAY;
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}

From source file:lineage2.gameserver.Config.java

/**
 * Method abuseLoad./*from   w  w  w.j a v a 2  s.  c o  m*/
 */
public static void abuseLoad() {
    List<Pattern> tmp = new ArrayList<Pattern>();
    LineNumberReader lnr = null;
    try {
        String line;
        lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(ANUSEWORDS_CONFIG_FILE), "UTF-8"));
        while ((line = lnr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, "\n\r");
            if (st.hasMoreTokens()) {
                tmp.add(Pattern.compile(".*" + st.nextToken() + ".*",
                        Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
            }
        }
        ABUSEWORD_LIST = tmp.toArray(new Pattern[tmp.size()]);
        tmp.clear();
        _log.info("Abuse: Loaded " + ABUSEWORD_LIST.length + " abuse words.");
    } catch (IOException e1) {
        _log.warn("Error reading abuse: " + e1);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception e2) {
        }
    }
}

From source file:org.kalypso.model.hydrology.internal.postprocessing.LzsToGml.java

private void readLzsFile(final FileReader fileReader, final Catchment catchment, final Feature lzCatchmentFE)
        throws Exception {
    final LineNumberReader reader = new LineNumberReader(fileReader);

    final IFeatureType lzCatchmentFT = GMLSchemaUtilities
            .getFeatureTypeQuiet(new QName(NaModelConstants.NS_INIVALUES, "Catchment")); //$NON-NLS-1$
    final IRelationType lzinitHydMemberRT = (IRelationType) lzCatchmentFT
            .getProperty(NaModelConstants.INI_CATCHMENT_LINK_HYD_PROP);

    final String iniDate = m_dateFormat.format(m_initialDate);
    int maxHydros = 0;
    int counterHydros = 0;
    // TODO: why compare the datum? IT would be more robust to just read all data that is in the lsz file, and append
    // it to the features!

    CatchmentStatus status = CatchmentStatus.SEARCH_HEADER;
    while (reader.ready()) {
        final String line = reader.readLine();
        if (line == null)
            break;

        final String cleanLine = line.trim().replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
        switch (status) {
        case SEARCH_HEADER:
            final Matcher matcherBODF = PATTERN_HEADER_BODF.matcher(cleanLine);
            if (cleanLine.endsWith("snow") && cleanLine.startsWith(iniDate)) //$NON-NLS-1$
                status = CatchmentStatus.READ_SNOW;
            else if (cleanLine.endsWith("gwsp") && cleanLine.startsWith(iniDate)) //$NON-NLS-1$
                status = CatchmentStatus.READ_GWSP;
            else if (matcherBODF.matches() && cleanLine.startsWith(iniDate)) {
                status = CatchmentStatus.READ_BODF;
                maxHydros = Integer.parseInt(matcherBODF.group(2));
            }/*from w  w  w.ja va2  s .c  o m*/
            break;

        case READ_BODF: {
            final Feature lzHydFE = m_lzWorkspace.createFeature(lzCatchmentFE, lzinitHydMemberRT,
                    lzinitHydMemberRT.getTargetFeatureType());
            m_lzWorkspace.addFeatureAsComposition(lzCatchmentFE, lzinitHydMemberRT, 0, lzHydFE);
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final int pos = Integer.parseInt(strings[0]) - 1;
            final String hydroID = m_hydroHash.getHydroFeatureId(catchment, pos);
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "featureId"), hydroID); //$NON-NLS-1$
            final Double interception = Double.valueOf(strings[1]);
            final List<Double> bofs = new ArrayList<>();
            for (int i = 2; i < strings.length; i++) {
                final Double bf = Double.valueOf(strings[i]);
                bofs.add(bf);
            }
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "bi"), interception); //$NON-NLS-1$
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "bofs"), bofs); //$NON-NLS-1$
            counterHydros++;
            if (counterHydros >= maxHydros) {
                status = CatchmentStatus.SEARCH_HEADER;
                counterHydros = 0;
            }
        }
            break;

        case READ_GWSP: {
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final Double hgws = Double.valueOf(strings[1]);// hoehe gw
            final Double qb = Double.valueOf(strings[2]);// basisabfluss
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "hgws"), hgws); //$NON-NLS-1$
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "qb"), qb); //$NON-NLS-1$
            status = CatchmentStatus.SEARCH_HEADER;
        }
            break;

        case READ_SNOW:
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final Double h = Double.valueOf(strings[1]);// hoehe schnee
            final Double ws = Double.valueOf(strings[2]);// wassergehalt
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "h"), h); //$NON-NLS-1$
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "ws"), ws); //$NON-NLS-1$
            status = CatchmentStatus.SEARCH_HEADER;
            break;
        }
    } // TODO: if we reach this line without any read data, something is wrong!
}

From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private WimbaResponse getResponseDocument(String rawResponse) {
    StringReader input = new StringReader(rawResponse);
    LineNumberReader reader = new LineNumberReader(input);

    WimbaResponse response = new WimbaResponse();
    String line;//from ww  w  .  ja v  a 2  s .c  o  m
    Map<String, String> record = new HashMap<String, String>();
    try {
        // start with status code in first line
        line = reader.readLine();
        response.setStatus(getStatusCode(line));
        // read the records following
        while ((line = reader.readLine()) != null) {
            if (line.equals(DELIM)) {
                // end of record
                response.addRecord(record);
                record = new HashMap<String, String>();
            } else {
                // regular part of a record
                String[] elem = line.split("=", 2);
                record.put(elem[0], elem[1]);
            }
        }
    } catch (IOException e) {
        logError("The Wimba Classroom response could not parsed. Raw response: " + rawResponse, e);
    }

    return response;
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Retrieve lines of text from an input stream
 *
 * @param is              The input stream to read
 * @param startLineNumber The starting line number
 * @param endLineNumber   The ending line number
 *
 * @return The text contained in line numbers startingLineNumber to endingLineNumber
 *///w  w w.j av a 2  s.  c  o  m
public String getTextStreamLines(InputStream is, int startLineNumber, int endLineNumber) throws IOException {
    if (is == null)
        return null;

    if (startLineNumber <= 0 && endLineNumber <= 0)
        return null;

    Reader isReader = null;
    LineNumberReader reader = null;
    StringBuffer result = new StringBuffer();

    try {
        isReader = new InputStreamReader(is);
        reader = new LineNumberReader(isReader);

        String line = null;

        if (startLineNumber > 0 && endLineNumber <= 0) {
            while ((line = reader.readLine()) != null) {
                if (reader.getLineNumber() == startLineNumber)
                    return line;
            }

        } else {
            while ((line = reader.readLine()) != null) {
                int lineNumber = reader.getLineNumber();

                if (lineNumber < startLineNumber)
                    continue;

                if (lineNumber > endLineNumber)
                    break;

                result.append(line);
                result.append("\n");
            }
        }
    } finally {
        if (reader != null)
            reader.close();

        if (isReader != null)
            is.close();

        is.close();
    }

    return result.toString();
}

From source file:org.opencms.synchronize.CmsSynchronize.java

/**
 * Reads the synchronization list from the last sync process form the file
 * system and stores the information in a HashMap. <p>
 * /*from   w  ww  .  j  a  va  2 s .  c o  m*/
 * Filenames are stored as keys, CmsSynchronizeList objects as values.
 * @return HashMap with synchronization information of the last sync process
 * @throws CmsException if something goes wrong
 */
private HashMap readSyncList() throws CmsException {

    HashMap syncList = new HashMap();

    // the sync list file in the server fs
    File syncListFile;
    syncListFile = new File(m_destinationPathInRfs, SYNCLIST_FILENAME);
    // try to read the sync list file if it is there
    if (syncListFile.exists()) {
        // prepare the streams to write the data
        FileReader fIn = null;
        LineNumberReader lIn = null;
        try {
            fIn = new FileReader(syncListFile);
            lIn = new LineNumberReader(fIn);
            // read one line from the file
            String line = lIn.readLine();
            while (line != null) {
                line = lIn.readLine();
                // extract the data and create a CmsSychroizedList object
                //  from it
                if (line != null) {
                    StringTokenizer tok = new StringTokenizer(line, ":");
                    String resName = tok.nextToken();
                    String tranResName = tok.nextToken();
                    long modifiedVfs = new Long(tok.nextToken()).longValue();
                    long modifiedFs = new Long(tok.nextToken()).longValue();
                    CmsSynchronizeList sync = new CmsSynchronizeList(resName, tranResName, modifiedVfs,
                            modifiedFs);
                    syncList.put(translate(resName), sync);
                }
            }
        } catch (IOException e) {
            throw new CmsSynchronizeException(Messages.get().container(Messages.ERR_READ_SYNC_LIST_0), e);
        } finally {
            // close all streams that were used
            try {
                if (lIn != null) {
                    lIn.close();
                }
                if (fIn != null) {
                    fIn.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return syncList;
}