home | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Groovy example source code file (SimpleWebServer.groovy)

This example Groovy source code file (SimpleWebServer.groovy) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Groovy tags/keywords

content-type, content-type, file, file, io, ok, ok

The Groovy SimpleWebServer.groovy source code

/**
 * Simple web server
 * @author <a href="mailto:jeremy.rayner@gmail.com">Jeremy Rayner
 * 
 * invoke using
 *    groovy -l 80 SimpleWebServer.groovy
 * 
 *       (where 80 is the port to listen for requests upon)
 */
import java.io.File

if (init) { 
    headers = [:] 
    binaryTypes = ["gif","jpg","png"]          
    mimeTypes = [
        "css" : "text/css",         
        "gif" : "image/gif",
        "htm" : "text/html",         
        "html": "text/html",         
        "jpg" : "image/jpeg",         
        "png" : "image/png"
    ]                                 
}

// parse the request
if (line.toLowerCase().startsWith("get")) {
    content = line.tokenize()[1]
} else {
    h = line.tokenize(":")
    headers[h[0]] = h[1]
}

// all done, now process request
if (line.size() == 0) {
    processRequest()
    return "success"
}

// ------------------------

def processRequest() {
    if (content.indexOf("..") < 0) { //simplistic security
        // simple file browser rooted from current dir
        f = new File("." + content)
        if (f.isDirectory()) {
            printDirectoryListing(f)
        } else {
            extension = content.substring(content.lastIndexOf(".") + 1)
            printHeaders(mimeTypes.get(extension,"text/plain"))          
                      
            if (binaryTypes.contains(extension)) {
                socket.outputStream.write(f.readBytes())
            } else {
                println(f.text)
            }
        }
    }
}

def printDirectoryListing(f) {
    printHeaders("text/html")          
    println "<html>"
    for (i in f.list().toList().sort()) {
        if ("/" == content) { content = "" } // special case for root document
        println "<a href='${content}/${i}'>${i}
" } println "</body>" } def printHeaders(mimeType) { println "HTTP/1.0 200 OK" println "Content-Type: ${mimeType}" println "" }

Other Groovy examples (source code examples)

Here is a short list of links related to this Groovy SimpleWebServer.groovy source code file:

new blog posts

 

Copyright 1998-2016 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.