简体   繁体   中英

Dynamically load jar file in groovy file, failed XML Parsing Error

I have a problem with that code:

import com.sun.net.httpserver.*
import groovy.sql.Sql
import java.util.concurrent.Executors

def jdbc_URL="jdbc:mysql: url to amazon ec2"  
def port= this.args ? this.args[0].toInteger() : 8888
def server = HttpServer.create(new InetSocketAddress(port),0)
def old_StdOut=System.out
def root_Dir = "C:/lab"

HttpContext kill = server.createContext("/kill", new Kill(server:server))
server.createContext("/", new info(rootDir:root_Dir))
server.createContext("/jar", new jar2xml(rootDir:root_Dir,oldStdOut:old_StdOut))

Object.metaClass.mysqlconnection= {->
  Sql.newInstance("${jdbc_URL}?"+
    "useUnicode=true&characterEncoding=UTF-8",
    'userairs', 'userairs', 'com.mysql.jdbc.Driver')
} 

kill.setAuthenticator(new BasicAuthenticator("kill") {
    public boolean checkCredentials(String user, String pwd) {
        println "user==$user pwd==$pwd"
        user=="1" && pwd=="1"
    }
});

server.setExecutor(null)
server.start()
println "\nHttpServer: localhost:$port started."

class info implements HttpHandler {
    def rootDir
    public void handle(HttpExchange exchange) {

        def path = exchange.getRequestURI().getPath()

        def out = new PrintWriter(exchange.getResponseBody())

        exchange.responseHeaders['Content-Type'] = 'text/html; charset=UTF-8'
        exchange.sendResponseHeaders(200, 0)
        println "info:==> ${path}"
        if(path =="/"){
            out.println """
            <H2>GROOVY HTTP-hello!</H2>
            """

            out.println "</ui><hr><h1>Jar files</h1><ui>"
            new File("${rootDir}/jar/").eachFileMatch(~/.*.jar/) {
                file->
                def fname=file.getName() [0..-5]
                out.println "<h3> <li><a href='/jar/${fname}' target='_blank'>/jar/${fname}.jar</a></h3>" }
            out.println "</ui><br>"
        }
        out.close()
        exchange.close()
    }
}


class jar2xml implements HttpHandler {
    def rootDir
    def oldStdOut
    public void handle(HttpExchange exchange) throws IOException {
        System.out = oldStdOut
        println "test-2"
        def query = exchange.getRequestURI().getQuery() ?: ""
        println "query=>> ${query}"
        def mpath = exchange.getRequestURI().getPath().tokenize("/")
        println "mpath=>> ${mpath}"
        exchange.responseHeaders['Content-Type'] = 'text/xml; charset=UTF-8'
        exchange.sendResponseHeaders(200, 0)
        def out = new PrintWriter(exchange.getResponseBody())
        println "test-1"
        def jarFile="${rootDir}/${mpath[0]}/${mpath[1]}.jar"
        println "jarFile=>> ${jarFile}"
        def bufStr = new ByteArrayOutputStream()
        println "run(new File('$jarFile') '${URLDecoder.decode(query)}')"

        System.out = new PrintStream(bufStr)
        // def shell = new GroovyShell()

        println "test"

        //getClass().classLoader.rootLoader.addURL(new File(jarFile).toURL())
        def urlLoader = new GroovyClassLoader()
        //Class.forName("Helloworld").newInstance().main("${URLDecoder.decode(query)}")

        urlLoader.addURL(new File(jarFile).toURL())
        Class.forName("Helloworld", true, urlLoader).newInstance()

        println "test2"

        def xml= bufStr.toString()
        System.out = oldStdOut

        println "test3"
        println "'${jarFile}' finished.\n"
        out.println xml
        out.close()
        exchange.close()
    }
}

java.awt.Desktop.getDesktop().browse(new URI("http://url:${port}/")) // localhost

Then I try:

groovy .\server.groovy

Then I open browser and click on link:

/jar/helloworld.jar

Result:

**XML Parsing Error: no element found

    Location: http://url:8888/jar/helloworld

Line Number 1, Column 1:**

jar file was compiled from:

    public class HelloWorld
    {
        public static void main (String args[]) 
        {
           System.out.println ("Hello World!");
        }
    }

There are two problems in your code.

  • In the line Class.forName("Helloworld", true Appears Helloworld (with lower w ) but the actual class name in the jar is HelloWorld (with upper W )

  • The response header says the content is xml but you are outputting plain text. This is the XML Parsing Error: no element found browser complaint.

If you fix these two errors the code works fine:

I'll replace Helloworld with HelloWorld in the class loading, and println test with <test> . Then:

public void handle(HttpExchange exchange) throws IOException {
    System.out = oldStdOut
    println "test-2"
    def query = exchange.getRequestURI().getQuery() ?: ""
    println "query=>> ${query}"
    def mpath = exchange.getRequestURI().getPath().tokenize("/")
    println "mpath=>> ${mpath}"
    exchange.responseHeaders['Content-Type'] = 'text/xml; charset=UTF-8'
    exchange.sendResponseHeaders(200, 0)
    def out = new PrintWriter(exchange.getResponseBody())
    println "test-1"
    def jarFile="${rootDir}/${mpath[0]}/${mpath[1]}.jar"
    println "jarFile=>> ${jarFile}"
    def bufStr = new ByteArrayOutputStream()
    println "run(new File('$jarFile') '${URLDecoder.decode(query)}')"

    System.out = new PrintStream(bufStr)
    // def shell = new GroovyShell()

    println "<test>"

    //getClass().classLoader.rootLoader.addURL(new File(jarFile).toURL())
    def urlLoader = new GroovyClassLoader()
    //Class.forName("Helloworld").newInstance().main("${URLDecoder.decode(query)}")

    urlLoader.addURL(new File(jarFile).toURL())
    try {
        def obj = Class.forName("HelloWorld", true, urlLoader).newInstance()
        println obj.class
    } catch (Exception e){
        println e
    }
    println "</test>"
    def xml= bufStr.toString()
    System.out = oldStdOut

    println "test3"
    println "'${jarFile}' finished.\n"
    out.println xml
    out.close()
    exchange.close()
}

Will output in the browser:

<test>
class HelloWorld
</test>

As expected.

I hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM