Search code examples
grailsgroovy

Displaying the contents of a file to a grails page?


I'm building a feature into my Grails project where the users can click on a button on the main form and using secure FTP it will read the contents of a remote log file. What I want to do is to display the contents of that log file to a Grails page. I'm not sure how to go about this and internet searches have been fruitless.

Here's the method to read the log, I just quickly threw this together. Not sure how to go about takig the contents of the file I'm reading and dumping to the grails page. Any help appreciated.

P.S. I'm sure there's an easier way to do the method below in Groovy.

 def getLogFile() {

    JSch jsch = new JSch();
    Session session = null;

    try {

        String username = "joesmith"
        String password = "mypassword"
        String hostname = "123.456.78.910"
        String x
        // connect to the server through secure ftp
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
        channel.connect();
        log.info("Session Connected, reading log file...");

        ChannelSftp sftpChannel = (ChannelSftp) channel;
        sftpChannel.cd("/usr/tmp")
        java.io.InputStream stream = sftpChannel.get("mylog.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(stream));

        while ((x = br.readLine()) != null) {
            log.info("line is " + x)
        }
    } catch (JSchException e) {
        e.printStackTrace();
    } catch (SftpException e) {
        e.printStackTrace();
    }

Solution

  • There are a few different ways to do this and some are safer than others. If your log files are too big you'll have issues displaying them. There are also encoding and security concerns you could think about.

    The simplest and quickest way would just be to dump the string to the page inside of a controller call using the render method:

        def stringBuilder = new StringBuilder()
        while ((x = br.readLine()) != null) {
            stringBuilder.append(x)
        }
        render(text: stringBuilder.toString(), contentType: "text/plain", encoding: "UTF-8")
    

    This probably wouldn't be my approach depending on whats inside the log files but, answers your question.