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.agnitas.util.AgnUtils.java

public static int getLineCountOfFile(File file) throws IOException {
    LineNumberReader lineNumberReader = null;
    try {/*ww w  .j a  va 2 s .  c  om*/
        lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
        while (lineNumberReader.readLine() != null) {
        }

        return lineNumberReader.getLineNumber();
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }
}

From source file:fitnesserefactor.FitnesseRefactor.java

public int CountLines(File filename) throws FileNotFoundException, IOException {
    LineNumberReader reader = new LineNumberReader(new FileReader(filename));
    int cnt = 0;//www.  j  a va 2s.c om
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
    }
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

/** {@inheritDoc} */
public void copyResources(SiteRenderingContext siteRenderingContext, File outputDirectory) throws IOException {
    if (siteRenderingContext.getSkin() != null) {
        ZipFile file = getZipFile(siteRenderingContext.getSkin().getFile());

        try {/*from  ww  w  . ja  va  2  s  .  co m*/
            for (Enumeration<? extends ZipEntry> e = file.entries(); e.hasMoreElements();) {
                ZipEntry entry = e.nextElement();

                if (!entry.getName().startsWith("META-INF/")) {
                    File destFile = new File(outputDirectory, entry.getName());
                    if (!entry.isDirectory()) {
                        if (destFile.exists()) {
                            // don't override existing content: avoids extra rewrite with same content or extra site
                            // resource
                            continue;
                        }

                        destFile.getParentFile().mkdirs();

                        copyFileFromZip(file, entry, destFile);
                    } else {
                        destFile.mkdirs();
                    }
                }
            }
        } finally {
            closeZipFile(file);
        }
    }

    if (siteRenderingContext.isUsingDefaultTemplate()) {
        InputStream resourceList = getClass().getClassLoader()
                .getResourceAsStream(RESOURCE_DIR + "/resources.txt");

        if (resourceList != null) {
            Reader r = null;
            LineNumberReader reader = null;
            try {
                r = ReaderFactory.newReader(resourceList, ReaderFactory.UTF_8);
                reader = new LineNumberReader(r);

                String line;

                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("#") || line.trim().length() == 0) {
                        continue;
                    }

                    InputStream is = getClass().getClassLoader().getResourceAsStream(RESOURCE_DIR + "/" + line);

                    if (is == null) {
                        throw new IOException("The resource " + line + " doesn't exist.");
                    }

                    File outputFile = new File(outputDirectory, line);

                    if (outputFile.exists()) {
                        // don't override existing content: avoids extra rewrite with same content or extra site
                        // resource
                        continue;
                    }

                    if (!outputFile.getParentFile().exists()) {
                        outputFile.getParentFile().mkdirs();
                    }

                    OutputStream os = null;
                    try {
                        // for the images
                        os = new FileOutputStream(outputFile);
                        IOUtil.copy(is, os);
                    } finally {
                        IOUtil.close(os);
                    }

                    IOUtil.close(is);
                }
            } finally {
                IOUtil.close(reader);
                IOUtil.close(r);
            }
        }
    }

    // Copy extra site resources
    for (File siteDirectory : siteRenderingContext.getSiteDirectories()) {
        File resourcesDirectory = new File(siteDirectory, "resources");

        if (resourcesDirectory != null && resourcesDirectory.exists()) {
            copyDirectory(resourcesDirectory, outputDirectory);
        }
    }

    // Check for the existence of /css/site.css
    File siteCssFile = new File(outputDirectory, "/css/site.css");
    if (!siteCssFile.exists()) {
        // Create the subdirectory css if it doesn't exist, DOXIA-151
        File cssDirectory = new File(outputDirectory, "/css/");
        boolean created = cssDirectory.mkdirs();
        if (created && getLogger().isDebugEnabled()) {
            getLogger().debug(
                    "The directory '" + cssDirectory.getAbsolutePath() + "' did not exist. It was created.");
        }

        // If the file is not there - create an empty file, DOXIA-86
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(
                    "The file '" + siteCssFile.getAbsolutePath() + "' does not exist. Creating an empty file.");
        }
        Writer writer = null;
        try {
            writer = WriterFactory.newWriter(siteCssFile, siteRenderingContext.getOutputEncoding());
            //DOXIA-290...the file should not be 0 bytes.
            writer.write("/* You can override this file with your own styles */");
        } finally {
            IOUtil.close(writer);
        }
    }
}

From source file:org.opencms.util.CmsRfsFileViewer.java

/**
 * Return the view portion of lines of text from the underlying file or an 
 * empty String if <code>{@link #isEnabled()}</code> returns <code>false</code>.<p>
 * //w  ww  .  j a v a  2 s  .co  m
 * @return the view portion of lines of text from the underlying file or an 
 *         empty String if <code>{@link #isEnabled()}</code> returns <code>false</code>
 * @throws CmsRfsException if something goes wrong
 */
public String readFilePortion() throws CmsRfsException {

    if (m_enabled) {
        // if we want to view the log file we have to set the internal m_windowPos to the last window 
        // to view the end: 
        int lines = -1;
        int startLine;
        if (m_isLogfile) {
            lines = scrollToFileEnd();
            // for logfile mode we show the last window of window size: 
            // it could be possible that only 4 lines are in the last window 
            // (e.g.: 123 lines with windowsize 10 -> last window has 3 lines) 
            // so we ignore the window semantics and show the n last lines: 
            startLine = lines - m_windowSize;
        } else {
            m_windowPos = 0;
            startLine = m_windowPos * m_windowSize;
        }
        LineNumberReader reader = null;
        try {
            // don't make the buffer too big, just big enough for windowSize lines (estimation: avg. of 200 characters per line) 
            // to save reading too much (this optimizes to read the first windows, much later windows will be slower...)
            reader = new LineNumberReader(
                    new BufferedReader(new InputStreamReader(new FileInputStream(m_filePath), m_fileEncoding)),
                    m_windowSize * 200);
            int currentLine = 0;
            // skip the lines to the current window:
            while (startLine > currentLine) {
                reader.readLine();
                currentLine++;
            }
            StringBuffer result = new StringBuffer();
            String read = reader.readLine();

            // logfile treatment is different
            // we invert the lines: latest come first
            if (m_isLogfile) {
                // stack is java hall of shame member... but standard
                Stack inverter = new Stack();
                for (int i = m_windowSize; (i > 0) && (read != null); i--) {
                    inverter.push(read);
                    read = reader.readLine();
                }
                // pop-off:
                while (!inverter.isEmpty()) {
                    result.append(inverter.pop());
                    result.append('\n');
                }
            } else {
                for (int i = m_windowSize; (i > 0) && (read != null); i--) {
                    result.append(read);
                    result.append('\n');
                    read = reader.readLine();
                }
            }
            return CmsEncoder.escapeXml(result.toString());
        } catch (IOException ioex) {
            CmsRfsException ex = new CmsRfsException(
                    Messages.get().container(Messages.ERR_FILE_ARG_ACCESS_1, m_filePath), ioex);
            throw ex;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }
        }
    } else {
        return Messages.get().getBundle().key(Messages.GUI_FILE_VIEW_NO_PREVIEW_0);
    }
}

From source file:net.pms.dlna.RootFolder.java

private void addWebFolder(File webConf) {
    if (webConf.exists()) {
        try {//from  w w w  .j  a  v  a  2s. co  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:org.opencms.applet.upload.FileUploadApplet.java

private List parseDuplicateFiles(String responseBodyAsString) {

    List result = new ArrayList();
    LineNumberReader reader = new LineNumberReader(
            new InputStreamReader(new ByteArrayInputStream(responseBodyAsString.getBytes())));
    try {/*  w w w .j  ava2  s  .  com*/
        String trim;
        for (String read = reader.readLine(); read != null; read = reader.readLine()) {
            trim = read.trim();
            if (!(trim.equals("") || trim.equals("\n"))) {
                // empty strings could happen if the serverside jsp is edited and has new unwanted linebreaks
                result.add(read);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.TestDockerContainerExecutorWithMocks.java

@Test
//Test that a container launch correctly wrote the session script with the
//commands we expected
public void testContainerLaunch() throws IOException {
    String appSubmitter = "nobody";
    String appSubmitterFolder = "nobodysFolder";
    String appId = "APP_ID";
    String containerId = "CONTAINER_ID";
    String testImage = "\"sequenceiq/hadoop-docker:2.4.1\"";

    Container container = mock(Container.class, RETURNS_DEEP_STUBS);
    ContainerId cId = mock(ContainerId.class, RETURNS_DEEP_STUBS);
    ContainerLaunchContext context = mock(ContainerLaunchContext.class);
    HashMap<String, String> env = new HashMap<String, String>();

    when(container.getContainerId()).thenReturn(cId);
    when(container.getLaunchContext()).thenReturn(context);
    when(cId.getApplicationAttemptId().getApplicationId().toString()).thenReturn(appId);
    when(cId.toString()).thenReturn(containerId);

    when(context.getEnvironment()).thenReturn(env);
    env.put(YarnConfiguration.NM_DOCKER_CONTAINER_EXECUTOR_IMAGE_NAME, testImage);
    Path scriptPath = new Path("file:///bin/echo");
    Path tokensPath = new Path("file:///dev/null");

    Path pidFile = new Path(workDir, "pid");

    dockerContainerExecutor.activateContainer(cId, pidFile);
    int ret = dockerContainerExecutor.launchContainer(new ContainerStartContext.Builder()
            .setContainer(container).setNmPrivateContainerScriptPath(scriptPath)
            .setNmPrivateTokensPath(tokensPath).setUser(appSubmitter).setAppId(appId)
            .setContainerWorkDir(workDir).setLocalDirs(dirsHandler.getLocalDirs())
            .setLogDirs(dirsHandler.getLogDirs()).setUserFolder(appSubmitterFolder).build());
    assertEquals(0, ret);//  www .  j  a v  a 2  s .  com
    //get the script
    Path sessionScriptPath = new Path(workDir,
            Shell.appendScriptExtension(DockerContainerExecutor.DOCKER_CONTAINER_EXECUTOR_SESSION_SCRIPT));
    LineNumberReader lnr = new LineNumberReader(new FileReader(sessionScriptPath.toString()));
    boolean cmdFound = false;
    List<String> localDirs = dirsToMount(dirsHandler.getLocalDirs());
    List<String> logDirs = dirsToMount(dirsHandler.getLogDirs());
    List<String> workDirMount = dirsToMount(Collections.singletonList(workDir.toUri().getPath()));
    List<String> expectedCommands = new ArrayList<String>(
            Arrays.asList(DOCKER_LAUNCH_COMMAND, "run", "--rm", "--net=host", "--name", containerId));
    expectedCommands.addAll(localDirs);
    expectedCommands.addAll(logDirs);
    expectedCommands.addAll(workDirMount);
    String shellScript = workDir + "/launch_container.sh";

    expectedCommands
            .addAll(Arrays.asList(testImage.replaceAll("['\"]", ""), "bash", "\"" + shellScript + "\""));

    String expectedPidString = "echo `/bin/true inspect --format {{.State.Pid}} " + containerId + "` > "
            + pidFile.toString() + ".tmp";
    boolean pidSetterFound = false;
    while (lnr.ready()) {
        String line = lnr.readLine();
        LOG.debug("line: " + line);
        if (line.startsWith(DOCKER_LAUNCH_COMMAND)) {
            List<String> command = new ArrayList<String>();
            for (String s : line.split("\\s+")) {
                command.add(s.trim());
            }

            assertEquals(expectedCommands, command);
            cmdFound = true;
        } else if (line.startsWith("echo")) {
            assertEquals(expectedPidString, line);
            pidSetterFound = true;
        }

    }
    assertTrue(cmdFound);
    assertTrue(pidSetterFound);
}

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

/**
 * read all lines of the file/*  www .  ja  v a 2s .c  o m*/
 * @param aForm
 * @param req
 * @return
 * @throws IOException
 */
public int getLinesOKFromFile(HttpServletRequest req) throws IOException {
    String csvString = new String(this.getCsvFile().getFileData(), this.getStatus().getCharset());
    LineNumberReader aReader = new LineNumberReader(new StringReader(csvString));
    String myline = "";
    int linesOK = 0;
    this.getUniqueValues().clear();
    aReader.readLine(); // skip header
    while ((myline = aReader.readLine()) != null) {
        if (myline.trim().length() > 0) {
            if (this.parseLine(myline,
                    (Locale) req.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY)) != null) {
                linesOK++;
            }
        }
    }
    aReader.close();
    return linesOK;
}

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

/**
 * Tries to read csv file Reads database column structure reads first line
 * splits line into tokens/* w ww  .j  a  v  a 2s.c om*/
 */
protected ActionErrors parseFirstline(HttpServletRequest req) {
    ApplicationContext aContext = this.getWebApplicationContext();
    DataSource ds = (DataSource) aContext.getBean("dataSource");
    String csvString = new String("");
    String firstline = null;
    ActionErrors errors = new ActionErrors();
    int colNum = 0;

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

    if (csvString.length() == 0) {
        errors.add("global", new ActionMessage("error.import.no_file"));
    }

    // read out DB column structure:
    this.readDBColumns(this.getCompanyID(req), ds);
    this.csvAllColumns = new ArrayList();
    LineNumberReader aReader = new LineNumberReader(new StringReader(csvString));

    try {
        // read first line:
        if ((firstline = aReader.readLine()) != null) {
            aReader.close(); // 

            // split line into tokens:
            CsvTokenizer st = new CsvTokenizer(firstline, status.getSeparator(), status.getDelimiter());
            String curr = "";
            CsvColInfo aCol = null;
            List<String> tempList = new ArrayList<String>();
            while ((curr = st.nextToken()) != null) {

                // curr = (String)st.nextElement();
                curr = curr.trim();
                curr = curr.toLowerCase();
                aCol = new CsvColInfo();
                aCol.setName(curr);
                aCol.setActive(false);
                aCol.setType(CsvColInfo.TYPE_UNKNOWN);

                // add column to csvAllColumns:
                if (!tempList.contains(aCol.getName())) {
                    tempList.add(aCol.getName());
                } else {
                    errors.add("global", new ActionMessage("error.import.column"));
                }
                csvAllColumns.add(aCol);
                colNum++;
                this.csvMaxUsedColumn = colNum;
            }
        }

    } catch (Exception e) {
        AgnUtils.logger().error("parseFirstline: " + e);
    }

    return errors;
}

From source file:massbank.BatchSearchWorker.java

/**
 * T}t@C???iHTML`?j/* w ww .j av a 2  s. c o m*/
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createSummary(File resultFile, File htmlFile) {
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        //(1) t@C?
        String line;
        int cnt = 0;
        ArrayList<String> nameList = new ArrayList<String>();
        ArrayList<String> top1LineList = new ArrayList<String>();
        TreeSet<String> top1IdList = new TreeSet<String>();
        in = new LineNumberReader(new FileReader(resultFile));
        while ((line = in.readLine()) != null) {
            line = line.trim();
            if (line.equals("")) {
                cnt = 0;
            } else {
                cnt++;
                if (cnt == 1) {
                    nameList.add(line);
                } else if (cnt == 2) {
                    if (line.equals("-1")) {
                        top1LineList.add("Invalid");
                    }
                    if (line.equals("0")) {
                        top1LineList.add("0");
                    }
                } else if (cnt == 4) {
                    String[] vals = line.split("\t");
                    String id = vals[0];
                    top1IdList.add(id);
                    top1LineList.add(line);
                }
            }
        }

        //? http://www.massbank.jp/ T?[o??KEGG???s
        HashMap<String, ArrayList> massbank2mapList = new HashMap<String, ArrayList>(); //(2)p
        HashMap<String, String> massbank2keggList = new HashMap<String, String>(); //(2)p
        HashMap<String, ArrayList> map2keggList = new HashMap<String, ArrayList>(); //(3)p
        ArrayList<String> mapNameList = new ArrayList<String>(); //(4)p
        boolean isKeggReturn = false;
        //         if (serverUrl.indexOf("www.massbank.jp") == -1) {
        //            isKeggReturn = false;
        //         }
        if (isKeggReturn) {

            //(2) KEGG ID, Map IDDB
            String where = "where MASSBANK in(";
            Iterator it = top1IdList.iterator();
            while (it.hasNext()) {
                String id = (String) it.next();
                where += "'" + id + "',";
            }
            where = where.substring(0, where.length() - 1);
            where += ")";
            String sql = "select MASSBANK, t1.KEGG, MAP from " + "(SELECT MASSBANK,KEGG FROM OTHER_DB_IDS "
                    + where + ") t1, PATHWAY_CPDS t2" + " where t1.KEGG=t2.KEGG order by MAP,MASSBANK";

            ArrayList<String> mapList = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String connectUrl = "jdbc:mysql://localhost/MassBank_General";
                Connection con = DriverManager.getConnection(connectUrl, "bird", "bird2006");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                String prevId = "";
                while (rs.next()) {
                    String id = rs.getString(1);
                    String kegg = rs.getString(2);
                    String map = rs.getString(3);
                    if (!id.equals(prevId)) {
                        if (!prevId.equals("")) {
                            massbank2mapList.put(prevId, mapList);
                        }
                        mapList = new ArrayList<String>();
                        massbank2keggList.put(id, kegg);
                    }
                    mapList.add(map);
                    prevId = id;
                }
                massbank2mapList.put(prevId, mapList);

                rs.close();
                stmt.close();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (mapList != null) {

                //(3) Pathway Map?FtXg??
                it = massbank2mapList.keySet().iterator();
                while (it.hasNext()) {
                    String id = (String) it.next();
                    String kegg = (String) massbank2keggList.get(id);

                    ArrayList<String> list1 = massbank2mapList.get(id);
                    for (int i = 0; i < list1.size(); i++) {
                        String map = list1.get(i);
                        ArrayList<String> list2 = null;
                        if (map2keggList.containsKey(map)) {
                            list2 = map2keggList.get(map);
                            list2.add(kegg);
                        } else {
                            list2 = new ArrayList<String>();
                            list2.add(kegg);
                            map2keggList.put(map, list2);
                        }
                    }
                }

                //(4) SOAPPathway Map?Ft?\bh?s
                it = map2keggList.keySet().iterator();
                List<Callable<HashMap<String, String>>> tasks = new ArrayList();
                while (it.hasNext()) {
                    String map = (String) it.next();
                    mapNameList.add(map);
                    ArrayList<String> list = map2keggList.get(map);
                    String[] cpds = list.toArray(new String[] {});
                    Callable<HashMap<String, String>> task = new ColorPathway(map, cpds);
                    tasks.add(task);
                }
                Collections.sort(mapNameList);

                // Xbhv?[10
                ExecutorService exsv = Executors.newFixedThreadPool(10);
                List<Future<HashMap<String, String>>> results = exsv.invokeAll(tasks);

                // Pathway mapi[??
                String saveRootPath = MassBankEnv.get(MassBankEnv.KEY_TOMCAT_APPTEMP_PATH) + "pathway";
                File rootDir = new File(saveRootPath);
                if (!rootDir.exists()) {
                    rootDir.mkdir();
                }
                //               String savePath = saveRootPath + File.separator + this.jobId;
                //               File newDir = new File(savePath);
                //               if ( !newDir.exists() ) {
                //                  newDir.mkdir();
                //               }

                //(6) Pathway mapURL
                for (Future<HashMap<String, String>> future : results) {
                    HashMap<String, String> res = future.get();
                    it = res.keySet().iterator();
                    String map = (String) it.next();
                    String mapUrl = res.get(map);
                    String filePath = saveRootPath + File.separator + this.jobId + "_" + map + ".png";
                    FileUtil.downloadFile(mapUrl, filePath);
                }
            }
        }

        //(7) ?o
        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();
        }
        String title = "Summary of Batch Service Results";
        out.println("<html>");
        out.println("<head>");
        out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" + title + "</h1>");
        out.println("<hr>");
        out.println("<h3>Request Date : " + this.time + "</h3>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("MS Type : " + this.ms + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br>");
        out.println("<hr>");
        out.println("<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">");
        String cols = String.valueOf(mapNameList.size());
        out.println("<tr>");
        out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">No.</th>");
        out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">Query&nbsp;Name</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Score</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Hit</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">MassBank&nbsp;ID</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Record&nbsp;Title</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Formula</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Exact Mass</th>");
        if (isKeggReturn) {
            out.println("<th bgcolor=\"LightYellow\" rowspan=\"2\">KEGG&nbsp;ID</th>");
            out.println(
                    "<th bgcolor=\"LightYellow\" colspan=\"" + cols + "\">Colored&nbsp;Pathway&nbsp;Maps</th>");
        }
        out.println("</tr>");
        out.print("<tr bgcolor=\"moccasin\">");
        for (int i = 0; i < mapNameList.size(); i++) {
            out.print("<th>MAP" + String.valueOf(i + 1) + "</th>");
        }
        out.println("</tr>");

        for (int i = 0; i < nameList.size(); i++) {
            out.println("<tr>");
            String no = String.format("%5d", i + 1);
            no = no.replace(" ", "&nbsp;");
            out.println("<td>" + no + "</td>");
            // Query Name
            String queryName = nameList.get(i);
            out.println("<td nowrap>" + queryName + "</td>");

            line = top1LineList.get(i);
            if (line.equals("0")) {
                if (isKeggReturn) {
                    cols = String.valueOf(mapNameList.size() + 5);
                } else {
                    cols = String.valueOf(6);
                }
                out.println("<td colspan=\"" + cols + "\">No Hit Record</td>");
            } else if (line.equals("Invalid")) {
                if (isKeggReturn) {
                    cols = String.valueOf(mapNameList.size() + 5);
                } else {
                    cols = String.valueOf(4);
                }
                out.println("<td colspan=\"" + cols + "\">Invalid Query</td>");
            } else {
                String[] data = formatLine(line);
                String id = data[0];
                String recTitle = data[1];
                String formula = data[2];
                String emass = data[3];
                String score = data[4];
                String hit = data[5];

                boolean isHiScore = false;
                if (Integer.parseInt(hit) >= 3 && Double.parseDouble(score) >= 0.8) {
                    isHiScore = true;
                }

                // Score
                if (isHiScore) {
                    out.println("<td><b>" + score + "</b></td>");
                } else {
                    out.println("<td>" + score + "</td>");
                }

                // hit peak
                if (isHiScore) {
                    out.println("<td align=\"right\"><b>" + hit + "</b></td>");
                } else {
                    out.println("<td align=\"right\">" + hit + "</td>");
                }

                // MassBank ID & Link
                out.println("<td><a href=\"" + serverUrl + "jsp/FwdRecord.jsp?id=" + id
                        + "\" target=\"_blank\">" + id + "</td>");
                // Record Title
                out.println("<td>" + recTitle + "</td>");

                // Formula
                out.println("<td nowrap>" + formula + "</td>");

                // Exact Mass
                out.println("<td nowrap>" + emass + "</td>");

                // KEGG ID & Link
                if (isKeggReturn) {
                    String keggLink = "&nbsp;&nbsp;-";
                    if (massbank2keggList.containsKey(id)) {
                        String keggUrl = "http://www.genome.jp/dbget-bin/www_bget?";
                        String kegg = massbank2keggList.get(id);
                        switch (kegg.charAt(0)) {
                        case 'C':
                            keggUrl += "cpd:" + kegg;
                            break;
                        case 'D':
                            keggUrl += "dr:" + kegg;
                            break;
                        case 'G':
                            keggUrl += "gl:" + kegg;
                            break;
                        }
                        keggLink = "<a href=\"" + keggUrl + "\" target=\"_blank\">" + kegg + "</a>";
                    }
                    out.println("<td>" + keggLink + "</td>");
                    // Pathway Map Link
                    if (massbank2mapList.containsKey(id)) {
                        ArrayList<String> list = massbank2mapList.get(id);
                        for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) {
                            boolean isFound = false;
                            String map = "";
                            for (int l2 = list.size() - 1; l2 >= 0; l2--) {
                                map = list.get(l2);
                                if (map.equals(mapNameList.get(l1))) {
                                    isFound = true;
                                    break;
                                }
                            }
                            if (isFound) {
                                ArrayList<String> list2 = map2keggList.get(map);
                                String mapUrl = serverUrl + "temp/pathway/" + this.jobId + "_" + map + ".png";
                                out.println("<td nowrap><a href=\"" + mapUrl + "\" target=\"_blank\">map:" + map
                                        + "(" + list2.size() + ")</a></td>");
                            } else {
                                out.println("<td>&nbsp;&nbsp;-</td>");
                            }
                        }
                    } else {
                        for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) {
                            out.println("<td>&nbsp;&nbsp;-</td>");
                        }
                    }
                }
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}