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:org.apache.pdfbox.text.TestTextStripper.java

/**
 * Validate text extraction on a single file.
 *
 * @param inFile The PDF file to validate
 * @param outDir The directory to store the output in
 * @param bLogResult Whether to log the extracted text
 * @param bSort Whether or not the extracted text is sorted
 * @throws Exception when there is an exception
 *///from w  w w  . j  a v  a  2  s.  c o  m
public void doTestFile(File inFile, File outDir, boolean bLogResult, boolean bSort) throws Exception {
    if (bSort) {
        log.info("Preparing to parse " + inFile.getName() + " for sorted test");
    } else {
        log.info("Preparing to parse " + inFile.getName() + " for standard test");
    }

    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw (new Exception("Error creating " + outDir.getAbsolutePath() + " directory"));
        }
    }

    //System.out.println("  " + inFile + (bSort ? " (sorted)" : ""));
    PDDocument document = PDDocument.load(inFile);
    try {
        File outFile;
        File diffFile;
        File expectedFile;

        if (bSort) {
            outFile = new File(outDir, inFile.getName() + "-sorted.txt");
            diffFile = new File(outDir, inFile.getName() + "-sorted-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + "-sorted.txt");
        } else {
            outFile = new File(outDir, inFile.getName() + ".txt");
            diffFile = new File(outDir, inFile.getName() + "-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + ".txt");
        }

        // delete possible leftover
        diffFile.delete();

        OutputStream os = new FileOutputStream(outFile);
        try {
            os.write(0xEF);
            os.write(0xBB);
            os.write(0xBF);

            Writer writer = new BufferedWriter(new OutputStreamWriter(os, ENCODING));
            try {
                //Allows for sorted tests 
                stripper.setSortByPosition(bSort);
                stripper.writeText(document, writer);
            } finally {
                // close the written file before reading it again
                writer.close();
            }
        } finally {
            os.close();
        }

        if (bLogResult) {
            log.info("Text for " + inFile.getName() + ":");
            log.info(stripper.getText(document));
        }

        if (!expectedFile.exists()) {
            this.bFail = true;
            log.error("FAILURE: Input verification file: " + expectedFile.getAbsolutePath() + " did not exist");
            return;
        }

        boolean localFail = false;

        LineNumberReader expectedReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(expectedFile), ENCODING));
        LineNumberReader actualReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(outFile), ENCODING));

        while (true) {
            String expectedLine = expectedReader.readLine();
            while (expectedLine != null && expectedLine.trim().length() == 0) {
                expectedLine = expectedReader.readLine();
            }
            String actualLine = actualReader.readLine();
            while (actualLine != null && actualLine.trim().length() == 0) {
                actualLine = actualReader.readLine();
            }
            if (!stringsEqual(expectedLine, actualLine)) {
                this.bFail = true;
                localFail = true;
                log.error("FAILURE: Line mismatch for file " + inFile.getName() + " (sort = " + bSort + ")"
                        + " at expected line: " + expectedReader.getLineNumber() + " at actual line: "
                        + actualReader.getLineNumber() + "\nexpected line was: \"" + expectedLine + "\""
                        + "\nactual line was:   \"" + actualLine + "\"" + "\n");

                //lets report all lines, even though this might produce some verbose logging
                //break;
            }

            if (expectedLine == null || actualLine == null) {
                break;
            }
        }
        expectedReader.close();
        actualReader.close();
        if (!localFail) {
            outFile.delete();
        } else {
            // https://code.google.com/p/java-diff-utils/wiki/SampleUsage
            List<String> original = fileToLines(expectedFile);
            List<String> revised = fileToLines(outFile);

            // Compute diff. Get the Patch object. Patch is the container for computed deltas.
            Patch patch = DiffUtils.diff(original, revised);

            PrintStream diffPS = new PrintStream(diffFile, ENCODING);
            for (Object delta : patch.getDeltas()) {
                if (delta instanceof ChangeDelta) {
                    ChangeDelta cdelta = (ChangeDelta) delta;
                    diffPS.println("Org: " + cdelta.getOriginal());
                    diffPS.println("New: " + cdelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof DeleteDelta) {
                    DeleteDelta ddelta = (DeleteDelta) delta;
                    diffPS.println("Org: " + ddelta.getOriginal());
                    diffPS.println("New: " + ddelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof InsertDelta) {
                    InsertDelta idelta = (InsertDelta) delta;
                    diffPS.println("Org: " + idelta.getOriginal());
                    diffPS.println("New: " + idelta.getRevised());
                    diffPS.println();
                } else {
                    diffPS.println(delta);
                }
            }
            diffPS.close();
        }
    } finally {
        document.close();
    }
}

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

@Deprecated
@Override//from w  ww. j a va2s  .  co 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.castis.sysComp.PoisConverterSysComp.java

private void writeFile(File file) throws IOException {

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

    String line = "";
    FileInputStream in = null;//from  ww w  .j  a  v  a  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:mitm.common.postfix.PostfixLogParser.java

public List<String> getRawLogItems(Reader log, final int startIndex, final int maxItems) throws IOException {
    if (startIndex < 0) {
        throw new IllegalArgumentException("startIndex must be >= 0");
    }// ww w.j a  v a2 s . c  om

    if (maxItems <= 0) {
        throw new IllegalArgumentException("maxItems must be > 0");
    }

    List<String> logLines = new LinkedList<String>();

    LineNumberReader lineReader = new LineNumberReader(log);

    int index = 0;

    String line;

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

        if (line == null) {
            continue;
        }

        if (searchPattern == null) {
            if (index >= startIndex) {
                logLines.add(line);
            }

            index++;
        } else {
            /*
             * Search pattern is given. We *must* always check if there is a match
             * before doing anything else
             */
            Matcher matcher = searchPattern.matcher(line);

            if (matcher.find()) {
                if (index >= startIndex) {
                    logLines.add(line);
                }

                index++;
            }
        }

        if (logLines.size() > maxItems) {
            break;
        }
    }

    return logLines;
}

From source file:com.oneis.javascript.Runtime.java

/**
 * Initialize the shared JavaScript environment. Loads libraries and removes
 * methods of escaping the sandbox./*from ww w .  ja  va2s  .co  m*/
 */
public static void initializeSharedEnvironment(String frameworkRoot) 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);

        // 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();

        // 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, KONEISHost.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, KUploadedFile.class);
        defineSealedHostClass(scope, KStoredFile.class);
        defineSealedHostClass(scope, KJob.class);
        defineSealedHostClass(scope, KSessionStore.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, JdSelectClause.class);
        defineSealedHostClass(scope, JdSelect.class, true /* map inheritance */);

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

        defineSealedHostClass(scope, KRefKeyDictionary.class);
        defineSealedHostClass(scope, KRefKeyDictionaryHierarchical.class, true /* map inheritance */);
        defineSealedHostClass(scope, KCheckingLookupObject.class);

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

        defineSealedHostClass(scope, KAuthenticationService.class);

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

        // Check JavaScript TimeZone
        checkJavaScriptTimeZoneIsGMT();

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

    initializeSharedEnvironmentTimeTaken = System.currentTimeMillis() - startTime;
}

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//  www  . j a  va2s.com
 */
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.l2jfree.gameserver.handler.admincommands.AdminTeleport.java

private void bookmark(L2Player activeChar, String Name) {
    File file = new File(Config.DATAPACK_ROOT, "data/html/admin/tele/bookmark.txt");
    LineNumberReader lnr = null;/*w  ww  .j a  va 2s.  c  o  m*/
    String bookmarks = "";
    String table = "";
    try {
        String line = null;
        lnr = new LineNumberReader(new FileReader(file));
        while ((line = lnr.readLine()) != null) {
            bookmarks += line + "\n";
            StringTokenizer st = new StringTokenizer(line, ";");
            String nm = st.nextToken();
            table += ("<a action=\"bypass -h admin_move_to " + st.nextToken() + " " + st.nextToken() + " "
                    + st.nextToken() + "\">" + nm + "</a>&nbsp;");
            table += ("<a action=\"bypass -h admin_delbookmark " + nm
                    + "\"><font color=\"FF0000\">[X]</font></a><br>");
        }
        if (Name == null) {
            NpcHtmlMessage adminReply = new NpcHtmlMessage(5);
            adminReply.setFile("data/html/admin/tele/bookmarks.htm");
            adminReply.replace("%bookmarks%", table);
            activeChar.sendPacket(adminReply);
        } else {
            FileWriter save = new FileWriter(file);
            bookmarks += Name + ";" + activeChar.getX() + ";" + activeChar.getY() + ";" + activeChar.getZ()
                    + "\n";
            save.write(bookmarks);
            save.close();
            bookmark(activeChar, null);
        }
    } catch (FileNotFoundException e) {
        activeChar.sendMessage("bookmark.txt not found");
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (lnr != null)
                lnr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.ice.client.widgets.moose.MOOSEFormEditor.java

/**
 * This private method is used to decide whether or not the given
 * ICEResource contains valid Postprocessor data to plot. Basically, for now
 * it naively checks that there is more than one line in the file, because
 * if there was 1 or less, then we would have no data or just the feature
 * line describing the data./*from ww  w . j  a v a2  s. c om*/
 * 
 * @param r
 * @return validData Whether or not there is valid data in the resource
 */
private boolean hasValidPostprocessorData(ICEResource r) {

    // Simply count the number of lines in the resource file
    try {
        LineNumberReader reader = new LineNumberReader(new FileReader(r.getPath().getPath()));
        int cnt = 0;
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {
        }

        cnt = reader.getLineNumber();
        reader.close();

        if (cnt <= 1) {
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error(getClass().getName() + " Exception!", e);
        return false;
    }
}

From source file:org.gcaldaemon.core.sendmail.SendMail.java

private final void sendPlainText(String email, String content, GmailEntry entry) throws Exception {

    // Mail properties
    HashSet to = new HashSet();
    HashSet cc = new HashSet();
    HashSet bcc = new HashSet();
    String subject = "Mail from " + username;
    QuickWriter body = new QuickWriter(content.length());
    if (email != null) {
        to.add(email);//from  w  w  w.java  2  s.  c  o  m
    }

    // Parse text
    LineNumberReader reader = new LineNumberReader(new StringReader(content));
    boolean readingBody = false;
    String line, upper;
    for (;;) {
        line = reader.readLine();
        if (line == null) {
            break;
        }
        if (readingBody) {
            body.write(line);
            body.write(CRLF);
            continue;
        }
        if (line.trim().length() == 0) {
            continue;
        }
        upper = line.toUpperCase();
        if (upper.startsWith("ENCODING")) {
            continue;
        }
        if (upper.startsWith("SUBJECT")) {
            subject = getParameter(line);
            continue;
        }
        if (upper.startsWith("TO")) {
            addParameters(to, line);
            continue;
        }
        if (upper.startsWith("CC")) {
            addParameters(cc, line);
            continue;
        }
        if (upper.startsWith("BCC")) {
            addParameters(bcc, line);
            continue;
        }
        readingBody = true;
        body.write(line);
        body.write(CRLF);
    }

    // Submit mail
    String toList = "";
    String ccList = "";
    String bccList = "";

    Iterator i = to.iterator();
    while (i.hasNext()) {
        toList += (String) i.next() + ",";
    }
    i = cc.iterator();
    while (i.hasNext()) {
        ccList += (String) i.next() + ",";
    }
    i = bcc.iterator();
    while (i.hasNext()) {
        bccList += (String) i.next() + ",";
    }
    if (toList.length() == 0) {
        toList = username;
    }

    String msg = body.toString();
    boolean isHTML = msg.indexOf("/>") != -1 || msg.indexOf("</") != -1;
    if (isHTML) {
        msg = cropBody(msg);
    }
    if (isHTML) {
        log.debug("Sending HTML mail...");
    } else {
        log.debug("Sending plain-text mail...");
    }
    entry.send(toList, ccList, bccList, subject, msg, isHTML);
    log.debug("Mail submission finished.");
}

From source file:org.springframework.jdbc.datasource.init.ScriptUtils.java

/**
 * Read a script from the provided resource, using the supplied comment prefix
 * and statement separator, and build a {@code String} containing the lines.
 * <p>Lines <em>beginning</em> with the comment prefix are excluded from the
 * results; however, line comments anywhere else &mdash; for example, within
 * a statement &mdash; will be included in the results.
 * @param resource the {@code EncodedResource} containing the script
 * to be processed/*from   w w  w. ja v a2 s.c o  m*/
 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
 * typically "--"
 * @param separator the statement separator in the SQL script &mdash; typically ";"
 * @return a {@code String} containing the script lines
 * @throws IOException in case of I/O errors
 */
private static String readScript(EncodedResource resource, @Nullable String commentPrefix,
        @Nullable String separator) throws IOException {

    LineNumberReader lnr = new LineNumberReader(resource.getReader());
    try {
        return readScript(lnr, commentPrefix, separator);
    } finally {
        lnr.close();
    }
}