├── .gitignore ├── .travis.yml ├── LICENSE ├── LoadJNI.java ├── MoreAsserts.java ├── README.md ├── gojava.go ├── gojava_test.go └── testdata └── SourceDirTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | *.swp 27 | 28 | .idea 29 | *.iml 30 | 31 | node_modules 32 | out 33 | tutorials 34 | .DS_Store 35 | 36 | *.xcuserstate 37 | project.xcworkspace/ 38 | 39 | .Trashes 40 | 41 | *~.nib 42 | DerivedData/ 43 | build/ 44 | 45 | /vendor/ 46 | 47 | *.pbxuser 48 | 49 | # .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html 50 | 51 | *.mode1v3 52 | 53 | # .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html 54 | 55 | *.mode2v3 56 | 57 | # .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file 58 | 59 | *.perspectivev3 60 | 61 | # NB: also, whitelist the default ones, some projects need to use these 62 | !default.pbxuser 63 | !default.mode1v3 64 | !default.mode2v3 65 | !default.perspectivev3 66 | 67 | 68 | #### 69 | # Xcode 4 - semi-personal settings 70 | # 71 | # Apple Shared data that Apple put in the wrong folder 72 | # c.f. http://stackoverflow.com/a/19260712/153422 73 | # FROM ANSWER: Apple says "don't ignore it" 74 | # 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 75 | # Up to you, but ... current advice: ignore it. 76 | *.xccheckout 77 | 78 | # 79 | # 80 | # OPTION 1: --------------------------------- 81 | # throw away ALL personal settings (including custom schemes! 82 | # - unless they are "shared") 83 | # As per build/ and DerivedData/, this ought to have a trailing slash 84 | # 85 | # NB: this is exclusive with OPTION 2 below 86 | xcuserdata/ 87 | 88 | # OPTION 2: --------------------------------- 89 | # get rid of ALL personal settings, but KEEP SOME OF THEM 90 | # - NB: you must manually uncomment the bits you want to keep 91 | # 92 | # NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X, 93 | # or manually install git over the top of the OS X version 94 | # NB: this is exclusive with OPTION 1 above 95 | # 96 | #xcuserdata/**/* 97 | 98 | # (requires option 2 above): Personal Schemes 99 | # 100 | #!xcuserdata/**/xcschemes/* 101 | 102 | #### 103 | # XCode 4 workspaces - more detailed 104 | # 105 | # Workspaces are important! They are a core feature of Xcode - don't exclude them :) 106 | # 107 | # Workspace layout is quite spammy. For reference: 108 | # 109 | # /(root)/ 110 | # /(project-name).xcodeproj/ 111 | # project.pbxproj 112 | # /project.xcworkspace/ 113 | # contents.xcworkspacedata 114 | # /xcuserdata/ 115 | # /(your name)/xcuserdatad/ 116 | # UserInterfaceState.xcuserstate 117 | # /xcshareddata/ 118 | # /xcschemes/ 119 | # (shared scheme name).xcscheme 120 | # /xcuserdata/ 121 | # /(your name)/xcuserdatad/ 122 | # (private scheme).xcscheme 123 | # xcschememanagement.plist 124 | # 125 | # 126 | 127 | #### 128 | # Xcode 4 - Deprecated classes 129 | # 130 | # Allegedly, if you manually "deprecate" your classes, they get moved here. 131 | # 132 | # We're using source-control, so this is a "feature" that we do not want! 133 | 134 | *.moved-aside 135 | 136 | # 137 | # COCOAPODS: 138 | # 139 | # c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock 140 | # c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 141 | 142 | !Podfile.lock 143 | 144 | # Android 145 | # 146 | # Built application files 147 | *.apk 148 | *.ap_ 149 | 150 | # Files for the Dalvik VM 151 | *.dex 152 | 153 | # Java class files 154 | *.class 155 | 156 | # Generated files 157 | bin/ 158 | gen/ 159 | 160 | # Gradle files 161 | .gradle/ 162 | build/ 163 | 164 | # Local configuration file (sdk path, etc) 165 | local.properties 166 | 167 | # Proguard folder generated by Eclipse 168 | proguard/ 169 | 170 | # Log Files 171 | *.log 172 | 173 | # Android Studio Navigation editor temp files 174 | .navigation/ 175 | 176 | # Android Studio captures folder 177 | captures/ 178 | 179 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.6 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Sridhar Venkatakrishnan 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LoadJNI.java: -------------------------------------------------------------------------------- 1 | package go; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.OutputStream; 5 | import java.io.InputStream; 6 | import java.io.File; 7 | import java.io.IOException; 8 | 9 | public class LoadJNI { 10 | static { 11 | try { 12 | loadLibrary(); 13 | } catch (IOException ex) { 14 | throw new RuntimeException(ex); 15 | } 16 | } 17 | 18 | private static void loadLibrary() throws IOException { 19 | File temp = File.createTempFile("gojava", "gojava"); 20 | temp.deleteOnExit(); 21 | 22 | InputStream input = LoadJNI.class.getResourceAsStream("/go/libgojava"); 23 | if (input == null) { 24 | throw new RuntimeException("Go JNI library not found in classpath"); 25 | } 26 | OutputStream out = new FileOutputStream(temp); 27 | try { 28 | byte[] buffer = new byte[1024]; 29 | int readBytes = 0; 30 | while ((readBytes = input.read(buffer)) != -1) { 31 | out.write(buffer, 0, readBytes); 32 | } 33 | } finally { 34 | out.close(); 35 | input.close(); 36 | } 37 | System.load(temp.getAbsolutePath()); 38 | } 39 | } -------------------------------------------------------------------------------- /MoreAsserts.java: -------------------------------------------------------------------------------- 1 | package go; 2 | 3 | import go.LoadJNI; 4 | import java.util.Arrays; 5 | import java.lang.Math; 6 | import java.lang.reflect.Method; 7 | import java.util.regex.Pattern; 8 | 9 | import go.SeqTest; 10 | 11 | public class MoreAsserts { 12 | public static void assertTrue(String msg, boolean condition) { 13 | if (!condition) { 14 | throw new RuntimeException(msg); 15 | } 16 | } 17 | 18 | public static void assertTrue(boolean condition) { 19 | if (!condition) { 20 | throw new RuntimeException("assert failed"); 21 | } 22 | } 23 | 24 | public static void assertEquals(int expected, int actual) { 25 | assertTrue(expected == actual); 26 | } 27 | 28 | public static void assertFalse(boolean condition) { 29 | assertTrue(!condition); 30 | } 31 | 32 | public static void assertFalse(String msg, boolean condition) { 33 | assertTrue(msg, !condition); 34 | } 35 | 36 | public static void assertEquals(String msg, int expected, int actual) { 37 | assertTrue(msg, expected == actual); 38 | } 39 | 40 | public static void assertEquals(String msg, long expected, long actual) { 41 | assertTrue(msg, expected == actual); 42 | } 43 | 44 | public static void assertEquals(String msg, String expected, String actual) { 45 | assertTrue(String.format("%s expected:%s != actual:%s", msg, expected, actual), expected.equals(actual)); 46 | } 47 | 48 | public static void assertEquals(String msg, boolean expected, boolean actual) { 49 | assertTrue(msg, expected == actual); 50 | } 51 | public static void assertEquals(String msg, byte[] expected, byte[] actual) { 52 | assertTrue(msg, Arrays.equals(expected, actual)); 53 | } 54 | 55 | public static void assertEquals(String msg, double expected, double actual, double epsilon) { 56 | assertTrue(msg, Math.abs(expected - actual) < epsilon); 57 | } 58 | 59 | public static void assertEquals(String msg, Object expected, Object actual) { 60 | assertTrue(msg, (expected == null && actual == null) || (expected.equals(actual))); 61 | } 62 | 63 | public static void fail(String msg) { 64 | throw new RuntimeException(msg); 65 | } 66 | 67 | public static void main(String[] args) { 68 | SeqTest test = new SeqTest(); 69 | Class c = test.getClass(); 70 | boolean failed = false; 71 | for (Method method : c.getDeclaredMethods()) { 72 | if (!method.getName().startsWith("test") || !Pattern.matches(args[0], method.getName())) { 73 | continue; 74 | } 75 | 76 | System.out.print(method.getName()); 77 | try { 78 | method.invoke(test); 79 | System.out.println(" PASS"); 80 | } catch (Exception ex) { 81 | System.out.println(" FAIL"); 82 | ex.printStackTrace(); 83 | failed = true; 84 | } 85 | } 86 | // NOTE: We need to call System.exit to force all go threads to exit. 87 | System.exit(failed ? 1 : 0); 88 | } 89 | } 90 | 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## GoJava - Java bindings to Go packages [![Build Status](https://travis-ci.org/sridharv/gojava.svg?branch=master)](https://travis-ci.org/sridharv/gojava) 2 | 3 | GoJava uses a [forked version of gomobile](https://github.com/sridharv/gomobile-java) to generate Java bindings to Go packages. 4 | The 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). 5 | 6 | ### Usage 7 | 8 | ``` 9 | gojava [-v] [-o ] [-s ] build [, [...]] 10 | 11 | This generates a jar containing Java bindings to the specified Go packages. 12 | 13 | -o string 14 | Path to write the generated jar file. (default "libgojava.jar") 15 | -s string 16 | Additional path to scan for Java source code. These files will be compiled and 17 | included in the final jar. 18 | -v Verbose output. 19 | ``` 20 | 21 | You can include the generated jar in your build using the build tool of your choice. 22 | The jar contains a native library (built for the build platform) which is loaded automatically. 23 | Cross platform builds are not currently supported. 24 | 25 | NOTE: This has only been tested on an OSX developer machine and Linux (on Travis) and not in production. 26 | -------------------------------------------------------------------------------- /gojava.go: -------------------------------------------------------------------------------- 1 | /* 2 | Command gojava is a tool for creating Java bindings to Go packages. 3 | 4 | Usage 5 | 6 | gojava [-v] [-o ] [-s ] build [, [...]] 7 | 8 | This generates a jar containing Java bindings to the specified Go packages. 9 | 10 | -o string 11 | Path to write the generated jar file. (default "libgojava.jar") 12 | -s string 13 | Additional path to scan for Java source code. These files will be compiled and 14 | included in the final jar. 15 | -v Verbose output. 16 | */ 17 | package main 18 | 19 | import ( 20 | "go/build" 21 | "path/filepath" 22 | "reflect" 23 | 24 | "fmt" 25 | "go/importer" 26 | "go/token" 27 | "go/types" 28 | "os" 29 | "os/exec" 30 | "strings" 31 | 32 | "io/ioutil" 33 | 34 | "archive/zip" 35 | "runtime" 36 | 37 | "flag" 38 | 39 | "github.com/sridharv/gomobile-java/bind" 40 | ) 41 | 42 | func runCommand(cmd string, args ...string) error { 43 | if out, err := exec.Command(cmd, args...).CombinedOutput(); err != nil { 44 | return fmt.Errorf("%s %s: %v: %s", cmd, strings.Join(args, " "), err, string(out)) 45 | } 46 | return nil 47 | } 48 | 49 | var javaHome = os.Getenv("JAVA_HOME") 50 | var cwd string 51 | var verbose = false 52 | 53 | func verbosef(format string, a ...interface{}) { 54 | if !verbose { 55 | return 56 | } 57 | fmt.Printf(format, a...) 58 | } 59 | 60 | func initBuild() (string, func(), error) { 61 | if javaHome == "" { 62 | return "", nil, fmt.Errorf("$JAVA_HOME not set") 63 | } 64 | var err error 65 | if cwd, err = os.Getwd(); err != nil { 66 | return "", nil, err 67 | } 68 | tmpDir, err := ioutil.TempDir("", "gojava") 69 | if err != nil { 70 | return "", nil, err 71 | } 72 | return tmpDir, func() { 73 | if err := os.RemoveAll(tmpDir); err != nil { 74 | fmt.Fprintln(os.Stderr, "failed to remove temp dir:", tmpDir, err) 75 | } 76 | if err := os.Chdir(cwd); err != nil { 77 | fmt.Fprintln(os.Stderr, "failed to change to dir:", cwd, err) 78 | } 79 | }, nil 80 | } 81 | 82 | func loadExportData(pkgs []string) ([]*types.Package, error) { 83 | // Load export data for the packages 84 | if err := runCommand("go", append([]string{"install"}, pkgs...)...); err != nil { 85 | return nil, err 86 | } 87 | typePkgs := make([]*types.Package, len(pkgs)) 88 | 89 | for i, p := range pkgs { 90 | buildPkg, err := build.Import(p, cwd, build.AllowBinary) 91 | if err != nil { 92 | return nil, err 93 | } 94 | if typePkgs[i], err = importer.Default().Import(buildPkg.ImportPath); err != nil { 95 | return nil, err 96 | } 97 | } 98 | return typePkgs, nil 99 | } 100 | 101 | func createDirs(dirs ...string) error { 102 | for _, d := range dirs { 103 | if err := os.MkdirAll(d, 0700); err != nil { 104 | return err 105 | } 106 | } 107 | return nil 108 | } 109 | 110 | func bindPackages(bindDir, javaDir string, pkgs []*types.Package) ([]string, error) { 111 | fs, javaFiles := token.NewFileSet(), make([]string, 0) 112 | for _, p := range pkgs { 113 | goFile := filepath.Join(bindDir, "go_"+p.Name()+"main.go") 114 | f, err := os.OpenFile(goFile, os.O_CREATE|os.O_RDWR, 0600) 115 | if err != nil { 116 | return nil, fmt.Errorf("failed to open: %s: %v", goFile, err) 117 | } 118 | conf := &bind.GeneratorConfig{Writer: f, Fset: fs, Pkg: p, AllPkg: pkgs} 119 | if err := bind.GenGo(conf); err != nil { 120 | return nil, fmt.Errorf("failed to bind %s:%v", p.Name(), err) 121 | } 122 | if err := f.Close(); err != nil { 123 | return nil, err 124 | } 125 | javaFile := strings.Title(p.Name()) + ".java" 126 | if err := bindJava(javaDir, javaFile, conf, int(bind.Java)); err != nil { 127 | return nil, err 128 | } 129 | if err := bindJava(bindDir, "java_"+p.Name()+".c", conf, int(bind.JavaC)); err != nil { 130 | return nil, err 131 | } 132 | if err := bindJava(bindDir, p.Name()+".h", conf, int(bind.JavaH)); err != nil { 133 | return nil, err 134 | } 135 | javaFiles = append(javaFiles, filepath.Join(javaDir, javaFile)) 136 | } 137 | return javaFiles, nil 138 | } 139 | 140 | func addExtraFiles(javaDir, sourceDir string) ([]string, error) { 141 | if sourceDir == "" { 142 | return nil, nil 143 | } 144 | var extraFiles []string 145 | err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, walkErr error) error { 146 | if walkErr != nil { 147 | return walkErr 148 | } 149 | if info.IsDir() { 150 | return nil 151 | } 152 | fileName, err := filepath.Rel(sourceDir, path) 153 | if err != nil { 154 | return err 155 | } 156 | if strings.HasSuffix(fileName, ".java") { 157 | p := filepath.Join(javaDir, fileName) 158 | extraFiles = append(extraFiles, p) 159 | return copyFile(p, path) 160 | } 161 | return nil 162 | }) 163 | if err != nil { 164 | return nil, err 165 | } 166 | if len(extraFiles) == 0 { 167 | verbosef("warning: argument -s was passed on command line, but no .java files were found in '%s'\n", sourceDir) 168 | } 169 | return extraFiles, nil 170 | } 171 | 172 | func createSupportFiles(bindDir, javaDir, mainFile string) error { 173 | bindPkg, err := build.Import(reflect.TypeOf(bind.ErrorList{}).PkgPath(), "", build.FindOnly) 174 | if err != nil { 175 | return err 176 | } 177 | bindJavaPkgDir := filepath.Join(bindPkg.Dir, "java") 178 | toCopy := []filePair{ 179 | {filepath.Join(bindDir, "seq.go"), filepath.Join(bindPkg.Dir, "seq.go.support")}, 180 | {filepath.Join(bindDir, "seq_java.go"), filepath.Join(bindJavaPkgDir, "seq_android.go.support")}, 181 | {filepath.Join(bindDir, "seq.c"), filepath.Join(bindJavaPkgDir, "seq_android.c.support")}, 182 | {filepath.Join(bindDir, "seq.h"), filepath.Join(bindJavaPkgDir, "seq.h")}, 183 | {filepath.Join(javaDir, "Seq.java"), filepath.Join(bindJavaPkgDir, "Seq.java")}, 184 | {filepath.Join(javaDir, "LoadJNI.java"), filepath.Join(bindPkg.Dir, "..", "..", "gojava", "LoadJNI.java")}, 185 | } 186 | if err := copyFiles(toCopy); err != nil { 187 | return err 188 | } 189 | if err := ioutil.WriteFile(mainFile, []byte(fmt.Sprintf(javaMain, bindPkg.ImportPath)), 0600); err != nil { 190 | return err 191 | } 192 | inc1, inc2 := filepath.Join(javaHome, "include"), filepath.Join(javaHome, "include", runtime.GOOS) 193 | flagFile := filepath.Join(bindDir, "gojavacimport.go") 194 | 195 | return ioutil.WriteFile(flagFile, []byte(fmt.Sprintf(javaInclude, inc1, inc2)), 0600) 196 | } 197 | 198 | func buildGo(classDir, mainDir string) error { 199 | dylib := filepath.Join(classDir, "libgojava") 200 | if err := os.Chdir(mainDir); err != nil { 201 | return err 202 | } 203 | return runCommand("go", "build", "-o", dylib, "-buildmode=c-shared", ".") 204 | } 205 | 206 | func buildJava(jarDir, javaDir string, javaFiles []string) error { 207 | if err := os.Chdir(javaDir); err != nil { 208 | return err 209 | } 210 | javaFiles = append(javaFiles, filepath.Join(javaDir, "Seq.java"), filepath.Join(javaDir, "LoadJNI.java")) 211 | return runCommand("javac", append([]string{ 212 | "-d", jarDir, 213 | "-sourcepath", filepath.Join(javaDir, ".."), 214 | }, javaFiles...)...) 215 | } 216 | 217 | func createJar(target, jarDir string) error { 218 | if err := os.Chdir(cwd); err != nil { 219 | return err 220 | } 221 | 222 | dirName := filepath.Dir(target) 223 | if _, err := os.Stat(dirName); err != nil && err == os.ErrNotExist { 224 | if err = os.MkdirAll(dirName, 0644); err != nil { 225 | return fmt.Errorf("failed to create: %v: %+v", dirName, err) 226 | } 227 | } 228 | 229 | t, err := ioutil.TempFile(dirName, "."+filepath.Base(target)+".tmp") 230 | if err != nil { 231 | return fmt.Errorf("failed to create temporary file: %+v", err) 232 | } 233 | tempFileName := t.Name() 234 | var successful bool 235 | defer func() { 236 | if successful { 237 | return 238 | } 239 | if err := os.Remove(tempFileName); err != nil { 240 | fmt.Fprintf(os.Stderr, "WARNING: failed to delete temporary file %s: %+v", tempFileName, err) 241 | } 242 | }() 243 | w := zip.NewWriter(t) 244 | verbosef("Building %s\n", tempFileName) 245 | if err := filepath.Walk(jarDir, func(path string, info os.FileInfo, walkErr error) error { 246 | if walkErr != nil { 247 | return walkErr 248 | } 249 | if info.IsDir() { 250 | return nil 251 | } 252 | fileName, err := filepath.Rel(jarDir, path) 253 | verbosef("Adding %s\n", fileName) 254 | if err != nil { 255 | return err 256 | } 257 | f, err := w.Create(fileName) 258 | if err != nil { 259 | return err 260 | } 261 | d, err := ioutil.ReadFile(path) 262 | if err != nil { 263 | return err 264 | } 265 | if _, err := f.Write(d); err != nil { 266 | return err 267 | } 268 | return nil 269 | }); err != nil { 270 | return err 271 | } 272 | if err := w.Close(); err != nil { 273 | return err 274 | } 275 | if err := t.Close(); err != nil { 276 | return err 277 | } 278 | if err := os.Rename(tempFileName, target); err != nil { 279 | return fmt.Errorf("failed to atomically rename: %v", err) 280 | } 281 | successful = true 282 | fmt.Printf("Finished building %s\n", target) 283 | return nil 284 | } 285 | 286 | func bindToJar(target string, sourceDir string, pkgs ...string) error { 287 | tmpDir, cleanup, err := initBuild() 288 | if err != nil { 289 | return err 290 | } 291 | defer cleanup() 292 | 293 | typePkgs, err := loadExportData(pkgs) 294 | if err != nil { 295 | return err 296 | } 297 | 298 | bindDir := filepath.Join(tmpDir, "gojava_bind") 299 | mainDir := filepath.Join(bindDir, "main") 300 | mainFile := filepath.Join(mainDir, "main.go") 301 | javaDir := filepath.Join(tmpDir, "src/go") 302 | jarDir := filepath.Join(tmpDir, "classes") 303 | classDir := filepath.Join(tmpDir, "classes/go") 304 | 305 | if err = createDirs(classDir, javaDir, mainDir); err != nil { 306 | return err 307 | } 308 | 309 | javaFiles, err := bindPackages(bindDir, javaDir, typePkgs) 310 | if err != nil { 311 | return err 312 | } 313 | extraFiles, err := addExtraFiles(javaDir, sourceDir) 314 | if err != nil { 315 | return err 316 | } 317 | javaFiles = append(javaFiles, extraFiles...) 318 | if err := createSupportFiles(bindDir, javaDir, mainFile); err != nil { 319 | return err 320 | } 321 | 322 | if err := buildGo(classDir, mainDir); err != nil { 323 | return err 324 | } 325 | if err := buildJava(jarDir, javaDir, javaFiles); err != nil { 326 | return err 327 | } 328 | return createJar(target, jarDir) 329 | } 330 | 331 | func copyFile(dst, src string) error { 332 | d, err := ioutil.ReadFile(src) 333 | if err != nil { 334 | return err 335 | } 336 | return ioutil.WriteFile(dst, d, 0600) 337 | } 338 | 339 | type filePair struct { 340 | dst string 341 | src string 342 | } 343 | 344 | func copyFiles(files []filePair) error { 345 | for _, p := range files { 346 | if err := copyFile(p.dst, p.src); err != nil { 347 | return err 348 | } 349 | } 350 | return nil 351 | } 352 | 353 | func bindJava(dir, file string, conf *bind.GeneratorConfig, ft int) error { 354 | path := filepath.Join(dir, file) 355 | w, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) 356 | if err != nil { 357 | return fmt.Errorf("failed to generate %s: %v", path, err) 358 | } 359 | conf.Writer = w 360 | defer func() { conf.Writer = nil }() 361 | 362 | switch ft { 363 | case int(bind.Java): 364 | err = bind.GenJava(conf, "", bind.Java) 365 | case int(bind.JavaH): 366 | err = bind.GenJava(conf, "", bind.JavaH) 367 | case int(bind.JavaC): 368 | err = bind.GenJava(conf, "", bind.JavaC) 369 | default: 370 | err = fmt.Errorf("unsupported bind type: %d", ft) 371 | } 372 | if err != nil { 373 | return err 374 | } 375 | return w.Close() 376 | } 377 | 378 | const javaInclude = `package gojava_bind 379 | 380 | // #cgo CFLAGS: -Wall -I%s -I%s 381 | import "C" 382 | 383 | ` 384 | const javaMain = `package main 385 | 386 | import ( 387 | _ %q 388 | _ ".." 389 | ) 390 | 391 | func main() {} 392 | ` 393 | 394 | const usage = `gojava is a tool for creating Java bindings to Go 395 | 396 | Usage: 397 | 398 | gojava [-v] [-o ] [-s ] build [, [...]] 399 | 400 | This generates a jar containing Java bindings to the specified Go packages. 401 | ` 402 | 403 | func main() { 404 | o := flag.String("o", "libgojava.jar", "Path to the generated jar file.") 405 | s := flag.String("s", "", "Additional path to scan for Java source code.") 406 | flag.BoolVar(&verbose, "v", false, "Verbose output.") 407 | flag.Usage = func() { 408 | fmt.Fprintln(os.Stderr, usage) 409 | flag.PrintDefaults() 410 | } 411 | flag.Parse() 412 | if flag.NArg() < 2 || flag.Args()[0] != "build" { 413 | flag.Usage() 414 | os.Exit(1) 415 | } 416 | if err := bindToJar(*o, *s, flag.Args()[1:]...); err != nil { 417 | fmt.Fprintln(os.Stderr, err) 418 | os.Exit(1) 419 | } 420 | } 421 | -------------------------------------------------------------------------------- /gojava_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "flag" 7 | "go/build" 8 | "io/ioutil" 9 | "os" 10 | "os/exec" 11 | "path/filepath" 12 | 13 | "github.com/surullabs/lint" 14 | ) 15 | 16 | var javaTest = flag.String("javatest", ".*", "Run only java tests matching the regular expression") 17 | 18 | func init() { 19 | verbose = testing.Verbose() 20 | } 21 | 22 | func TestLint(t *testing.T) { 23 | if err := lint.Default.Check("."); err != nil { 24 | t.Fatal(err) 25 | } 26 | } 27 | 28 | func TestJavaBind(t *testing.T) { 29 | tmpDir, err := ioutil.TempDir("", "gojavatest") 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | jar := filepath.Join(tmpDir, "gojavatest.jar") 34 | if err := bindToJar(jar, 35 | "", 36 | "github.com/sridharv/gomobile-java/bind/testpkg", 37 | "github.com/sridharv/gomobile-java/bind/testpkg/secondpkg", 38 | "github.com/sridharv/gomobile-java/bind/testpkg/simplepkg", 39 | ); err != nil { 40 | t.Fatal(err) 41 | } 42 | 43 | toCopy := []filePair{ 44 | {filepath.Join(tmpDir, "MoreAsserts.java"), "MoreAsserts.java"}, 45 | {filepath.Join(tmpDir, "SeqTest.java"), filepath.Join(build.Default.GOPATH, "src/github.com/sridharv/gomobile-java/bind/java/SeqTest.java")}, 46 | } 47 | if err := copyFiles(toCopy); err != nil { 48 | t.Fatal(err) 49 | } 50 | if err := runCommand("javac", "-cp", jar, "-d", tmpDir, toCopy[0].dst, toCopy[1].dst); err != nil { 51 | t.Fatal(err) 52 | } 53 | cmd := exec.Command("java", "-cp", jar+":"+tmpDir, "go.MoreAsserts", *javaTest) 54 | cmd.Stderr = os.Stderr 55 | cmd.Stdout = os.Stdout 56 | if err := cmd.Run(); err != nil { 57 | t.Fatal(err) 58 | } 59 | } 60 | 61 | func TestSourceDir(t *testing.T) { 62 | tmpDir, err := ioutil.TempDir("", "gojavatest") 63 | if err != nil { 64 | t.Fatal(err) 65 | } 66 | jar := filepath.Join(tmpDir, "gojavatest.jar") 67 | if err := bindToJar(jar, 68 | "testdata", 69 | "github.com/sridharv/gomobile-java/bind/testpkg", 70 | ); err != nil { 71 | t.Fatal(err) 72 | } 73 | cmd := exec.Command("java", "-cp", jar, "go.SourceDirTest") 74 | cmd.Stderr = os.Stderr 75 | cmd.Stdout = os.Stdout 76 | if err := cmd.Run(); err != nil { 77 | t.Fatal(err) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /testdata/SourceDirTest.java: -------------------------------------------------------------------------------- 1 | package go; 2 | 3 | public class SourceDirTest { 4 | public static void main(String[] args) { 5 | System.out.println("testSourceDirInclusion PASS"); 6 | } 7 | } --------------------------------------------------------------------------------