<commit_before>/**
 * CodeCanaan Client Tools 客戶端工具
 * 服務啟動程式（Launcher）
 */

import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
import javax.servlet.http.*
import javax.servlet.ServletConfig
import groovy.json.*

//import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
import java.awt.event.*

class FileBinaryCategory{    
    def static leftShift(File file, URL url) {
       url.withInputStream {is->
            file.withOutputStream {os->
                def bs = new BufferedOutputStream( os )
                bs << is                    
            }
        } 
    }    
}

class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        super.init(config)
        context = config.servletContext
    }
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
            requestHandler.call()
        }
    }
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')
        jetty.start()
    }
}

//移除瀏覽器下載的 .jnlp 暫存檔案
try {
    new File(System.properties['jnlpx.origFilenameArg'])?.delete()
}
catch(e) {
    //none
}

def osname = System.properties['os.name']
def isWindows = osname.toLowerCase().startsWith('windows')
def isMac = osname.toLowerCase().startsWith('mac')
def isLinux = osname.toLowerCase().startsWith('linux')

//download toolkits.zip
def toolkitsUrl = System.properties['core.toolkits.url'].toURL()

//create temp dir
def tempfile = File.createTempFile('temp', '.dump')
def tempdir = new File(tempfile.parentFile, tempfile.name.split('\\.')[0])
tempdir.mkdir()

def toolkits = new File(tempdir, 'toolkits.zip')
use (FileBinaryCategory) {
    toolkits << toolkitsUrl
}

//unzip toolkits
def ant = new AntBuilder();
ant.unzip(src: toolkits, dest: tempdir, overwrite: 'true') {
    //mapper(type: 'flatten')
}

def httpOrigin = System.properties['core.http.origin']?System.properties['core.http.origin']:'*'
def clientPort = System.properties['core.client.port']?new Integer(System.properties['core.client.port']):1337


//Swing UI Look And Feel
UIManager.lookAndFeel = UIManager.systemLookAndFeelClassName
UIManager.put('swing.boldMetal', Boolean.FALSE)

//彈出訊息
JOptionPane.showMessageDialog(null, "<html>客戶端工具已執行！<br/>Client Tools executed.")

//shutdown previous server
try {
    new URL("http://localhost:${clientPort}/?action=shutdown").text
}
catch (e) {
    //ignore
}

def versionCheck = {
    cmd ->
    try {
        def proc = cmd.execute()
        proc.waitForOrKill(10*1000)
        return [
            exitValue: proc.exitValue(),
            stdout: "${proc.in.text}\n${proc.err.text}".trim()
        ]
    }
    catch (e) {
        return [
            exitValue: -1,
            stdout: e.message
        ]
    }
}

def counter = 0

SimpleGroovyServlet.run(clientPort) { ->
    response.addHeader('Access-Control-Allow-Origin', httpOrigin)
    response.contentType = 'application/json'
    
    def json = new JsonBuilder()

    def action = params['action']

    if (!action) return

    if (action == 'shutdown') {
        System.exit(0)
        return
    }
    
    if (action == 'versions') {
        json.result {
            status 'success'<commit_msg>better version checker for Windows<commit_after>/**
 * CodeCanaan Client Tools 客戶端工具
 * 服務啟動程式（Launcher）
 */

import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
import javax.servlet.http.*
import javax.servlet.ServletConfig
import groovy.json.*

//import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
import java.awt.event.*

class FileBinaryCategory{    
    def static leftShift(File file, URL url) {
       url.withInputStream {is->
            file.withOutputStream {os->
                def bs = new BufferedOutputStream( os )
                bs << is                    
            }
        } 
    }    
}

class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        super.init(config)
        context = config.servletContext
    }
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
            requestHandler.call()
        }
    }
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')
        jetty.start()
    }
}

//移除瀏覽器下載的 .jnlp 暫存檔案
try {
    new File(System.properties['jnlpx.origFilenameArg'])?.delete()
}
catch(e) {
    //none
}

def osname = System.properties['os.name']
def isWindows = osname.toLowerCase().startsWith('windows')
def isMac = osname.toLowerCase().startsWith('mac')
def isLinux = osname.toLowerCase().startsWith('linux')

//download toolkits.zip
def toolkitsUrl = System.properties['core.toolkits.url'].toURL()

//create temp dir
def tempfile = File.createTempFile('temp', '.dump')
def tempdir = new File(tempfile.parentFile, tempfile.name.split('\\.')[0])
tempdir.mkdir()

def toolkits = new File(tempdir, 'toolkits.zip')
use (FileBinaryCategory) {
    toolkits << toolkitsUrl
}

//unzip toolkits
def ant = new AntBuilder();
ant.unzip(src: toolkits, dest: tempdir, overwrite: 'true') {
    //mapper(type: 'flatten')
}

def httpOrigin = System.properties['core.http.origin']?System.properties['core.http.origin']:'*'
def clientPort = System.properties['core.client.port']?new Integer(System.properties['core.client.port']):1337


//Swing UI Look And Feel
UIManager.lookAndFeel = UIManager.systemLookAndFeelClassName
UIManager.put('swing.boldMetal', Boolean.FALSE)

//彈出訊息
JOptionPane.showMessageDialog(null, "<html>客戶端工具已執行！<br/>Client Tools executed.")

//shutdown previous server
try {
    new URL("http://localhost:${clientPort}/?action=shutdown").text
}
catch (e) {
    //ignore
}

def versionCheck = {
    cmd ->
    try {
    
        if (isWindows) {
            cmd = "cmd /C ${cmd}"
        }
        
        def proc = cmd.execute()
        proc.waitForOrKill(10*1000)
        
        def output = "";

        if (isWindows) {
            output = "${proc.in.getText('MS950')}\n${proc.err.getText('MS950')}".trim()
        }
        else {
            output = "${proc.in.text}\n${proc.err.text}".trim()
        }
        
        return [
            exitValue: proc.exitValue(),
            stdout: output
        ]
    }
    catch (e) {
        return [
            exitValue: -1,
            stdout: e.message
        ]
    }
}

def counter = 0

SimpleGroovyServlet.run(clientPort) { ->
    response.addHeader('Access-Control-Allow-Origin', httpOrigin)
    response.contentType = 'application/json'
    
    def json = new JsonBuilder()

    def action = params['action']

    if (!action) return

    if (action == 'shutdown') {
        System.exit(0)
        return
    }
    
    if (action == 'versions') {
        json.result {
            status 'success'
{'fraction_non_alphanumeric': 0.1303827751196172, 'fraction_numerical': 0.004518872939925572, 'mean_word_length': 2.7493771798704536, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2742023', 'n_tokens_mistral': 2407, 'n_tokens_neox': 2390, 'n_words': 488}