หน้าเว็บ

วันศุกร์ที่ 17 พฤษภาคม พ.ศ. 2556

obfuscate javascript by google closure : java

maven dependencies
        <!-- javascript compiler @ https://code.google.com/p/closure-compiler/-->
        <dependency>
            <groupId>com.google.javascript</groupId>
            <artifactId>closure-compiler</artifactId>
            <version>v20130411</version>
        </dependency>
        <!-- javascript compiler -->

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>
java code
JavascriptCompiler.java
package com.blogspot.na5cent.compiler;

import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author redcrow
 */
public class JavascriptCompiler {

    private static final Logger LOG = LoggerFactory.getLogger(JavascriptCompiler.class);

    public void compile(File javascriptFile) throws IOException {
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try{
            inputStream = new FileInputStream(javascriptFile);
            outputStream = new FileOutputStream(javascriptFile));

            String code = IOUtils.toString(inputStream);
            IOUtils.write(compile(code), outputStream);
        }finally{
             if(outputStream != null){
                 outputStream.close();  
             }

             if(inputStream != null){
                 inputStream.close();  
             }
        }
    }

    public String compile(String javascriptCode) {
        com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler();
        CompilerOptions options = new CompilerOptions();
        CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
        JSSourceFile extern = JSSourceFile.fromCode("externs.js", "");
        JSSourceFile input = JSSourceFile.fromCode("input.js", javascriptCode);
        compiler.compile(extern, input, options);
        return compiler.toSource();
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น