[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n\n*.swp\n\n.idea\n*.iml\n\nnode_modules\nout\ntutorials\n.DS_Store\n\n*.xcuserstate\nproject.xcworkspace/\n\n.Trashes\n\n*~.nib\nDerivedData/\nbuild/\n\n/vendor/\n\n*.pbxuser\n\n# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html\n\n*.mode1v3\n\n# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html\n\n*.mode2v3\n\n# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file\n\n*.perspectivev3\n\n#    NB: also, whitelist the default ones, some projects need to use these\n!default.pbxuser\n!default.mode1v3\n!default.mode2v3\n!default.perspectivev3\n\n\n####\n# Xcode 4 - semi-personal settings\n#\n# Apple Shared data that Apple put in the wrong folder\n# c.f. http://stackoverflow.com/a/19260712/153422\n#     FROM ANSWER: Apple says \"don't ignore it\"\n#     FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode\n# Up to you, but ... current advice: ignore it.\n*.xccheckout\n\n#\n#\n# OPTION 1: ---------------------------------\n#     throw away ALL personal settings (including custom schemes!\n#     - unless they are \"shared\")\n# As per build/ and DerivedData/, this ought to have a trailing slash\n#\n# NB: this is exclusive with OPTION 2 below\nxcuserdata/\n\n# OPTION 2: ---------------------------------\n#     get rid of ALL personal settings, but KEEP SOME OF THEM\n#     - NB: you must manually uncomment the bits you want to keep\n#\n# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,\n#    or manually install git over the top of the OS X version\n# NB: this is exclusive with OPTION 1 above\n#\n#xcuserdata/**/*\n\n#     (requires option 2 above): Personal Schemes\n#\n#!xcuserdata/**/xcschemes/*\n\n####\n# XCode 4 workspaces - more detailed\n#\n# Workspaces are important! They are a core feature of Xcode - don't exclude them :)\n#\n# Workspace layout is quite spammy. For reference:\n#\n# /(root)/\n#   /(project-name).xcodeproj/\n#     project.pbxproj\n#     /project.xcworkspace/\n#       contents.xcworkspacedata\n#       /xcuserdata/\n#         /(your name)/xcuserdatad/\n#           UserInterfaceState.xcuserstate\n#     /xcshareddata/\n#       /xcschemes/\n#         (shared scheme name).xcscheme\n#     /xcuserdata/\n#       /(your name)/xcuserdatad/\n#         (private scheme).xcscheme\n#         xcschememanagement.plist\n#\n#\n\n####\n# Xcode 4 - Deprecated classes\n#\n# Allegedly, if you manually \"deprecate\" your classes, they get moved here.\n#\n# We're using source-control, so this is a \"feature\" that we do not want!\n\n*.moved-aside\n\n#\n# COCOAPODS:\n#\n# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock\n# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control\n\n!Podfile.lock\n\n# Android\n#\n# Built application files\n*.apk\n*.ap_\n\n# Files for the Dalvik VM\n*.dex\n\n# Java class files\n*.class\n\n# Generated files\nbin/\ngen/\n\n# Gradle files\n.gradle/\nbuild/\n\n# Local configuration file (sdk path, etc)\nlocal.properties\n\n# Proguard folder generated by Eclipse\nproguard/\n\n# Log Files\n*.log\n\n# Android Studio Navigation editor temp files\n.navigation/\n\n# Android Studio captures folder\ncaptures/\n\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: go\n\ngo:\n  - 1.6\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2016 Sridhar Venkatakrishnan\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "LoadJNI.java",
    "content": "package go;\n\nimport java.io.FileOutputStream;\nimport java.io.OutputStream;\nimport java.io.InputStream;\nimport java.io.File;\nimport java.io.IOException;\n\npublic class LoadJNI {\n\tstatic {\n\t\ttry {\n\t\t\tloadLibrary();\n\t\t} catch (IOException ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t}\n\t}\n\n\tprivate static void loadLibrary() throws IOException {\n\t\tFile temp = File.createTempFile(\"gojava\", \"gojava\");\n\t\ttemp.deleteOnExit();\n\n\t\tInputStream input = LoadJNI.class.getResourceAsStream(\"/go/libgojava\");\n\t\tif (input == null) {\n\t\t\tthrow new RuntimeException(\"Go JNI library not found in classpath\");\n\t\t}\n\t\tOutputStream out = new FileOutputStream(temp);\n\t\ttry {\n\t\t\tbyte[] buffer = new byte[1024];\n\t\t\tint readBytes = 0;\n\t\t\twhile ((readBytes = input.read(buffer)) != -1) {\n\t\t\t\tout.write(buffer, 0, readBytes);\n\t\t\t}\n\t\t} finally {\n\t\t\tout.close();\n\t\t\tinput.close();\n\t\t}\n\t\tSystem.load(temp.getAbsolutePath());\n\t}\n}"
  },
  {
    "path": "MoreAsserts.java",
    "content": "package go;\n\nimport go.LoadJNI;\nimport java.util.Arrays;\nimport java.lang.Math;\nimport java.lang.reflect.Method;\nimport java.util.regex.Pattern;\n\nimport go.SeqTest;\n\npublic class MoreAsserts {\n    public static void assertTrue(String msg, boolean condition) {\n        if (!condition) {\n            throw new RuntimeException(msg);\n        }\n    }\n\n    public static void assertTrue(boolean condition) {\n        if (!condition) {\n            throw new RuntimeException(\"assert failed\");\n        }\n    }\n\n    public static void assertEquals(int expected, int actual) {\n        assertTrue(expected == actual);\n    }\n\n    public static void assertFalse(boolean condition) {\n        assertTrue(!condition);\n    }\n\n    public static void assertFalse(String msg, boolean condition) {\n        assertTrue(msg, !condition);\n    }\n\n    public static void assertEquals(String msg, int expected, int actual) {\n        assertTrue(msg, expected == actual);\n    }\n\n    public static void assertEquals(String msg, long expected, long actual) {\n        assertTrue(msg, expected == actual);\n    }\n\n    public static void assertEquals(String msg, String expected, String actual) {\n        assertTrue(String.format(\"%s expected:%s != actual:%s\", msg, expected, actual), expected.equals(actual));\n    }\n\n    public static void assertEquals(String msg, boolean expected, boolean actual) {\n        assertTrue(msg, expected == actual);\n    }\n    public static void assertEquals(String msg, byte[] expected, byte[] actual) {\n        assertTrue(msg, Arrays.equals(expected, actual));\n    }\n\n    public static void assertEquals(String msg, double expected, double actual, double epsilon) {\n        assertTrue(msg, Math.abs(expected - actual) < epsilon);\n    }\n\n    public static void assertEquals(String msg, Object expected, Object actual) {\n        assertTrue(msg, (expected == null && actual == null) || (expected.equals(actual)));\n    }\n\n    public static void fail(String msg) {\n        throw new RuntimeException(msg);\n    }\n\n    public static void main(String[] args) {\n        SeqTest test = new SeqTest();\n        Class c = test.getClass();\n        boolean failed = false;\n        for (Method method : c.getDeclaredMethods()) {\n            if (!method.getName().startsWith(\"test\") || !Pattern.matches(args[0], method.getName())) {\n                continue;\n            }\n\n            System.out.print(method.getName());\n            try {\n                method.invoke(test);\n                System.out.println(\" PASS\");\n            } catch (Exception ex) {\n                System.out.println(\" FAIL\");\n                ex.printStackTrace();\n                failed = true;\n            }\n        }\n        // NOTE: We need to call System.exit to force all go threads to exit.\n        System.exit(failed ? 1 : 0);\n    }\n}\n\n"
  },
  {
    "path": "README.md",
    "content": "## GoJava - Java bindings to Go packages [![Build Status](https://travis-ci.org/sridharv/gojava.svg?branch=master)](https://travis-ci.org/sridharv/gojava)\n\nGoJava uses a [forked version of gomobile](https://github.com/sridharv/gomobile-java) to generate Java bindings to Go packages.\nThe same set of types are supported. Details on how the binding works can be found [here](https://godoc.org/golang.org/x/mobile/cmd/gobind).\n\n### Usage\n\n```\n\tgojava [-v] [-o <jar>] [-s <dir>] build [<pkg1>, [<pkg2>...]]\n\n\tThis generates a jar containing Java bindings to the specified Go packages.\n\n\t-o string\n\t    Path to write the generated jar file. (default \"libgojava.jar\")\n\t-s string\n\t    Additional path to scan for Java source code. These files will be compiled and\n\t    included in the final jar.\n\t-v  Verbose output.\n```\n\nYou can include the generated jar in your build using the build tool of your choice.\nThe jar contains a native library (built for the build platform) which is loaded automatically.\nCross platform builds are not currently supported.\n\nNOTE: This has only been tested on an OSX developer machine and Linux (on Travis) and not in production.\n"
  },
  {
    "path": "gojava.go",
    "content": "/*\nCommand gojava is a tool for creating Java bindings to Go packages.\n\nUsage\n\n\tgojava [-v] [-o <jar>] [-s <dir>] build [<pkg1>, [<pkg2>...]]\n\n\tThis generates a jar containing Java bindings to the specified Go packages.\n\n\t-o string\n\t    Path to write the generated jar file. (default \"libgojava.jar\")\n\t-s string\n\t    Additional path to scan for Java source code. These files will be compiled and\n\t    included in the final jar.\n\t-v  Verbose output.\n*/\npackage main\n\nimport (\n\t\"go/build\"\n\t\"path/filepath\"\n\t\"reflect\"\n\n\t\"fmt\"\n\t\"go/importer\"\n\t\"go/token\"\n\t\"go/types\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"io/ioutil\"\n\n\t\"archive/zip\"\n\t\"runtime\"\n\n\t\"flag\"\n\n\t\"github.com/sridharv/gomobile-java/bind\"\n)\n\nfunc runCommand(cmd string, args ...string) error {\n\tif out, err := exec.Command(cmd, args...).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"%s %s: %v: %s\", cmd, strings.Join(args, \" \"), err, string(out))\n\t}\n\treturn nil\n}\n\nvar javaHome = os.Getenv(\"JAVA_HOME\")\nvar cwd string\nvar verbose = false\n\nfunc verbosef(format string, a ...interface{}) {\n\tif !verbose {\n\t\treturn\n\t}\n\tfmt.Printf(format, a...)\n}\n\nfunc initBuild() (string, func(), error) {\n\tif javaHome == \"\" {\n\t\treturn \"\", nil, fmt.Errorf(\"$JAVA_HOME not set\")\n\t}\n\tvar err error\n\tif cwd, err = os.Getwd(); err != nil {\n\t\treturn \"\", nil, err\n\t}\n\ttmpDir, err := ioutil.TempDir(\"\", \"gojava\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treturn tmpDir, func() {\n\t\tif err := os.RemoveAll(tmpDir); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"failed to remove temp dir:\", tmpDir, err)\n\t\t}\n\t\tif err := os.Chdir(cwd); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"failed to change to dir:\", cwd, err)\n\t\t}\n\t}, nil\n}\n\nfunc loadExportData(pkgs []string) ([]*types.Package, error) {\n\t// Load export data for the packages\n\tif err := runCommand(\"go\", append([]string{\"install\"}, pkgs...)...); err != nil {\n\t\treturn nil, err\n\t}\n\ttypePkgs := make([]*types.Package, len(pkgs))\n\n\tfor i, p := range pkgs {\n\t\tbuildPkg, err := build.Import(p, cwd, build.AllowBinary)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif typePkgs[i], err = importer.Default().Import(buildPkg.ImportPath); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn typePkgs, nil\n}\n\nfunc createDirs(dirs ...string) error {\n\tfor _, d := range dirs {\n\t\tif err := os.MkdirAll(d, 0700); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc bindPackages(bindDir, javaDir string, pkgs []*types.Package) ([]string, error) {\n\tfs, javaFiles := token.NewFileSet(), make([]string, 0)\n\tfor _, p := range pkgs {\n\t\tgoFile := filepath.Join(bindDir, \"go_\"+p.Name()+\"main.go\")\n\t\tf, err := os.OpenFile(goFile, os.O_CREATE|os.O_RDWR, 0600)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open: %s: %v\", goFile, err)\n\t\t}\n\t\tconf := &bind.GeneratorConfig{Writer: f, Fset: fs, Pkg: p, AllPkg: pkgs}\n\t\tif err := bind.GenGo(conf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to bind %s:%v\", p.Name(), err)\n\t\t}\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjavaFile := strings.Title(p.Name()) + \".java\"\n\t\tif err := bindJava(javaDir, javaFile, conf, int(bind.Java)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := bindJava(bindDir, \"java_\"+p.Name()+\".c\", conf, int(bind.JavaC)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := bindJava(bindDir, p.Name()+\".h\", conf, int(bind.JavaH)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjavaFiles = append(javaFiles, filepath.Join(javaDir, javaFile))\n\t}\n\treturn javaFiles, nil\n}\n\nfunc addExtraFiles(javaDir, sourceDir string) ([]string, error) {\n\tif sourceDir == \"\" {\n\t\treturn nil, nil\n\t}\n\tvar extraFiles []string\n\terr := filepath.Walk(sourceDir, func(path string, info os.FileInfo, walkErr error) error {\n\t\tif walkErr != nil {\n\t\t\treturn walkErr\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tfileName, err := filepath.Rel(sourceDir, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif strings.HasSuffix(fileName, \".java\") {\n\t\t\tp := filepath.Join(javaDir, fileName)\n\t\t\textraFiles = append(extraFiles, p)\n\t\t\treturn copyFile(p, path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(extraFiles) == 0 {\n\t\tverbosef(\"warning: argument -s was passed on command line, but no .java files were found in '%s'\\n\", sourceDir)\n\t}\n\treturn extraFiles, nil\n}\n\nfunc createSupportFiles(bindDir, javaDir, mainFile string) error {\n\tbindPkg, err := build.Import(reflect.TypeOf(bind.ErrorList{}).PkgPath(), \"\", build.FindOnly)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbindJavaPkgDir := filepath.Join(bindPkg.Dir, \"java\")\n\ttoCopy := []filePair{\n\t\t{filepath.Join(bindDir, \"seq.go\"), filepath.Join(bindPkg.Dir, \"seq.go.support\")},\n\t\t{filepath.Join(bindDir, \"seq_java.go\"), filepath.Join(bindJavaPkgDir, \"seq_android.go.support\")},\n\t\t{filepath.Join(bindDir, \"seq.c\"), filepath.Join(bindJavaPkgDir, \"seq_android.c.support\")},\n\t\t{filepath.Join(bindDir, \"seq.h\"), filepath.Join(bindJavaPkgDir, \"seq.h\")},\n\t\t{filepath.Join(javaDir, \"Seq.java\"), filepath.Join(bindJavaPkgDir, \"Seq.java\")},\n\t\t{filepath.Join(javaDir, \"LoadJNI.java\"), filepath.Join(bindPkg.Dir, \"..\", \"..\", \"gojava\", \"LoadJNI.java\")},\n\t}\n\tif err := copyFiles(toCopy); err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(mainFile, []byte(fmt.Sprintf(javaMain, bindPkg.ImportPath)), 0600); err != nil {\n\t\treturn err\n\t}\n\tinc1, inc2 := filepath.Join(javaHome, \"include\"), filepath.Join(javaHome, \"include\", runtime.GOOS)\n\tflagFile := filepath.Join(bindDir, \"gojavacimport.go\")\n\n\treturn ioutil.WriteFile(flagFile, []byte(fmt.Sprintf(javaInclude, inc1, inc2)), 0600)\n}\n\nfunc buildGo(classDir, mainDir string) error {\n\tdylib := filepath.Join(classDir, \"libgojava\")\n\tif err := os.Chdir(mainDir); err != nil {\n\t\treturn err\n\t}\n\treturn runCommand(\"go\", \"build\", \"-o\", dylib, \"-buildmode=c-shared\", \".\")\n}\n\nfunc buildJava(jarDir, javaDir string, javaFiles []string) error {\n\tif err := os.Chdir(javaDir); err != nil {\n\t\treturn err\n\t}\n\tjavaFiles = append(javaFiles, filepath.Join(javaDir, \"Seq.java\"), filepath.Join(javaDir, \"LoadJNI.java\"))\n\treturn runCommand(\"javac\", append([]string{\n\t\t\"-d\", jarDir,\n\t\t\"-sourcepath\", filepath.Join(javaDir, \"..\"),\n\t}, javaFiles...)...)\n}\n\nfunc createJar(target, jarDir string) error {\n\tif err := os.Chdir(cwd); err != nil {\n\t\treturn err\n\t}\n\n\tdirName := filepath.Dir(target)\n\tif _, err := os.Stat(dirName); err != nil && err == os.ErrNotExist {\n\t\tif err = os.MkdirAll(dirName, 0644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create: %v: %+v\", dirName, err)\n\t\t}\n\t}\n\n\tt, err := ioutil.TempFile(dirName, \".\"+filepath.Base(target)+\".tmp\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create temporary file: %+v\", err)\n\t}\n\ttempFileName := t.Name()\n\tvar successful bool\n\tdefer func() {\n\t\tif successful {\n\t\t\treturn\n\t\t}\n\t\tif err := os.Remove(tempFileName); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"WARNING: failed to delete temporary file %s: %+v\", tempFileName, err)\n\t\t}\n\t}()\n\tw := zip.NewWriter(t)\n\tverbosef(\"Building %s\\n\", tempFileName)\n\tif err := filepath.Walk(jarDir, func(path string, info os.FileInfo, walkErr error) error {\n\t\tif walkErr != nil {\n\t\t\treturn walkErr\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tfileName, err := filepath.Rel(jarDir, path)\n\t\tverbosef(\"Adding %s\\n\", fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf, err := w.Create(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Write(d); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := w.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := t.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Rename(tempFileName, target); err != nil {\n\t\treturn fmt.Errorf(\"failed to atomically rename: %v\", err)\n\t}\n\tsuccessful = true\n\tfmt.Printf(\"Finished building %s\\n\", target)\n\treturn nil\n}\n\nfunc bindToJar(target string, sourceDir string, pkgs ...string) error {\n\ttmpDir, cleanup, err := initBuild()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cleanup()\n\n\ttypePkgs, err := loadExportData(pkgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbindDir := filepath.Join(tmpDir, \"gojava_bind\")\n\tmainDir := filepath.Join(bindDir, \"main\")\n\tmainFile := filepath.Join(mainDir, \"main.go\")\n\tjavaDir := filepath.Join(tmpDir, \"src/go\")\n\tjarDir := filepath.Join(tmpDir, \"classes\")\n\tclassDir := filepath.Join(tmpDir, \"classes/go\")\n\n\tif err = createDirs(classDir, javaDir, mainDir); err != nil {\n\t\treturn err\n\t}\n\n\tjavaFiles, err := bindPackages(bindDir, javaDir, typePkgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\textraFiles, err := addExtraFiles(javaDir, sourceDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjavaFiles = append(javaFiles, extraFiles...)\n\tif err := createSupportFiles(bindDir, javaDir, mainFile); err != nil {\n\t\treturn err\n\t}\n\n\tif err := buildGo(classDir, mainDir); err != nil {\n\t\treturn err\n\t}\n\tif err := buildJava(jarDir, javaDir, javaFiles); err != nil {\n\t\treturn err\n\t}\n\treturn createJar(target, jarDir)\n}\n\nfunc copyFile(dst, src string) error {\n\td, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dst, d, 0600)\n}\n\ntype filePair struct {\n\tdst string\n\tsrc string\n}\n\nfunc copyFiles(files []filePair) error {\n\tfor _, p := range files {\n\t\tif err := copyFile(p.dst, p.src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc bindJava(dir, file string, conf *bind.GeneratorConfig, ft int) error {\n\tpath := filepath.Join(dir, file)\n\tw, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate %s: %v\", path, err)\n\t}\n\tconf.Writer = w\n\tdefer func() { conf.Writer = nil }()\n\n\tswitch ft {\n\tcase int(bind.Java):\n\t\terr = bind.GenJava(conf, \"\", bind.Java)\n\tcase int(bind.JavaH):\n\t\terr = bind.GenJava(conf, \"\", bind.JavaH)\n\tcase int(bind.JavaC):\n\t\terr = bind.GenJava(conf, \"\", bind.JavaC)\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported bind type: %d\", ft)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.Close()\n}\n\nconst javaInclude = `package gojava_bind\n\n// #cgo CFLAGS: -Wall -I%s -I%s\nimport \"C\"\n\n`\nconst javaMain = `package main\n\nimport (\n\t_ %q\n\t_ \"..\"\n)\n\nfunc main() {}\n`\n\nconst usage = `gojava is a tool for creating Java bindings to Go\n\nUsage:\n\n\tgojava [-v] [-o <jar>] [-s <dir>] build [<pkg1>, [<pkg2>...]]\n\nThis generates a jar containing Java bindings to the specified Go packages.\n`\n\nfunc main() {\n\to := flag.String(\"o\", \"libgojava.jar\", \"Path to the generated jar file.\")\n\ts := flag.String(\"s\", \"\", \"Additional path to scan for Java source code.\")\n\tflag.BoolVar(&verbose, \"v\", false, \"Verbose output.\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, usage)\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif flag.NArg() < 2 || flag.Args()[0] != \"build\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif err := bindToJar(*o, *s, flag.Args()[1:]...); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "gojava_test.go",
    "content": "package main\n\nimport (\n\t\"testing\"\n\n\t\"flag\"\n\t\"go/build\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/surullabs/lint\"\n)\n\nvar javaTest = flag.String(\"javatest\", \".*\", \"Run only java tests matching the regular expression\")\n\nfunc init() {\n\tverbose = testing.Verbose()\n}\n\nfunc TestLint(t *testing.T) {\n\tif err := lint.Default.Check(\".\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestJavaBind(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"gojavatest\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tjar := filepath.Join(tmpDir, \"gojavatest.jar\")\n\tif err := bindToJar(jar,\n\t\t\"\",\n\t\t\"github.com/sridharv/gomobile-java/bind/testpkg\",\n\t\t\"github.com/sridharv/gomobile-java/bind/testpkg/secondpkg\",\n\t\t\"github.com/sridharv/gomobile-java/bind/testpkg/simplepkg\",\n\t); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttoCopy := []filePair{\n\t\t{filepath.Join(tmpDir, \"MoreAsserts.java\"), \"MoreAsserts.java\"},\n\t\t{filepath.Join(tmpDir, \"SeqTest.java\"), filepath.Join(build.Default.GOPATH, \"src/github.com/sridharv/gomobile-java/bind/java/SeqTest.java\")},\n\t}\n\tif err := copyFiles(toCopy); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := runCommand(\"javac\", \"-cp\", jar, \"-d\", tmpDir, toCopy[0].dst, toCopy[1].dst); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcmd := exec.Command(\"java\", \"-cp\", jar+\":\"+tmpDir, \"go.MoreAsserts\", *javaTest)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tif err := cmd.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestSourceDir(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"gojavatest\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tjar := filepath.Join(tmpDir, \"gojavatest.jar\")\n\tif err := bindToJar(jar,\n\t\t\"testdata\",\n\t\t\"github.com/sridharv/gomobile-java/bind/testpkg\",\n\t); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcmd := exec.Command(\"java\", \"-cp\", jar, \"go.SourceDirTest\")\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tif err := cmd.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n"
  },
  {
    "path": "testdata/SourceDirTest.java",
    "content": "package go;\n\npublic class SourceDirTest {\n    public static void main(String[] args) {\n        System.out.println(\"testSourceDirInclusion PASS\");\n    }\n}"
  }
]