2014-12-05 43 views
1

我有代碼的一個問題:動態加載jar文件,失敗的XML解析錯誤

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

請下次嘗試隔離問題並提供最少的代碼以重現問題。幫助你會容易得多。 – fonkap 2014-12-06 12:01:16

回答

0

你的代碼有兩個問題。

  • 在線路Class.forName("Helloworld", true顯示Helloworld(具有較低w),但在該罐中的實際的類名稱是HelloWorld(具有上W

  • 響應頭指出內容是XML,但你正在輸出純文本。這是XML Parsing Error: no element found瀏覽器投訴。

如果解決這兩個錯誤的代碼工作正常:

我會<test>取代Helloworld與類裝載HelloWorldprintln 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> 

正如預期的那樣。

我希望這會有所幫助。