繁体   English   中英

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

[英]Dynamically load jar file in groovy file, failed XML Parsing Error

我对该代码有疑问:

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

您的代码中有两个问题。

  • Class.forName("Helloworld", true出现在Helloworld (带有较低的w ),但jar中的实际类名是HelloWorld (具有较高的W )。

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

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

我将在类加载中用HelloWorld替换Helloworld ,并用<test> println 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>

如预期的那样。

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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