在groovy文件中动态加载jar文件,XML分析错误失败

时间:2014-12-05 10:14:54

标签: java xml groovy jar

我的代码有问题:

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

然后我尝试:

groovy .\server.groovy

然后我打开浏览器并点击链接:

/jar/helloworld.jar

结果:

**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!");
        }
    }

1 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题。

  • 在第Class.forName("Helloworld", true行中显示Helloworld(较低w),但jar中的实际类名称为HelloWorld(上限为W })

  • 响应标头表示内容为xml,但您输出的是纯文本。这是XML Parsing Error: no element found浏览器投诉。

如果您修复了这两个错误,代码可以正常工作:

我会在课程加载中将Helloworld替换为HelloWorld,将println test替换为<test>。然后:

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()
}

将在浏览器中输出:

<test>
class HelloWorld
</test>

正如所料。

我希望它会有所帮助。