Example usage for java.io LineNumberReader LineNumberReader

List of usage examples for java.io LineNumberReader LineNumberReader

Introduction

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

Prototype

public LineNumberReader(Reader in) 

Source Link

Document

Create a new line-numbering reader, using the default input-buffer size.

Usage

From source file:mitm.common.postfix.PostfixLogParser.java

public int getRawLogCount(Reader log) throws IOException {
    LineNumberReader lineReader = new LineNumberReader(log);

    int count = 0;

    String line;//from ww w  .ja  v  a  2s. com

    while ((line = lineReader.readLine()) != null) {
        line = StringUtils.trimToNull(line);

        if (line == null) {
            continue;
        }

        if (searchPattern != null) {
            Matcher matcher = searchPattern.matcher(line);

            if (matcher.find()) {
                count++;
            }
        } else {
            count++;
        }
    }

    return count;
}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???iHTML`?j//w  w w . j a  v a2  s.  c om
 * @param time NGXg 
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createHtmlFile(String time, File resultFile, File htmlFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile)));

        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        out.println("<html>");
        out.println("<head><title>MassBank Batch Service Results</title></head>");
        out.println("<body>");
        out.println(
                "<h1><a href=\"http://www.massbank.jp/\" target=\"_blank\">MassBank</a> Batch Service Results</h1>");
        out.println("<hr>");
        out.println("<h2>Request Date : " + time + "<h2>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br><hr>");

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        while ((line = in.readLine()) != null) {
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("<h2>Query " + nf.format(queryCnt) + "</h2><br>");
                out.println("Name: " + line.trim() + "<br>");
                readName = true;
            } else if (!readHit) {
                out.println("Hit: " + nf.format(Integer.parseInt(line.trim())) + "<br>");
                readHit = true;
            } else if (!readNum) {
                out.println("<table border=\"1\">");
                out.println("<tr><td colspan=\"6\">Top " + line.trim() + " List</td></tr>");
                out.println(
                        "<tr><th>Accession</th><th>Title</th><th>Formula</th><th>Ion</th><th>Score</th><th>Hit</th></tr>");
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    String acc = data[0];
                    String title = data[1];
                    String formula = data[2];
                    String ion = data[3];
                    String score = data[4];
                    String hit = data[5];

                    out.println("<tr>");
                    out.println("<td><a href=\"http://www.massbank.jp/jsp/FwdRecord.jsp?id=" + acc
                            + "\" target=\"_blank\">" + acc + "</td>");
                    out.println("<td>" + title + "</td>");
                    out.println("<td>" + formula + "</td>");
                    out.println("<td>" + ion + "</td>");
                    out.println("<td>" + score + "</td>");
                    out.println("<td align=\"right\">" + hit + "</td>");
                    out.println("</tr>");
                } else {
                    out.println("</table>");
                    out.println("<hr>");
                    readName = false;
                    readHit = false;
                    readNum = false;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:org.apache.lucene.search.SearchUtil.java

public void parse(File file) throws IOException, InterruptedException {
    FileInputStream fis = null;/*from  w w  w. j a va  2 s.  c  om*/
    try {
        fis = new FileInputStream(file);
        HTMLParser parser = new HTMLParser(fis);

        //         this.title=Entities.encode(parser.getTitle());
        StringBuilder sb = new StringBuilder();
        LineNumberReader reader = new LineNumberReader(parser.getReader());
        for (String l = reader.readLine(); l != null; l = reader.readLine()) {
            //            System.out.println(l);
            sb.append(l + " ");
        }
        this.contents = sb.toString();
        //         System.out.println("Parsed Contents: "+contents);
    } finally {
        if (fis != null)
            fis.close();
    }
}

From source file:org.haplo.javascript.Runtime.java

/**
 * Initialize the shared JavaScript environment. Loads libraries and removes
 * methods of escaping the sandbox.//from   ww w .  j  a  v  a  2 s .co m
 */
public static void initializeSharedEnvironment(String frameworkRoot, boolean pluginDebuggingEnabled)
        throws java.io.IOException {
    // Don't allow this to be called twice
    if (sharedScope != null) {
        return;
    }

    long startTime = System.currentTimeMillis();

    final Context cx = Runtime.enterContext();
    try {
        final ScriptableObject scope = cx.initStandardObjects(null,
                false /* don't seal the standard objects yet */);

        if (!scope.has("JSON", scope)) {
            throw new RuntimeException(
                    "Expecting built-in JSON support in Rhino, check version is at least 1.7R3");
        }

        if (standardTemplateLoader == null) {
            throw new RuntimeException("StandardTemplateLoader for Runtime hasn't been set.");
        }
        String standardTemplateJSON = standardTemplateLoader.standardTemplateJSON();
        scope.put("$STANDARDTEMPLATES", scope, standardTemplateJSON);
        // Define the HaploTemplate host object now, so the JS code can use it to parse templates
        // TODO: Convert all standard templates from Handlebars, move HaploTemplate host object declaraction back with the others, remove $HaploTemplate from whitelist
        defineSealedHostClass(scope, HaploTemplate.class);

        // Load the library code
        FileReader bootScriptsFile = new FileReader(frameworkRoot + "/lib/javascript/bootscripts.txt");
        LineNumberReader bootScripts = new LineNumberReader(bootScriptsFile);
        String scriptFilename = null;
        while ((scriptFilename = bootScripts.readLine()) != null) {
            FileReader script = new FileReader(frameworkRoot + "/" + scriptFilename);
            cx.evaluateReader(scope, script, scriptFilename, 1, null /* no security domain */);
            script.close();
        }
        bootScriptsFile.close();

        // Insert plugin debugging flag
        if (pluginDebuggingEnabled) {
            Scriptable o = (Scriptable) scope.get("O", scope);
            o.put("PLUGIN_DEBUGGING_ENABLED", o, true);
        }

        // Load the list of allowed globals
        FileReader globalsWhitelistFile = new FileReader(
                frameworkRoot + "/lib/javascript/globalswhitelist.txt");
        HashSet<String> globalsWhitelist = new HashSet<String>();
        LineNumberReader whitelist = new LineNumberReader(globalsWhitelistFile);
        String globalName = null;
        while ((globalName = whitelist.readLine()) != null) {
            String g = globalName.trim();
            if (g.length() > 0) {
                globalsWhitelist.add(g);
            }
        }
        globalsWhitelistFile.close();

        // Remove all the globals which aren't allowed, using a whitelist            
        for (Object propertyName : scope.getAllIds()) // the form which includes the DONTENUM hidden properties
        {
            if (propertyName instanceof String) // ConsString is checked
            {
                // Delete any property which isn't in the whitelist
                if (!(globalsWhitelist.contains(propertyName))) {
                    scope.delete((String) propertyName); // ConsString is checked
                }
            } else {
                // Not expecting any other type of property name in the global namespace
                throw new RuntimeException(
                        "Not expecting global JavaScript scope to contain a property which isn't a String");
            }
        }

        // Run through the globals again, just to check nothing escaped
        for (Object propertyName : scope.getAllIds()) {
            if (!(globalsWhitelist.contains(propertyName))) {
                throw new RuntimeException("JavaScript global was not destroyed: " + propertyName.toString());
            }
        }
        // Run through the whilelist, and make sure that everything in it exists
        for (String propertyName : globalsWhitelist) {
            if (!scope.has(propertyName, scope)) {
                // The whitelist should only contain non-host objects created by the JavaScript source files.
                throw new RuntimeException(
                        "JavaScript global specified in whitelist does not exist: " + propertyName);
            }
        }
        // And make sure java has gone, to check yet again that everything expected has been removed
        if (scope.get("java", scope) != Scriptable.NOT_FOUND) {
            throw new RuntimeException("JavaScript global 'java' escaped destruction");
        }

        // Seal the scope and everything within in, so nothing else can be added and nothing can be changed
        // Asking initStandardObjects() to seal the standard library doesn't actually work, as it will leave some bits
        // unsealed so that decodeURI.prototype.pants = 43; works, and can pass information between runtimes.
        // This recursive object sealer does actually work. It can't seal the main host object class, so that's
        // added to the scope next, with the (working) seal option set to true.
        HashSet<Object> sealedObjects = new HashSet<Object>();
        recursiveSealObjects(scope, scope, sealedObjects, false /* don't seal the root object yet */);
        if (sealedObjects.size() == 0) {
            throw new RuntimeException("Didn't seal any JavaScript globals");
        }

        // Add the host object classes. The sealed option works perfectly, so no need to use a special seal function.
        defineSealedHostClass(scope, KHost.class);
        defineSealedHostClass(scope, KPlatformGenericInterface.class);
        defineSealedHostClass(scope, KObjRef.class);
        defineSealedHostClass(scope, KScriptable.class);
        defineSealedHostClass(scope, KLabelList.class);
        defineSealedHostClass(scope, KLabelChanges.class);
        defineSealedHostClass(scope, KLabelStatements.class);
        defineSealedHostClass(scope, KDateTime.class);
        defineSealedHostClass(scope, KObject.class);
        defineSealedHostClass(scope, KText.class);
        defineSealedHostClass(scope, KQueryClause.class);
        defineSealedHostClass(scope, KQueryResults.class);
        defineSealedHostClass(scope, KPluginAppGlobalStore.class);
        defineSealedHostClass(scope, KPluginResponse.class);
        defineSealedHostClass(scope, KTemplatePartialAutoLoader.class);
        defineSealedHostClass(scope, KAuditEntry.class);
        defineSealedHostClass(scope, KAuditEntryQuery.class);
        defineSealedHostClass(scope, KUser.class);
        defineSealedHostClass(scope, KUserData.class);
        defineSealedHostClass(scope, KWorkUnit.class);
        defineSealedHostClass(scope, KWorkUnitQuery.class);
        defineSealedHostClass(scope, KEmailTemplate.class);
        defineSealedHostClass(scope, KBinaryData.class);
        defineSealedHostClass(scope, KBinaryDataInMemory.class, true /* map inheritance */);
        defineSealedHostClass(scope, KBinaryDataStaticFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KBinaryDataTempFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KUploadedFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KStoredFile.class);
        defineSealedHostClass(scope, KJob.class);
        defineSealedHostClass(scope, KFilePipelineResult.class);
        defineSealedHostClass(scope, KSessionStore.class);
        defineSealedHostClass(scope, KKeychainCredential.class);

        // HaploTemplate created earlier as required by some of the setup
        defineSealedHostClass(scope, HaploTemplateDeferredRender.class);
        defineSealedHostClass(scope, JSFunctionThis.class);
        defineSealedHostClass(scope, GenericDeferredRender.class);

        defineSealedHostClass(scope, KSecurityRandom.class);
        defineSealedHostClass(scope, KSecurityBCrypt.class);
        defineSealedHostClass(scope, KSecurityDigest.class);
        defineSealedHostClass(scope, KSecurityHMAC.class);

        defineSealedHostClass(scope, JdNamespace.class);
        defineSealedHostClass(scope, JdTable.class);
        defineSealedHostClass(scope, JdDynamicTable.class, true /* map inheritance */);
        defineSealedHostClass(scope, JdSelectClause.class);
        defineSealedHostClass(scope, JdSelect.class, true /* map inheritance */);

        defineSealedHostClass(scope, KGenerateTable.class, true /* map inheritance */);
        defineSealedHostClass(scope, KGenerateXLS.class, true /* map inheritance */);

        defineSealedHostClass(scope, KRefKeyDictionary.class);
        defineSealedHostClass(scope, KRefKeyDictionaryHierarchical.class, true /* map inheritance */);
        defineSealedHostClass(scope, KRefSet.class);
        defineSealedHostClass(scope, KCheckingLookupObject.class);
        defineSealedHostClass(scope, WorkUnitTags.class);
        defineSealedHostClass(scope, GetterDictionaryBase.class);
        defineSealedHostClass(scope, InterRuntimeSignal.class);
        defineSealedHostClass(scope, KRequestContinuation.class);
        defineSealedHostClass(scope, JsBigDecimal.class);
        defineSealedHostClass(scope, JsDecimalFormat.class);

        defineSealedHostClass(scope, XmlDocument.class);
        defineSealedHostClass(scope, XmlCursor.class);

        defineSealedHostClass(scope, KCollaborationService.class);
        defineSealedHostClass(scope, KCollaborationFolder.class);
        defineSealedHostClass(scope, KCollaborationItemList.class);
        defineSealedHostClass(scope, KCollaborationItem.class);

        defineSealedHostClass(scope, KAuthenticationService.class);

        defineSealedHostClass(scope, KMessageBusPlatformSupport.class);
        defineSealedHostClass(scope, KUUIDPlatformSupport.class);

        defineSealedHostClass(scope, StdReporting.class);
        defineSealedHostClass(scope, StdWebPublisher.class);
        defineSealedHostClass(scope, StdWebPublisher.RenderedAttributeListView.class);
        defineSealedHostClass(scope, StdWebPublisher.ValueView.class);

        // Seal the root now everything has been added
        scope.sealObject();

        // Check JavaScript TimeZone
        checkJavaScriptTimeZoneIsGMT();

        // Templating integration
        JSPlatformIntegration.parserConfiguration = new TemplateParserConfiguration();
        JSPlatformIntegration.includedTemplateRenderer = new TemplateIncludedRenderer();
        JSPlatformIntegration.platformFunctionRenderer = new TemplateFunctionRenderer();

        sharedScope = scope;
    } finally {
        cx.exit();
    }

    initializeSharedEnvironmentTimeTaken = System.currentTimeMillis() - startTime;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Counts text lines available in input.
 *
 * @param reader//w w w  .  ja v a 2s .com
 *            a {@link java.io.Reader} object to provide the underlying input stream
 * @return number of lines currently available in input
 * @throws java.io.IOException
 *             If an I/O error occurs
 * @deprecated use {@link #countLines(java.io.InputStream)} instead
 */
@Deprecated
public static int countLines(Reader reader) throws IOException {
    int lCount = 0;
    LineNumberReader lineReader = null;
    try {
        lineReader = new LineNumberReader(reader);
        lineReader.skip(Long.MAX_VALUE);
        // NOTE: Add 1 because line index starts at 0
        lCount = lineReader.getLineNumber() + 1;
    } finally {
        close(lineReader);
    }

    return lCount;
}

From source file:org.openadaptor.auxil.connector.socket.SocketWriteConnector.java

protected LineNumberReader getInputStream() throws IOException {
    return new LineNumberReader(new InputStreamReader(socket.getInputStream()));
}

From source file:org.agnitas.web.ImportProfileColumnsAction.java

/**
 * Adds column mappings from uploaded csv-file using import profile settings
 * for parsing csv file//from w  w  w.  j av  a  2 s  .  c o m
 *
 * @param aForm   a form
 * @param request request
 */
private void addColumnsFromFile(ImportProfileColumnsForm aForm, HttpServletRequest request) {
    RecipientDao recipientDao = (RecipientDao) getWebApplicationContext().getBean("RecipientDao");
    if (aForm.getProfile() == null) {
        loadImportProfile(aForm, request);
    }
    ImportProfile profile = aForm.getProfile();
    List<ColumnMapping> columnMappings = profile.getColumnMapping();
    File file = getCurrentFile(request);
    if (file == null) {
        return;
    }
    try {
        Map dbColumns = recipientDao.readDBColumns(AgnUtils.getCompanyID(request));
        String profileCharset = Charset.getValue(profile.getCharset());
        String fileString = FileUtils.readFileToString(file, profileCharset);
        LineNumberReader aReader = new LineNumberReader(new StringReader(fileString));
        String firstLine = aReader.readLine();
        firstLine = firstLine.trim();
        CsvTokenizer tokenizer = new CsvTokenizer(firstLine, Separator.getValue(profile.getSeparator()),
                TextRecognitionChar.getValue(profile.getTextRecognitionChar()));
        String[] newCsvColumns = tokenizer.toArray();
        List<ColumnMapping> newMappings = new ArrayList<ColumnMapping>();
        for (String newCsvColumn : newCsvColumns) {
            if (!aForm.columnExists(newCsvColumn, columnMappings) && !StringUtils.isEmpty(newCsvColumn)) {
                ColumnMapping newMapping = new ColumnMappingImpl();
                newMapping.setProfileId(profile.getId());
                newMapping.setMandatory(false);
                newMapping.setFileColumn(newCsvColumn);
                if (dbColumns.get(newCsvColumn) != null) {
                    String dbColumn = getInsensetiveMapKey(dbColumns, newCsvColumn);
                    if (dbColumn == null) {
                        // if dbColumn is NULL mapping is invalid
                        continue;
                    }
                    newMapping.setDatabaseColumn(dbColumn);
                    String defaultValue = aForm.getDbColumnsDefaults().get(dbColumn);
                    if (defaultValue != null) {
                        newMapping.setDefaultValue(defaultValue);
                    }
                }
                newMappings.add(newMapping);
            }
        }
        profile.getColumnMapping().addAll(newMappings);
    } catch (IOException e) {
        AgnUtils.logger().error("Error reading csv-file: " + e + "\n" + AgnUtils.getStackTrace(e));
    } catch (Exception e) {
        AgnUtils.logger().error("Error reading csv-file: " + e + "\n" + AgnUtils.getStackTrace(e));
    }

}

From source file:com.haulmont.cuba.uberjar.ServerRunner.java

protected void stop(int port, String key) {
    try {/*from  www.j a  v  a  2s .  co  m*/
        try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"), port)) {
            s.setSoTimeout(STOP_TIMEOUT * 1000);
            try (OutputStream out = s.getOutputStream()) {
                out.write((key + "\r\nstop\r\n").getBytes(StandardCharsets.UTF_8));
                out.flush();
                System.out.println(String.format("Waiting %,d seconds for server to stop", STOP_TIMEOUT));
                LineNumberReader lin = new LineNumberReader(
                        new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
                String response;
                while ((response = lin.readLine()) != null) {
                    System.out.println(String.format("Received \"%s\"", response));
                    if ("Stopped".equals(response)) {
                        System.out.println("Server reports itself as Stopped");
                    }
                }
            }
        }
    } catch (SocketTimeoutException e) {
        System.out.println("Timed out waiting for stop confirmation");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.stanford.muse.index.Indexer.java

public static Set<String> readStreamAndInternStrings(Reader r) {
    Set<String> result = new LinkedHashSet<String>();
    try {// ww  w .  j a  v a2 s  . c  o m
        LineNumberReader lnr = new LineNumberReader(r);
        while (true) {
            String word = lnr.readLine();
            if (word == null) {
                lnr.close();
                break;
            }
            word = word.trim();
            if (word.startsWith("#") || word.length() == 0)
                continue;
            word = IndexUtils.canonicalizeMultiWordTerm(word, false); // TOFIX: not really sure if stemming shd be off
            word = InternTable.intern(word);
            result.add(word);
        }
    } catch (IOException e) {
        log.warn("Exception reading reader " + r + ": " + e + Util.stackTrace(e));
    }

    return result;
}

From source file:org.apache.pig.scripting.Pig.java

private static String getScriptFromFile(String filename) throws IOException {
    LineNumberReader rd = new LineNumberReader(new FileReader(filename));
    StringBuilder sb = new StringBuilder();
    try {//from  w w w.  j  a v  a 2 s. c o  m
        String line = rd.readLine();
        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = rd.readLine();
        }
    } finally {
        rd.close();
    }
    return sb.toString();
}