pax_global_header00006660000000000000000000000064121127750560014520gustar00rootroot0000000000000052 comment=a426605edbafbdada722f0c4da442acde59f7499 libnative-platform-java-0.3~rc2/000077500000000000000000000000001211277505600167055ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/.gitignore000066400000000000000000000000461211277505600206750ustar00rootroot00000000000000*.iml *.ipr *.iws .gradle /build /out libnative-platform-java-0.3~rc2/LICENSE000066400000000000000000000261361211277505600177220ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. libnative-platform-java-0.3~rc2/build.gradle000077500000000000000000000207401211277505600211720ustar00rootroot00000000000000apply plugin: 'groovy' apply plugin: 'cpp' allprojects { apply plugin: 'java' apply plugin: 'idea' apply plugin: 'maven' repositories { mavenCentral() maven { url "http://repo.gradle.org/gradle/libs-releases-local" } } dependencies { testCompile 'org.spockframework:spock-core:0.6-groovy-1.8' } group = 'net.rubygrapefruit' version = '0.3-rc-2' sourceCompatibility = 1.5 targetCompatibility = 1.5 tasks.withType(Upload) { repositories { mavenDeployer { if (project.hasProperty('release')) { repository(url: uri("https://gradle.artifactoryonline.com/gradle/libs-releases-local")) { authentication(userName: artifactoryUserName, password: artifactoryPassword) } } else { repository(url: uri("$rootProject.buildDir/repo")) } } } } } dependencies { testCompile 'org.codehaus.groovy:groovy:1.8.7' } def nativeHeadersDir = file("$buildDir/nativeHeaders") task nativeHeaders { def outputFile = file("$nativeHeadersDir/native.h") inputs.files sourceSets.main.output outputs.file outputFile doLast { outputFile.parentFile.mkdirs() exec { executable org.gradle.internal.jvm.Jvm.current().getExecutable('javah') args '-o', outputFile args '-classpath', sourceSets.main.output.classesDir args 'net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions' args 'net.rubygrapefruit.platform.internal.jni.PosixFileFunctions' args 'net.rubygrapefruit.platform.internal.jni.PosixFileSystemFunctions' args 'net.rubygrapefruit.platform.internal.jni.PosixProcessFunctions' args 'net.rubygrapefruit.platform.internal.jni.PosixTerminalFunctions' args 'net.rubygrapefruit.platform.internal.jni.TerminfoFunctions' args 'net.rubygrapefruit.platform.internal.jni.WindowsConsoleFunctions' args 'net.rubygrapefruit.platform.internal.jni.WindowsHandleFunctions' } } } cpp { sourceSets { main { source.exclude 'curses.cpp' } curses { source.srcDirs = ['src/main/cpp'] source.include 'curses.cpp' source.include 'generic.cpp' source.include 'generic_posix.cpp' } } } def variants = [:] libraries { if (org.gradle.internal.os.OperatingSystem.current().macOsX) { all { spec { includes(files('/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/')) args("-arch", "x86_64", "-arch", "i386") } } universal { sourceSets << cpp.sourceSets.main spec { baseName = 'native-platform-osx-universal' args("-o", outputFile) } } cursesUniversal { sourceSets << cpp.sourceSets.curses spec { baseName = 'native-platform-curses-osx-universal' args("-lcurses") args("-o", outputFile) } } variants['osx-universal'] = [universal, cursesUniversal] } else if (org.gradle.internal.os.OperatingSystem.current().windows) { all { spec { includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include")) includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include/win32")) args("/DWIN32") } } def out = new ByteArrayOutputStream() exec { commandLine "cl.exe", "/?" errorOutput = out standardOutput = new ByteArrayOutputStream() } def header = out.toString().readLines().head() if (header.endsWith("for 80x86") || header.endsWith("for x86")) { i386 { sourceSets << cpp.sourceSets.main spec { baseName = 'native-platform-windows-i386' } } variants['windows-i386'] = [i386] } else if (header.endsWith("for x64")) { amd64 { sourceSets << cpp.sourceSets.main spec { baseName = 'native-platform-windows-amd64' } } variants['windows-amd64'] = [amd64] } else { throw new RuntimeException("Cannot determine compiler's target architecture") } } else if (org.gradle.internal.os.OperatingSystem.current().linux) { all { spec { includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include")) includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include/linux")) } } if (System.getProperty('os.arch') == 'i386' || project.hasProperty('multiarch')) { i386 { sourceSets << cpp.sourceSets.main spec { baseName = 'native-platform-linux-i386' args("-m32") } } cursesI386 { sourceSets << cpp.sourceSets.curses spec { baseName = 'native-platform-curses-linux-i386' args("-m32", "-lcurses") } } variants['linux-i386'] = [i386, cursesI386] } if (System.getProperty('os.arch') == 'amd64' || project.hasProperty('multiarch')) { amd64 { sourceSets << cpp.sourceSets.main spec { baseName = 'native-platform-linux-amd64' args("-m64") } } cursesAmd64 { sourceSets << cpp.sourceSets.curses spec { baseName = 'native-platform-curses-linux-amd64' args("-m64", "-lcurses") } } variants['linux-amd64'] = [amd64, cursesAmd64] } } else { baseName = "native-platform-solaris" main { sourceSets << cpp.sourceSets.main sourceSets << cpp.sourceSets.curses spec { includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include")) includes(files("${org.gradle.internal.jvm.Jvm.current().javaHome}/include/solaris")) args("-DSOLARIS", "-lcurses") } } variants['solaris'] = [main] } all { spec { includes(files(nativeHeadersDir, 'src/main/headers')) } def task = tasks["compile${spec.binary.name.capitalize()}"] task.dependsOn nativeHeaders test.dependsOn spec } } configurations { jni } def deployer = uploadJni.repositories.mavenDeployer variants.each { variant, libs -> def variantName = GUtil.toCamelCase(variant) def nativeJar = task("nativeJar${variantName}", type: Jar) { from libs.collect { tasks["compile${it.name.capitalize()}"] } baseName = "native-platform-$variant" } artifacts { jni nativeJar runtime nativeJar } def jniPom = deployer.addFilter(variant) { artifact, file -> return file == nativeJar.archivePath } jniPom.groupId = project.group jniPom.artifactId = nativeJar.baseName jniPom.version = project.version jniPom.scopeMappings.mappings.clear() } javadoc { exclude '**/internal/**' } task sourceZip(type: Zip) { from sourceSets.main.allSource classifier = 'sources' extension = 'jar' } task javadocZip(type: Zip) { from javadoc classifier = 'javadoc' extension = 'jar' } artifacts { archives sourceZip archives javadocZip } def mainPom = uploadArchives.repositories.mavenDeployer.pom mainPom.groupId = project.group mainPom.artifactId = jar.baseName mainPom.version = project.version mainPom.scopeMappings.mappings.clear() mainPom.withXml { provider -> def node = provider.asNode() def deps = node.appendNode('dependencies') ['osx-universal', 'linux-amd64', 'linux-i386', 'windows-amd64', 'windows-i386'].each { platform -> def dep = deps.appendNode('dependency') dep.appendNode('groupId', project.group) dep.appendNode('artifactId', "native-platform-${platform}") dep.appendNode('version', project.version) } } task wrapper(type: Wrapper) { gradleVersion = "1.3-20120907220018+0000" } libnative-platform-java-0.3~rc2/gradlew000077500000000000000000000117201211277505600202610ustar00rootroot00000000000000#!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" APP_HOME="`pwd -P`" cd "$SAVED" CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" libnative-platform-java-0.3~rc2/gradlew.bat000066400000000000000000000045441211277505600210310ustar00rootroot00000000000000@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega libnative-platform-java-0.3~rc2/readme.md000077500000000000000000000166051211277505600204770ustar00rootroot00000000000000 # Native-platform: Java bindings for various native APIs A collection of cross-platform Java APIs for various native APIs. Supports OS X, Linux, Solaris and Windows. These APIs support Java 5 and later. Some of these APIs overlap with APIs available in later Java versions. ## Available bindings ### System information * Get kernel name and version. * Get machine architecture. ### Processes * Get the PID of the current process. * Get and set the process working directory. * Get and set the process environment variables. ### Terminal and console These bindings work for both the UNIX terminal and the Windows console: * Determine if stdout/stderr are attached to a terminal. * Query the terminal size. * Switch between bold and normal mode on the terminal. * Change foreground color on the terminal. * Move terminal cursor up, down, left, right, start of line. * Clear to end of line. ### File systems * Get and set UNIX file mode. * Create and read symbolic links. * List the available file systems on the machine * Query file system mount point. * Query file system type. * Query file system device name. * Query whether a file system is local or remote. ## Supported platforms Currently ported to OS X, Linux and Windows. Support for Solaris and FreeBSD is a work in progress. Tested on: * OS X 10.7.4, 10.8 (x86_64), 10.6.7 (i386) * Ubunutu 12.04 (amd64), 8.04.4 (i386, amd64) * Windows 7 (x64), XP (x86) * Solaris 11 (x86) ## Using Include `native-platform.jar` and `native-platform-${os}-${arch}.jar` in your classpath. From Gradle, you can do this: repositories { maven { url "http://repo.gradle.org/gradle/libs-releases-local" } } dependencies { compile "net.rubygrapefruit:native-platform:0.3" } You can also download [here](http://repo.gradle.org/gradle/libs-releases-local/net/rubygrapefruit/) Some sample code to use the terminal: import net.rubygrapefruit.platform.Native; import net.rubygrapefruit.platform.Terminals; import net.rubygrapefruit.platform.Terminal; import static net.rubygrapefruit.platform.Terminals.Output.*; Terminals terminals = Native.get(Terminals.class); // check if terminal terminals.isTerminal(Stdout); // use terminal Terminal stdout = terminals.getTerminal(Stdout); stdout.bold(); System.out.println("bold text"); ## Changes ### 0.3 * Get and set process working directory. * Get and set process environment variables. * Launch processes. * Fixed character set issue on Linux and Mac OS X. * Fixes to work with 64-bit OpenJDK 7 on Mac OS X. Thanks to Rene Gr�schke. ### 0.2 * Fixes to make native library extraction multi-process safe. * Fixes to windows terminal detection and reset. ### 0.1 * Initial release. # Development ## Building You will need to use the Gradle wrapper. Just run `gradlew` in the root directory. ### Ubuntu The g++ compiler is required to build the native library. You will need the `g++` package for this. Usually this is already installed. You need to install the `libncurses5-dev` package to pick up the ncurses header files. Also worth installing the `ncurses-doc` package too. #### 64-bit machines with multi-arch support Where multi-arch support is available (e.g. recent Ubuntu releases), you can build the i386 and amd64 versions of the library on the same machine. You need to install the `gcc-multilib` and `g++-multilib` packages to pick up i386 support. You need to install the `lib32ncurses5-dev` package to pick up the ncurses i386 version. To build, include `-Pmultiarch` on the command-line. ### Windows You need to install Visual studio, and build from a Visual studio command prompt. ### OS X The g++ compiler is required to build the native library. You will need to install the XCode tools for this. ### Solaris For Solaris 11, you need to install the `development/gcc-45` and `system/header` packages. ## Running Run `gradle installApp` to install the test application into `test-app/build/install/native-platform-test`. Or `gradle distZip` to create an application distribtion in `test-app/build/distributions/native-platform-test-$version.zip`. You can run `$INSTALL_DIR/bin/native-platform-test` to run the test application. # Releasing 1. Check the version number in `build.gradle`. 2. Create a tag and push. 3. Build each variant: 1. Checkout tag. 2. `./gradlew clean :test :uploadJni -Prelease -PartifactoryUserName=<> -PartifactoryPassword=<>` * OS X universal * Linux i386, using Ubunutu 8.04 * Linux amd64, using Ubunutu 8.04 * Windows x86, using VC++ 2010 * Windows x64 4. Build Java library and test app: 1. Checkout tag. 2. `./gradlew clean :test :uploadArchives testApp:uploadArchives -Prelease -PartifactoryUserName=<> -PartifactoryPassword=<>` 5. Checkout master 6. Increment version number in `build.gradle` and this readme. ## Testing * Test on IBM JVM. * Test on Java 5, 6, 7. * Test on Windows 7, Windows XP ## TODO ### Fixes * Posix: allow terminal to be detected when ncurses cannot be loaded * Windows: fix detection of shared drive under VMWare fusion and Windows XP * Windows: restore std handles after launching child process * Linux: detect remote filesystems. * Solaris: fix unicode file name handling. * Solaris: fail for unsupported architecture. * Solaris: build 32 bit and 64 bit libraries. * Freebsd: finish port. * Freebsd: fail for unsupported architecture. * Freebsd: build 32 bit and 64 bit libraries. ### Improvements * Use wchar_to_java() for windows system and file system info. * Test network file systems on Mac, Linux, Windows * Test mount points on Windows * Cache class, method and field lookups * Change readLink() implementation so that it does not need to NULL terminate the encoded content * Don't use NewStringUTF() anywhere * Use iconv() to convert from C char string to UTF-16 when converting from C char string to Java String. * Support for cygwin terminal * Use TERM=xtermc instead of TERM=xterm on Solaris. * Add diagnostics for terminal. * Version each native interface separately. * String names for errno values. * Split into multiple projects. * Convert to c. * Use fully decomposed form for unicode file names on hfs+ filesystems. * Extend FileSystem to deal with removable media. * Add a method to Terminal that returns a PrintStream that can be used to write to the terminal, regardless of what System.out/System.err point to. * Add a Terminal implementation that uses ANSI control codes. Use this on UNIX platforms when TERM != 'dumb' and libncurses cannot be loaded. * Add a method to Terminal that indicates whether the cursor wraps to the next line when a character is written to the rightmost character position. * Check for null parameters. ### Ideas * Expose platform-specific HTTP proxy configuration. Query registry on windows to determine IE settings. * Expose native named semaphores, mutexes and condition variables (CreateMutex, CreateSemaphore, CreateEvent, semget, sem_open, etc). * Expose information about network interfaces. * Fire events when filesystems or network interfaces change in some way. * Fire events when terminal size changes. * Fire events when files change. * Expose system keystores and authentication services. * Expose a mechanism for generating a temporary directory. libnative-platform-java-0.3~rc2/settings.gradle000066400000000000000000000001701211277505600217230ustar00rootroot00000000000000rootProject.name = 'native-platform' include 'testApp' project(':testApp').projectDir = new File(rootDir, 'test-app') libnative-platform-java-0.3~rc2/src/000077500000000000000000000000001211277505600174745ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/000077500000000000000000000000001211277505600204205ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/cpp/000077500000000000000000000000001211277505600212025ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/cpp/curses.cpp000066400000000000000000000164511211277505600232210ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Curses functions */ #ifndef WIN32 #include "native.h" #include "generic.h" #include #include #include #include #define NORMAL_TEXT 0 #define BRIGHT_TEXT 1 #define FOREGROUND_COLOR 2 #define CURSOR_UP 3 #define CURSOR_DOWN 4 #define CURSOR_LEFT 5 #define CURSOR_RIGHT 6 #define CURSOR_START_LINE 7 #define CLEAR_END_OF_LINE 8 #ifdef SOLARIS #define TERMINAL_CHAR_TYPE char #else #define TERMINAL_CHAR_TYPE int #endif int current_terminal = -1; const char* terminal_capabilities[9]; int write_to_terminal(TERMINAL_CHAR_TYPE ch) { write(current_terminal, &ch, 1); } const char* getcap(const char* capability) { return tgetstr((char*)capability, NULL); } void write_capability(JNIEnv *env, const char* capability, jobject result) { if (capability == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } if (tputs((char*)capability, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } void write_param_capability(JNIEnv *env, const char* capability, int count, jobject result) { if (capability == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } capability = tparm((char*)capability, count, 0, 0, 0, 0, 0, 0, 0, 0); if (capability == NULL) { mark_failed_with_message(env, "could not format terminal capability string", result); return; } if (tputs((char*)capability, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_getVersion(JNIEnv *env, jclass target) { return NATIVE_VERSION; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_initTerminal(JNIEnv *env, jclass target, jint output, jobject capabilities, jobject result) { if (!isatty(output+1)) { mark_failed_with_message(env, "not a terminal", result); return; } if (current_terminal < 0) { char* termType = getenv("TERM"); if (termType == NULL) { mark_failed_with_message(env, "$TERM not set", result); return; } int retval = tgetent(NULL, termType); if (retval != 1) { mark_failed_with_message(env, "could not get termcap entry", result); return; } jclass destClass = env->GetObjectClass(capabilities); jfieldID field = env->GetFieldID(destClass, "terminalName", "Ljava/lang/String;"); jstring jtermType = char_to_java(env, termType, result); env->SetObjectField(capabilities, field, jtermType); // Text attributes terminal_capabilities[NORMAL_TEXT] = getcap("me"); terminal_capabilities[BRIGHT_TEXT] = getcap("md"); field = env->GetFieldID(destClass, "textAttributes", "Z"); env->SetBooleanField(capabilities, field, terminal_capabilities[NORMAL_TEXT] != NULL && terminal_capabilities[BRIGHT_TEXT] != NULL); // Colors terminal_capabilities[FOREGROUND_COLOR] = getcap("AF"); field = env->GetFieldID(destClass, "colors", "Z"); env->SetBooleanField(capabilities, field, terminal_capabilities[FOREGROUND_COLOR] != NULL); // Cursor motion terminal_capabilities[CURSOR_UP] = getcap("up"); terminal_capabilities[CURSOR_DOWN] = getcap("do"); terminal_capabilities[CURSOR_LEFT] = getcap("le"); terminal_capabilities[CURSOR_RIGHT] = getcap("nd"); terminal_capabilities[CURSOR_START_LINE] = getcap("cr"); terminal_capabilities[CLEAR_END_OF_LINE] = getcap("ce"); field = env->GetFieldID(destClass, "cursorMotion", "Z"); env->SetBooleanField(capabilities, field, terminal_capabilities[CURSOR_UP] != NULL && terminal_capabilities[CURSOR_DOWN] != NULL && terminal_capabilities[CURSOR_RIGHT] != NULL && terminal_capabilities[CURSOR_LEFT] != NULL && terminal_capabilities[CURSOR_START_LINE] != NULL && terminal_capabilities[CLEAR_END_OF_LINE] != NULL); } current_terminal = output + 1; if (terminal_capabilities[NORMAL_TEXT] != NULL) { write_capability(env, terminal_capabilities[NORMAL_TEXT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_bold(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[BRIGHT_TEXT], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_reset(JNIEnv *env, jclass target, jobject result) { if (terminal_capabilities[NORMAL_TEXT] != NULL) { write_capability(env, terminal_capabilities[NORMAL_TEXT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_foreground(JNIEnv *env, jclass target, jint color, jobject result) { write_param_capability(env, terminal_capabilities[FOREGROUND_COLOR], color, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_up(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_UP], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_down(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_DOWN], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_left(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_LEFT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_right(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_RIGHT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_startLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[CURSOR_START_LINE], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_clearToEndOfLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[CLEAR_END_OF_LINE], result); } #endif libnative-platform-java-0.3~rc2/src/main/cpp/generic.cpp000077500000000000000000000030071211277505600233250ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Generic cross-platform functions. */ #include "native.h" #include "generic.h" void mark_failed_with_message(JNIEnv *env, const char* message, jobject result) { mark_failed_with_code(env, message, 0, NULL, result); } void mark_failed_with_code(JNIEnv *env, const char* message, int error_code, const char* error_code_message, jobject result) { jclass destClass = env->GetObjectClass(result); jmethodID method = env->GetMethodID(destClass, "failed", "(Ljava/lang/String;ILjava/lang/String;)V"); jstring message_str = env->NewStringUTF(message); jstring error_code_str = error_code_message == NULL ? NULL : env->NewStringUTF(error_code_message); env->CallVoidMethod(result, method, message_str, error_code, error_code_str); } JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_NativeLibraryFunctions_getVersion(JNIEnv *env, jclass target) { return NATIVE_VERSION; } libnative-platform-java-0.3~rc2/src/main/cpp/generic_posix.cpp000066400000000000000000000050371211277505600245510ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * POSIX platform functions. */ #ifndef WIN32 #include "native.h" #include "generic.h" #include #include #include #include void mark_failed_with_errno(JNIEnv *env, const char* message, jobject result) { const char * errno_message = NULL; switch(errno) { case ENOENT: errno_message = "ENOENT"; break; } mark_failed_with_code(env, message, errno, errno_message, result); } char* java_to_char(JNIEnv *env, jstring string, jobject result) { size_t stringLen = env->GetStringLength(string); wchar_t* wideString = (wchar_t*)malloc(sizeof(wchar_t) * (stringLen+1)); const jchar* javaString = env->GetStringChars(string, NULL); for (size_t i = 0; i < stringLen; i++) { wideString[i] = javaString[i]; } wideString[stringLen] = L'\0'; env->ReleaseStringChars(string, javaString); size_t bytes = wcstombs(NULL, wideString, 0); if (bytes < 0) { mark_failed_with_message(env, "could not convert string to current locale", result); free(wideString); return NULL; } char* chars = (char*)malloc(bytes + 1); wcstombs(chars, wideString, bytes+1); free(wideString); return chars; } jstring char_to_java(JNIEnv* env, const char* chars, jobject result) { size_t bytes = strlen(chars); wchar_t* wideString = (wchar_t*)malloc(sizeof(wchar_t) * (bytes+1)); if (mbstowcs(wideString, chars, bytes+1) < 0) { mark_failed_with_message(env, "could not convert string from current locale", result); free(wideString); return NULL; } size_t stringLen = wcslen(wideString); jchar* javaString = (jchar*)malloc(sizeof(jchar) * stringLen); for (int i =0; i < stringLen; i++) { javaString[i] = (jchar)wideString[i]; } jstring string = env->NewString(javaString, stringLen); free(wideString); free(javaString); return string; } #endif libnative-platform-java-0.3~rc2/src/main/cpp/linux.cpp000066400000000000000000000033731211277505600230530ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Linux specific functions. */ #ifdef __linux__ #include "native.h" #include "generic.h" #include #include /* * File system functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) { FILE *fp = setmntent(MOUNTED, "r"); if (fp == NULL) { mark_failed_with_errno(env, "could not open mount file", result); return; } char buf[1024]; struct mntent mount_info; jclass info_class = env->GetObjectClass(info); jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V"); while (getmntent_r(fp, &mount_info, buf, sizeof(buf)) != NULL) { jstring mount_point = char_to_java(env, mount_info.mnt_dir, result); jstring file_system_type = char_to_java(env, mount_info.mnt_type, result); jstring device_name = char_to_java(env, mount_info.mnt_fsname, result); env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, JNI_FALSE); } endmntent(fp); } #endif libnative-platform-java-0.3~rc2/src/main/cpp/osx.cpp000066400000000000000000000040601211277505600225170ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * OS X specific functions. */ #ifdef __APPLE__ #include "native.h" #include "generic.h" #include #include #include #include /* * File system functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) { int fs_count = getfsstat(NULL, 0, MNT_NOWAIT); if (fs_count < 0) { mark_failed_with_errno(env, "could not stat file systems", result); return; } size_t len = fs_count * sizeof(struct statfs); struct statfs* buf = (struct statfs*)malloc(len); if (getfsstat(buf, len, MNT_NOWAIT) < 0 ) { mark_failed_with_errno(env, "could not stat file systems", result); free(buf); return; } jclass info_class = env->GetObjectClass(info); jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V"); for (int i = 0; i < fs_count; i++) { jstring mount_point = char_to_java(env, buf[i].f_mntonname, result); jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result); jstring device_name = char_to_java(env, buf[i].f_mntfromname, result); jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0; env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote); } free(buf); } #endif libnative-platform-java-0.3~rc2/src/main/cpp/posix.cpp000077500000000000000000000170511211277505600230570ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * POSIX platform functions. */ #ifndef WIN32 #include "native.h" #include "generic.h" #include #include #include #include #include #include #include JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_NativeLibraryFunctions_getSystemInfo(JNIEnv *env, jclass target, jobject info, jobject result) { jclass infoClass = env->GetObjectClass(info); struct utsname machine_info; if (uname(&machine_info) != 0) { mark_failed_with_errno(env, "could not query machine details", result); return; } jfieldID osNameField = env->GetFieldID(infoClass, "osName", "Ljava/lang/String;"); env->SetObjectField(info, osNameField, char_to_java(env, machine_info.sysname, result)); jfieldID osVersionField = env->GetFieldID(infoClass, "osVersion", "Ljava/lang/String;"); env->SetObjectField(info, osVersionField, char_to_java(env, machine_info.release, result)); jfieldID machineArchitectureField = env->GetFieldID(infoClass, "machineArchitecture", "Ljava/lang/String;"); env->SetObjectField(info, machineArchitectureField, char_to_java(env, machine_info.machine, result)); } /* * File functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_chmod(JNIEnv *env, jclass target, jstring path, jint mode, jobject result) { char* pathStr = java_to_char(env, path, result); if (pathStr == NULL) { return; } int retval = chmod(pathStr, mode); free(pathStr); if (retval != 0) { mark_failed_with_errno(env, "could not chmod file", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_stat(JNIEnv *env, jclass target, jstring path, jobject dest, jobject result) { struct stat fileInfo; char* pathStr = java_to_char(env, path, result); if (pathStr == NULL) { return; } int retval = stat(pathStr, &fileInfo); free(pathStr); if (retval != 0) { mark_failed_with_errno(env, "could not stat file", result); return; } jclass destClass = env->GetObjectClass(dest); jfieldID modeField = env->GetFieldID(destClass, "mode", "I"); env->SetIntField(dest, modeField, 0777 & fileInfo.st_mode); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_symlink(JNIEnv *env, jclass target, jstring path, jstring contents, jobject result) { char* pathStr = java_to_char(env, path, result); if (pathStr == NULL) { return; } char* contentStr = java_to_char(env, contents, result); if (contentStr == NULL) { free(pathStr); return; } int retval = symlink(contentStr, pathStr); free(contentStr); free(pathStr); if (retval != 0) { mark_failed_with_errno(env, "could not symlink", result); } } JNIEXPORT jstring JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_readlink(JNIEnv *env, jclass target, jstring path, jobject result) { struct stat link_info; char* pathStr = java_to_char(env, path, result); if (pathStr == NULL) { return NULL; } int retval = lstat(pathStr, &link_info); if (retval != 0) { free(pathStr); mark_failed_with_errno(env, "could not lstat file", result); return NULL; } char* contents = (char*)malloc(link_info.st_size + 1); if (contents == NULL) { free(pathStr); mark_failed_with_message(env, "could not create array", result); return NULL; } retval = readlink(pathStr, contents, link_info.st_size); free(pathStr); if (retval < 0) { free(contents); mark_failed_with_errno(env, "could not readlink", result); return NULL; } contents[link_info.st_size] = 0; jstring contents_str = char_to_java(env, contents, result); free(contents); return contents_str; } /* * Process functions */ JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) { return getpid(); } JNIEXPORT jstring JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getWorkingDirectory(JNIEnv *env, jclass target, jobject result) { char* path = getcwd(NULL, 0); if (path == NULL) { mark_failed_with_errno(env, "could not getcwd()", result); return NULL; } jstring dir = char_to_java(env, path, result); free(path); return dir; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setWorkingDirectory(JNIEnv *env, jclass target, jstring dir, jobject result) { char* path = java_to_char(env, dir, result); if (path == NULL) { return; } if (chdir(path) != 0) { mark_failed_with_errno(env, "could not setcwd()", result); } free(path); } JNIEXPORT jstring JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jobject result) { char* varStr = java_to_char(env, var, result); char* valueStr = getenv(varStr); free(varStr); if (valueStr == NULL) { return NULL; } return char_to_java(env, valueStr, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jstring value, jobject result) { char* varStr = java_to_char(env, var, result); if (value == NULL) { if (setenv(varStr, "", 1) != 0) { mark_failed_with_errno(env, "could not putenv()", result); } } else { char* valueStr = java_to_char(env, value, result); if (setenv(varStr, valueStr, 1) != 0) { mark_failed_with_errno(env, "could not putenv()", result); } free(valueStr); } free(varStr); } /* * Terminal functions */ JNIEXPORT jboolean JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_isatty(JNIEnv *env, jclass target, jint output) { struct stat fileInfo; int result; switch (output) { case 0: case 1: return isatty(output+1) ? JNI_TRUE : JNI_FALSE; default: return JNI_FALSE; } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_getTerminalSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) { struct winsize screen_size; int retval = ioctl(output+1, TIOCGWINSZ, &screen_size); if (retval != 0) { mark_failed_with_errno(env, "could not fetch terminal size", result); return; } jclass dimensionClass = env->GetObjectClass(dimension); jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I"); env->SetIntField(dimension, widthField, screen_size.ws_col); jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I"); env->SetIntField(dimension, heightField, screen_size.ws_row); } #endif libnative-platform-java-0.3~rc2/src/main/cpp/win.cpp000077500000000000000000000456171211277505600225230ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef WIN32 #include "native.h" #include "generic.h" #include #include /* * Marks the given result as failed, using the current value of GetLastError() */ void mark_failed_with_errno(JNIEnv *env, const char* message, jobject result) { mark_failed_with_code(env, message, GetLastError(), NULL, result); } jstring wchar_to_java(JNIEnv* env, const wchar_t* chars, size_t len, jobject result) { if (sizeof(wchar_t) != 2) { mark_failed_with_message(env, "unexpected size of wchar_t", result); return NULL; } return env->NewString((jchar*)chars, len); } wchar_t* java_to_wchar(JNIEnv *env, jstring string, jobject result) { jsize len = env->GetStringLength(string); wchar_t* str = (wchar_t*)malloc(sizeof(wchar_t) * (len+1)); env->GetStringRegion(string, 0, len, (jchar*)str); str[len] = L'\0'; return str; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_NativeLibraryFunctions_getSystemInfo(JNIEnv *env, jclass target, jobject info, jobject result) { jclass infoClass = env->GetObjectClass(info); OSVERSIONINFOEX versionInfo; versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (GetVersionEx((OSVERSIONINFO*)&versionInfo) == 0) { mark_failed_with_errno(env, "could not get version info", result); return; } SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); jstring arch = NULL; if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { arch = env->NewStringUTF("amd64"); } else if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) { arch = env->NewStringUTF("x86"); } else if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { arch = env->NewStringUTF("ia64"); } else { arch = env->NewStringUTF("unknown"); } jmethodID method = env->GetMethodID(infoClass, "windows", "(IIIZLjava/lang/String;)V"); env->CallVoidMethod(info, method, versionInfo.dwMajorVersion, versionInfo.dwMinorVersion, versionInfo.dwBuildNumber, versionInfo.wProductType == VER_NT_WORKSTATION, arch); } /* * Process functions */ JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) { return GetCurrentProcessId(); } JNIEXPORT jstring JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getWorkingDirectory(JNIEnv *env, jclass target, jobject result) { DWORD size = GetCurrentDirectoryW(0, NULL); if (size == 0) { mark_failed_with_errno(env, "could not determine length of working directory path", result); return NULL; } size = size+1; // Needs to include null character wchar_t* path = (wchar_t*)malloc(sizeof(wchar_t) * size); DWORD copied = GetCurrentDirectoryW(size, path); if (copied == 0) { free(path); mark_failed_with_errno(env, "could get working directory path", result); return NULL; } jstring dirName = wchar_to_java(env, path, copied, result); free(path); return dirName; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setWorkingDirectory(JNIEnv *env, jclass target, jstring dir, jobject result) { wchar_t* dirPath = java_to_wchar(env, dir, result); if (dirPath == NULL) { return; } BOOL ok = SetCurrentDirectoryW(dirPath); free(dirPath); if (!ok) { mark_failed_with_errno(env, "could not set current directory", result); return; } } JNIEXPORT jstring JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jobject result) { wchar_t* varStr = java_to_wchar(env, var, result); DWORD len = GetEnvironmentVariableW(varStr, NULL, 0); if (len == 0) { if (GetLastError() != ERROR_ENVVAR_NOT_FOUND) { mark_failed_with_errno(env, "could not determine length of environment variable", result); } free(varStr); return NULL; } wchar_t* valueStr = (wchar_t*)malloc(sizeof(wchar_t) * len); DWORD copied = GetEnvironmentVariableW(varStr, valueStr, len); if (copied == 0) { if (len > 1) { // If the value is empty, then copied will be 0 mark_failed_with_errno(env, "could not get environment variable", result); } free(varStr); free(valueStr); return NULL; } free(varStr); jstring value = wchar_to_java(env, valueStr, copied, result); free(valueStr); return value; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jstring value, jobject result) { wchar_t* varStr = java_to_wchar(env, var, result); wchar_t* valueStr = value == NULL ? NULL : java_to_wchar(env, value, result); BOOL ok = SetEnvironmentVariableW(varStr, valueStr); free(varStr); if (valueStr != NULL) { free(valueStr); } if (!ok && GetLastError() != ERROR_ENVVAR_NOT_FOUND) { mark_failed_with_errno(env, "could not set environment var", result); return; } } /* * File system functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) { wchar_t* volumeName = (wchar_t*)malloc(sizeof(wchar_t) * (MAX_PATH+1)); jclass info_class = env->GetObjectClass(info); jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V"); HANDLE handle = FindFirstVolumeW(volumeName, MAX_PATH+1); if (handle == INVALID_HANDLE_VALUE) { free(volumeName); mark_failed_with_errno(env, "could not find first volume", result); return; } wchar_t* deviceName = (wchar_t*)malloc(sizeof(wchar_t) * (MAX_PATH+1)); wchar_t* pathNames = (wchar_t*)malloc(sizeof(wchar_t) * (MAX_PATH+1)); wchar_t* fsName = (wchar_t*)malloc(sizeof(wchar_t) * (MAX_PATH+1)); while(true) { // Chop off the trailing '\' size_t len = wcslen(volumeName); if (len < 5) { mark_failed_with_message(env, "volume name is too short", result); break; } volumeName[len-1] = L'\0'; if (QueryDosDeviceW(&volumeName[4], deviceName, MAX_PATH+1) == 0) { mark_failed_with_errno(env, "could not query dos device", result); break; } volumeName[len-1] = L'\\'; DWORD used; if (GetVolumePathNamesForVolumeNameW(volumeName, pathNames, MAX_PATH+1, &used) == 0) { // TODO - try again if the buffer is too small mark_failed_with_errno(env, "could not query volume paths", result); break; } wchar_t* cur = pathNames; if (cur[0] != L'\0') { // TODO - use GetDriveTypeW() to determine if removable, remote, etc if(GetVolumeInformationW(cur, NULL, 0, NULL, NULL, NULL, fsName, MAX_PATH+1) == 0) { if (GetLastError() != ERROR_NOT_READY) { mark_failed_with_errno(env, "could not query volume information", result); break; } wcscpy(fsName, L"unknown"); } for (;cur[0] != L'\0'; cur += wcslen(cur) + 1) { env->CallVoidMethod(info, method, wchar_to_java(env, cur, wcslen(cur), result), wchar_to_java(env, fsName, wcslen(fsName), result), wchar_to_java(env, deviceName, wcslen(deviceName), result), JNI_FALSE); } } if (FindNextVolumeW(handle, volumeName, MAX_PATH) == 0) { if (GetLastError() != ERROR_NO_MORE_FILES) { mark_failed_with_errno(env, "could find next volume", result); } break; } } free(volumeName); free(deviceName); free(pathNames); free(fsName); FindVolumeClose(handle); } /* * Console functions */ HANDLE getHandle(JNIEnv *env, int output, jobject result) { HANDLE handle = output == 0 ? GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE); if (handle == INVALID_HANDLE_VALUE) { mark_failed_with_errno(env, "could not get console handle", result); return NULL; } return handle; } JNIEXPORT jboolean JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_isConsole(JNIEnv *env, jclass target, jint output, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; HANDLE handle = getHandle(env, output, result); if (handle == NULL) { return JNI_FALSE; } if (!GetConsoleScreenBufferInfo(handle, &console_info)) { if (GetLastError() == ERROR_INVALID_HANDLE) { return JNI_FALSE; } mark_failed_with_errno(env, "could not get console buffer", result); return JNI_FALSE; } return JNI_TRUE; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_getConsoleSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; HANDLE handle = getHandle(env, output, result); if (handle == NULL) { mark_failed_with_message(env, "not a console", result); return; } if (!GetConsoleScreenBufferInfo(handle, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } jclass dimensionClass = env->GetObjectClass(dimension); jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I"); env->SetIntField(dimension, widthField, console_info.srWindow.Right - console_info.srWindow.Left + 1); jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I"); env->SetIntField(dimension, heightField, console_info.srWindow.Bottom - console_info.srWindow.Top + 1); } HANDLE current_console = NULL; WORD original_attributes = 0; WORD current_attributes = 0; JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_initConsole(JNIEnv *env, jclass target, jint output, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; HANDLE handle = getHandle(env, output, result); if (handle == NULL) { mark_failed_with_message(env, "not a terminal", result); return; } if (!GetConsoleScreenBufferInfo(handle, &console_info)) { if (GetLastError() == ERROR_INVALID_HANDLE) { mark_failed_with_message(env, "not a console", result); } else { mark_failed_with_errno(env, "could not get console buffer", result); } return; } current_console = handle; original_attributes = console_info.wAttributes; current_attributes = original_attributes; Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_normal(env, target, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_bold(JNIEnv *env, jclass target, jobject result) { current_attributes |= FOREGROUND_INTENSITY; if (!SetConsoleTextAttribute(current_console, current_attributes)) { mark_failed_with_errno(env, "could not set text attributes", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_normal(JNIEnv *env, jclass target, jobject result) { current_attributes &= ~FOREGROUND_INTENSITY; SetConsoleTextAttribute(current_console, current_attributes); if (!SetConsoleTextAttribute(current_console, current_attributes)) { mark_failed_with_errno(env, "could not set text attributes", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_reset(JNIEnv *env, jclass target, jobject result) { current_attributes = original_attributes; if (!SetConsoleTextAttribute(current_console, current_attributes)) { mark_failed_with_errno(env, "could not set text attributes", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_foreground(JNIEnv *env, jclass target, jint color, jobject result) { current_attributes &= ~ (FOREGROUND_BLUE|FOREGROUND_RED|FOREGROUND_GREEN); switch (color) { case 0: break; case 1: current_attributes |= FOREGROUND_RED; break; case 2: current_attributes |= FOREGROUND_GREEN; break; case 3: current_attributes |= FOREGROUND_RED|FOREGROUND_GREEN; break; case 4: current_attributes |= FOREGROUND_BLUE; break; case 5: current_attributes |= FOREGROUND_RED|FOREGROUND_BLUE; break; case 6: current_attributes |= FOREGROUND_GREEN|FOREGROUND_BLUE; break; default: current_attributes |= FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; break; } SetConsoleTextAttribute(current_console, current_attributes); if (!SetConsoleTextAttribute(current_console, current_attributes)) { mark_failed_with_errno(env, "could not set text attributes", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_left(JNIEnv *env, jclass target, jint count, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } console_info.dwCursorPosition.X -= count; if (!SetConsoleCursorPosition(current_console, console_info.dwCursorPosition)) { mark_failed_with_errno(env, "could not set cursor position", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_right(JNIEnv *env, jclass target, jint count, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } console_info.dwCursorPosition.X += count; if (!SetConsoleCursorPosition(current_console, console_info.dwCursorPosition)) { mark_failed_with_errno(env, "could not set cursor position", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_up(JNIEnv *env, jclass target, jint count, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } console_info.dwCursorPosition.Y -= count; if (!SetConsoleCursorPosition(current_console, console_info.dwCursorPosition)) { mark_failed_with_errno(env, "could not set cursor position", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_down(JNIEnv *env, jclass target, jint count, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } console_info.dwCursorPosition.Y += count; if (!SetConsoleCursorPosition(current_console, console_info.dwCursorPosition)) { mark_failed_with_errno(env, "could not set cursor position", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_startLine(JNIEnv *env, jclass target, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } console_info.dwCursorPosition.X = 0; if (!SetConsoleCursorPosition(current_console, console_info.dwCursorPosition)) { mark_failed_with_errno(env, "could not set cursor position", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsConsoleFunctions_clearToEndOfLine(JNIEnv *env, jclass target, jobject result) { CONSOLE_SCREEN_BUFFER_INFO console_info; if (!GetConsoleScreenBufferInfo(current_console, &console_info)) { mark_failed_with_errno(env, "could not get console buffer", result); return; } DWORD count; if (!FillConsoleOutputCharacterW(current_console, L' ', console_info.dwSize.X - console_info.dwCursorPosition.X, console_info.dwCursorPosition, &count)) { mark_failed_with_errno(env, "could not clear console", result); } } void uninheritStream(JNIEnv *env, DWORD stdInputHandle, jobject result) { HANDLE streamHandle = GetStdHandle(stdInputHandle); if (streamHandle == NULL) { // We're not attached to a stdio (eg Desktop application). Ignore. return; } if (streamHandle == INVALID_HANDLE_VALUE) { mark_failed_with_errno(env, "could not get std handle", result); return; } boolean ok = SetHandleInformation(streamHandle, HANDLE_FLAG_INHERIT, 0); if (!ok) { mark_failed_with_errno(env, "could not change std handle", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsHandleFunctions_markStandardHandlesUninheritable(JNIEnv *env, jclass target, jobject result) { uninheritStream(env, STD_INPUT_HANDLE, result); uninheritStream(env, STD_OUTPUT_HANDLE, result); uninheritStream(env, STD_ERROR_HANDLE, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsHandleFunctions_restoreStandardHandles(JNIEnv *env, jclass target, jobject result) { } #endif libnative-platform-java-0.3~rc2/src/main/headers/000077500000000000000000000000001211277505600220335ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/headers/generic.h000077500000000000000000000043421211277505600236260ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __INCLUDE_GENERIC_H__ #define __INCLUDE_GENERIC_H__ #include #ifdef __cplusplus extern "C" { #endif #define NATIVE_VERSION 15 /* * Marks the given result as failed, using the given error message */ extern void mark_failed_with_message(JNIEnv *env, const char* message, jobject result); /* * Marks the given result as failed, using the given error message and the current value of errno/GetLastError() */ extern void mark_failed_with_errno(JNIEnv *env, const char* message, jobject result); /* * Marks the given result as failed, using the given error message and error code */ extern void mark_failed_with_code(JNIEnv *env, const char* message, int error_code, const char* error_code_message, jobject result); /* * Converts the given Java string to a NULL terminated wchar_str. Should call free() when finished. * * Returns NULL on failure. */ extern wchar_t* java_to_wchar(JNIEnv *env, jstring string, jobject result); /* * Converts the given wchar_t string to a Java string. * * Returns NULL on failure. */ extern jstring wchar_to_java(JNIEnv* env, const wchar_t* chars, size_t len, jobject result); /* * Converts the given Java string to a NULL terminated char string. Should call free() when finished. * * Returns NULL on failure. */ extern char* java_to_char(JNIEnv *env, jstring string, jobject result); /* * Converts the given NULL terminated char string to a Java string. * * Returns NULL on failure. */ extern jstring char_to_java(JNIEnv* env, const char* chars, jobject result); #ifdef __cplusplus } #endif #endif libnative-platform-java-0.3~rc2/src/main/java/000077500000000000000000000000001211277505600213415ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/000077500000000000000000000000001211277505600221275ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/000077500000000000000000000000001211277505600252015ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/000077500000000000000000000000001211277505600270255ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/FileSystem.java000066400000000000000000000025111211277505600317530ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.io.File; /** * Information about a file system. This is a snapshot view and does not change. */ @ThreadSafe public interface FileSystem { /** * Returns the root directory of this file system. */ @ThreadSafe File getMountPoint(); /** * Returns the operating system specific name for the type of this file system. */ @ThreadSafe String getFileSystemType(); /** * Returns true if this file system is a remote file system, or false if local. */ @ThreadSafe boolean isRemote(); /** * Returns the operating system specific name for this file system. */ @ThreadSafe String getDeviceName(); } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/FileSystems.java000066400000000000000000000021141211277505600321350ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.util.List; /** * Provides access to the file systems of the current machine. */ @ThreadSafe public interface FileSystems extends NativeIntegration { /** * Returns the set of all file systems for the current machine. * * @return The set of file systems. Never returns null. * @throws NativeException On failure. */ @ThreadSafe List getFileSystems() throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/Native.java000077500000000000000000000076461211277505600311360ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import net.rubygrapefruit.platform.internal.NativeLibraryLoader; import net.rubygrapefruit.platform.internal.NativeLibraryLocator; import net.rubygrapefruit.platform.internal.Platform; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Provides access to the native integrations. Use {@link #get(Class)} to load a particular integration. */ @ThreadSafe public class Native { private static NativeLibraryLoader loader; private static final Map, Object> integrations = new HashMap, Object>(); private Native() { } /** * Initialises the native integration, if not already initialized. * * @param extractDir The directory to extract native resources into. May be null, in which case a default is * selected. * * @throws NativeIntegrationUnavailableException When native integration is not available on the current machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe static public void init(File extractDir) throws NativeIntegrationUnavailableException, NativeException { synchronized (Native.class) { if (loader == null) { Platform platform = Platform.current(); try { loader = new NativeLibraryLoader(platform, new NativeLibraryLocator(extractDir)); loader.load(platform.getLibraryName()); int nativeVersion = NativeLibraryFunctions.getVersion(); if (nativeVersion != NativeLibraryFunctions.VERSION) { throw new NativeException(String.format("Unexpected native library version loaded. Expected %s, was %s.", NativeLibraryFunctions.VERSION, nativeVersion)); } } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException("Failed to initialise native integration.", t); } } } } /** * Locates a native integration of the given type. * * @return The native integration. Never returns null. * @throws NativeIntegrationUnavailableException When the given native integration is not available on the current * machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe public static T get(Class type) throws NativeIntegrationUnavailableException, NativeException { init(null); synchronized (Native.class) { Object instance = integrations.get(type); if (instance == null) { try { instance = Platform.current().get(type, loader); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException(String.format("Failed to load native integration %s.", type.getSimpleName()), t); } integrations.put(type, instance); } return type.cast(instance); } } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/NativeException.java000066400000000000000000000016071211277505600330010ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; public class NativeException extends RuntimeException { public NativeException(String message, Throwable throwable) { super(message, throwable); } public NativeException(String message) { super(message); } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/NativeIntegration.java000066400000000000000000000014011211277505600333160ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * A marker interface that represents a native integration. */ public interface NativeIntegration { } NativeIntegrationUnavailableException.java000066400000000000000000000016331211277505600372710ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * Thrown when a given integration is not available for the current machine. */ public class NativeIntegrationUnavailableException extends NativeException { public NativeIntegrationUnavailableException(String message) { super(message); } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/PosixFile.java000066400000000000000000000030151211277505600315710ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.io.File; /** * Functions to query and modify a file's POSIX meta-data. */ @ThreadSafe public interface PosixFile extends NativeIntegration { /** * Sets the mode for the given file. * * @throws NativeException On failure. */ @ThreadSafe void setMode(File path, int perms) throws NativeException; /** * Gets the mode for the given file. * * @throws NativeException On failure. */ @ThreadSafe int getMode(File path) throws NativeException; /** * Creates a symbolic link. * * @throws NativeException On failure. */ @ThreadSafe void symlink(File link, String contents) throws NativeException; /** * Reads the contents of a symbolic link. * * @throws NativeException On failure. */ @ThreadSafe String readLink(File link) throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/Process.java000077500000000000000000000043521211277505600313150ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.io.File; /** * Functions to query and modify a process' state. */ @ThreadSafe public interface Process extends NativeIntegration { /** * Returns the process identifier. * * @throws NativeException On failure. */ @ThreadSafe int getProcessId() throws NativeException; /** * Returns the process' current working directory. * * @throws NativeException On failure. */ @ThreadSafe File getWorkingDirectory() throws NativeException; /** * Sets the process' working directory. * * @throws NativeException On failure. */ @ThreadSafe void setWorkingDirectory(File directory) throws NativeException; /** * Get the value of an environment variable. * * @return The value or null if no such environment variable. Also returns null for an environment variable whose * value is an empty string. * @throws NativeException On failure. */ @ThreadSafe String getEnvironmentVariable(String name) throws NativeException; /** * Sets the value of an environment variable. * * @param value the new value. Use null or an empty string to remove the environment variable. Note that on some * platforms it is not possible to remove the environment variable safely. On such platforms, the value is set to an * empty string instead. * @throws NativeException On failure. */ @ThreadSafe void setEnvironmentVariable(String name, String value) throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/ProcessLauncher.java000066400000000000000000000023351211277505600327730ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.lang.Process; /** * Used to start processes, taking care of some platform-specific issues when launching processes concurrently or * launching processes that will run in the background. */ @ThreadSafe public interface ProcessLauncher extends NativeIntegration { /** * Starts a process from the given settings. * * @param processBuilder The process settings. * @return the process * @throws NativeException On failure to start the process. */ @ThreadSafe Process start(ProcessBuilder processBuilder) throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/SystemInfo.java000066400000000000000000000023431211277505600317720ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * Provides access to some system information. This is a snapshot view and does not change. */ @ThreadSafe public interface SystemInfo extends NativeIntegration { /** * Returns the name of the kernel for the current operating system. */ @ThreadSafe String getKernelName(); /** * Returns the version of the kernel for the current operating system. */ @ThreadSafe String getKernelVersion(); /** * Returns the machine architecture, as reported by the operating system. */ @ThreadSafe String getMachineArchitecture(); } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/Terminal.java000066400000000000000000000103371211277505600314470ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * Allows the terminal/console to be manipulated. * *

On UNIX based platforms, this provides access to the terminal. On Windows platforms, this provides access to the * console. *

*/ @ThreadSafe public interface Terminal { /** * Basic colors supported by a terminal. */ enum Color { // Don't change the order of these. They are in ANSI order Black, Red, Green, Yellow, Blue, Magenta, Cyan, White } /** * Returns true if this terminal supports setting text attributes, such as bold. */ @ThreadSafe boolean supportsTextAttributes(); /** * Returns true if this terminal supports setting output colors. */ @ThreadSafe boolean supportsColor(); /** * Returns true if this terminal supports moving the cursor. */ @ThreadSafe boolean supportsCursorMotion(); /** * Returns the size of the terminal. Supported by all terminals. * * @return The current terminal size. Never returns null. * @throws NativeException On failure. */ @ThreadSafe TerminalSize getTerminalSize() throws NativeException; /** * Sets the terminal foreground color, if supported. Does nothing if this terminal does not support setting the * foreground color. * * @throws NativeException On failure. */ @ThreadSafe Terminal foreground(Color color) throws NativeException; /** * Switches the terminal to bold mode, if supported. Does nothing if this terminal does not support bold mode. * * @throws NativeException On failure. */ @ThreadSafe Terminal bold() throws NativeException; /** * Switches the terminal to normal mode. Supported by all terminals. * * @throws NativeException On failure. */ @ThreadSafe Terminal normal() throws NativeException; /** * Switches the terminal to normal mode and restores default colors. Supported by all terminals. * * @throws NativeException On failure. */ @ThreadSafe Terminal reset() throws NativeException; /** * Moves the cursor the given number of characters to the left. * * @throws NativeException On failure, or if this terminal does not support cursor motion. */ @ThreadSafe Terminal cursorLeft(int count) throws NativeException; /** * Moves the cursor the given number of characters to the right. * * @throws NativeException On failure, or if this terminal does not support cursor motion. */ @ThreadSafe Terminal cursorRight(int count) throws NativeException; /** * Moves the cursor the given number of characters up. * * @throws NativeException On failure, or if this terminal does not support cursor motion. */ @ThreadSafe Terminal cursorUp(int count) throws NativeException; /** * Moves the cursor the given number of characters down. * * @throws NativeException On failure, or if this terminal does not support cursor motion. */ @ThreadSafe Terminal cursorDown(int count) throws NativeException; /** * Moves the cursor to the start of the current line. * * @throws NativeException On failure, or if this terminal does not support cursor motion. */ @ThreadSafe Terminal cursorStartOfLine() throws NativeException; /** * Clears characters from the cursor position to the end of the current line. * * @throws NativeException On failure, or if this terminal does not support clearing. */ @ThreadSafe Terminal clearToEndOfLine() throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/TerminalSize.java000066400000000000000000000020061211277505600322740ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * The size of a terminal. This is a snapshot view and does not change. */ @ThreadSafe public interface TerminalSize { /** * Returns the number of character columns in the terminal. */ @ThreadSafe public int getCols(); /** * Returns the number of character rows in the terminal. */ @ThreadSafe public int getRows(); } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/Terminals.java000066400000000000000000000027321211277505600316320ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; /** * Provides access to the terminal/console. * *

On UNIX based platforms, this provides access to the terminal. On Windows platforms, this provides access to the * console. *

*/ @ThreadSafe public interface Terminals extends NativeIntegration { /** * System outputs. */ enum Output {Stdout, Stderr} /** * Returns true if the given output is attached to a terminal. * * @throws NativeException On failure. */ @ThreadSafe boolean isTerminal(Output output) throws NativeException; /** * Returns the terminal attached to the given output. * * @return The terminal. Never returns null. * @throws NativeException When the output is not attached to a terminal. */ @ThreadSafe Terminal getTerminal(Output output) throws NativeException; } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/ThreadSafe.java000066400000000000000000000015711211277505600317020ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Indicates that the given class or method is thread safe. */ @Target({ElementType.TYPE, ElementType.METHOD}) public @interface ThreadSafe { } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/000077500000000000000000000000001211277505600306415ustar00rootroot00000000000000AbstractTerminal.java000077500000000000000000000015071211277505600346720ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.Terminal; public abstract class AbstractTerminal implements Terminal { protected abstract void init(); } AbstractTerminals.java000066400000000000000000000034001211277505600350440ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.Terminal; import net.rubygrapefruit.platform.Terminals; public abstract class AbstractTerminals implements Terminals { private final Object lock = new Object(); private Output currentlyOpen; private AbstractTerminal current; public Terminal getTerminal(Output output) { synchronized (lock) { if (currentlyOpen != null && currentlyOpen != output) { throw new UnsupportedOperationException("Currently only one output can be used as a terminal."); } if (current == null) { final AbstractTerminal terminal = createTerminal(output); terminal.init(); Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { terminal.reset(); } }); currentlyOpen = output; current = terminal; } return current; } } protected abstract AbstractTerminal createTerminal(Output output); } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/AnsiTerminal.java000066400000000000000000000135161211277505600341000ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Terminal; import net.rubygrapefruit.platform.TerminalSize; import net.rubygrapefruit.platform.Terminals; import java.io.IOException; import java.io.OutputStream; public class AnsiTerminal extends AbstractTerminal { private static final byte[] BOLD = "\u001b[1m".getBytes(); private static final byte[] RESET = "\u001b[0m".getBytes(); private static final byte[] START_OF_LINE = "\u001b[0E".getBytes(); private static final byte[] CLEAR_TO_END_OF_LINE = "\u001b[0K".getBytes(); private final Terminals.Output output; private final OutputStream outputStream; private Color foreground; public AnsiTerminal(OutputStream outputStream, Terminals.Output output) { this.outputStream = outputStream; this.output = output; } @Override public String toString() { return String.format("ANSI terminal on %s", getOutputDisplay()); } private String getOutputDisplay() { return output.toString().toLowerCase(); } @Override protected void init() { } public boolean supportsTextAttributes() { return true; } public boolean supportsColor() { return true; } public boolean supportsCursorMotion() { return true; } public TerminalSize getTerminalSize() throws NativeException { return new MutableTerminalSize(); } public Terminal foreground(Color color) throws NativeException { try { String esc = String.format("\u001b[%sm", 30 + color.ordinal()); outputStream.write(esc.getBytes()); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not set foreground color on %s.", getOutputDisplay()), e); } foreground = color; return this; } public Terminal bold() throws NativeException { try { outputStream.write(BOLD); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not switch to bold output on %s.", getOutputDisplay()), e); } return this; } public Terminal normal() throws NativeException { try { outputStream.write(RESET); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not switch to normal output on %s.", getOutputDisplay()), e); } if (foreground != null) { foreground(foreground); } return this; } public Terminal reset() throws NativeException { try { outputStream.write(RESET); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not reset output on %s.", getOutputDisplay()), e); } return this; } public Terminal cursorLeft(int count) throws NativeException { try { String esc = String.format("\u001b[%sD", count); outputStream.write(esc.getBytes()); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not move cursor on %s.", getOutputDisplay()), e); } return this; } public Terminal cursorRight(int count) throws NativeException { try { String esc = String.format("\u001b[%sC", count); outputStream.write(esc.getBytes()); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not move cursor on %s.", getOutputDisplay()), e); } return this; } public Terminal cursorUp(int count) throws NativeException { try { String esc = String.format("\u001b[%sA", count); outputStream.write(esc.getBytes()); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not move cursor on %s.", getOutputDisplay()), e); } return this; } public Terminal cursorDown(int count) throws NativeException { try { String esc = String.format("\u001b[%sB", count); outputStream.write(esc.getBytes()); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not move cursor on %s.", getOutputDisplay()), e); } return this; } public Terminal cursorStartOfLine() throws NativeException { try { outputStream.write(START_OF_LINE); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not move cursor on %s.", getOutputDisplay()), e); } return this; } public Terminal clearToEndOfLine() throws NativeException { try { outputStream.write(CLEAR_TO_END_OF_LINE); outputStream.flush(); } catch (IOException e) { throw new NativeException(String.format("Could not clear to end of line on %s.", getOutputDisplay()), e); } return this; } } DefaultFileSystem.java000066400000000000000000000027201211277505600350170ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.FileSystem; import java.io.File; public class DefaultFileSystem implements FileSystem { private final File mountPoint; private final String fileSystemType; private final String deviceName; private final boolean remote; public DefaultFileSystem(File mountPoint, String fileSystemType, String deviceName, boolean remote) { this.mountPoint = mountPoint; this.fileSystemType = fileSystemType; this.deviceName = deviceName; this.remote = remote; } public String getDeviceName() { return deviceName; } public File getMountPoint() { return mountPoint; } public String getFileSystemType() { return fileSystemType; } public boolean isRemote() { return remote; } } DefaultPosixFile.java000077500000000000000000000045601211277505600346440ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.PosixFile; import net.rubygrapefruit.platform.internal.jni.PosixFileFunctions; import java.io.File; public class DefaultPosixFile implements PosixFile { public void setMode(File file, int perms) { FunctionResult result = new FunctionResult(); PosixFileFunctions.chmod(file.getPath(), perms, result); if (result.isFailed()) { throw new NativeException(String.format("Could not set UNIX mode on %s: %s", file, result.getMessage())); } } public int getMode(File file) { FunctionResult result = new FunctionResult(); FileStat stat = new FileStat(); PosixFileFunctions.stat(file.getPath(), stat, result); if (result.isFailed()) { throw new NativeException(String.format("Could not get UNIX mode on %s: %s", file, result.getMessage())); } return stat.mode; } @Override public String readLink(File link) throws NativeException { FunctionResult result = new FunctionResult(); String contents = PosixFileFunctions.readlink(link.getPath(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not read symlink %s: %s", link, result.getMessage())); } return contents; } @Override public void symlink(File link, String contents) throws NativeException { FunctionResult result = new FunctionResult(); PosixFileFunctions.symlink(link.getPath(), contents, result); if (result.isFailed()) { throw new NativeException(String.format("Could not create symlink %s: %s", link, result.getMessage())); } } } DefaultProcess.java000077500000000000000000000054121211277505600343550ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Process; import net.rubygrapefruit.platform.internal.jni.PosixProcessFunctions; import java.io.File; public class DefaultProcess implements Process { public int getProcessId() throws NativeException { return PosixProcessFunctions.getPid(); } public File getWorkingDirectory() throws NativeException { FunctionResult result = new FunctionResult(); String dir = PosixProcessFunctions.getWorkingDirectory(result); if (result.isFailed()) { throw new NativeException(String.format("Could not get process working directory: %s", result.getMessage())); } return new File(dir); } public void setWorkingDirectory(File directory) throws NativeException { FunctionResult result = new FunctionResult(); PosixProcessFunctions.setWorkingDirectory(directory.getAbsolutePath(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not set process working directory to '%s': %s", directory.getAbsoluteFile(), result.getMessage())); } } public String getEnvironmentVariable(String name) throws NativeException { FunctionResult result = new FunctionResult(); String value = PosixProcessFunctions.getEnvironmentVariable(name, result); if (result.isFailed()) { throw new NativeException(String.format("Could not get the value of environment variable '%s': %s", name, result.getMessage())); } return value; } public void setEnvironmentVariable(String name, String value) throws NativeException { FunctionResult result = new FunctionResult(); PosixProcessFunctions.setEnvironmentVariable(name, value, result); if (result.isFailed()) { throw new NativeException(String.format("Could not set the value of environment variable '%s': %s", name, result.getMessage())); } } } DefaultProcessLauncher.java000077500000000000000000000021671211277505600360430ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.ProcessLauncher; public class DefaultProcessLauncher implements ProcessLauncher { public Process start(ProcessBuilder processBuilder) throws NativeException { try { return processBuilder.start(); } catch (Exception e) { throw new NativeException(String.format("Could not start '%s'", processBuilder.command().get(0)), e); } } } DefaultSystemInfo.java000066400000000000000000000031301211277505600350270ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.SystemInfo; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; public class DefaultSystemInfo implements SystemInfo { MutableSystemInfo systemInfo = new MutableSystemInfo(); public DefaultSystemInfo() { FunctionResult result = new FunctionResult(); NativeLibraryFunctions.getSystemInfo(systemInfo, result); if (result.isFailed()) { throw new NativeException(String.format("Could not fetch system information: %s", result.getMessage())); } } @Override public String getKernelName() { return systemInfo.getKernelName(); } @Override public String getKernelVersion() { return systemInfo.getKernelVersion(); } @Override public String getMachineArchitecture() { return systemInfo.getMachineArchitecture(); } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/FileStat.java000066400000000000000000000013161211277505600332200ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; public class FileStat { public int mode; } FileSystemList.java000066400000000000000000000021311211277505600343420ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.FileSystem; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSystemList { public final List fileSystems = new ArrayList(); public void add(String mountPoint, String fileSystemName, String deviceName, boolean remote) { fileSystems.add(new DefaultFileSystem(new File(mountPoint), fileSystemName, deviceName, remote)); } } FunctionResult.java000066400000000000000000000026331211277505600344150ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; public class FunctionResult { String message; int errno; private String errorCodeDescription; void failed(String message, int errno, String errorCodeDescription) { this.message = message; this.errno = errno; this.errorCodeDescription = errorCodeDescription; } void failed(String message) { this.message = message; } public boolean isFailed() { return message != null; } public String getMessage() { if (errorCodeDescription != null) { return String.format("%s (%s errno %d)", message, errorCodeDescription, errno); } if (errno != 0) { return String.format("%s (errno %d)", message, errno); } return message; } } MutableSystemInfo.java000077500000000000000000000045761211277505600350560ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.SystemInfo; public class MutableSystemInfo implements SystemInfo { // Fields set from native code public String osName; public String osVersion; public String machineArchitecture; public String getKernelName() { return osName; } public String getKernelVersion() { return osVersion; } public String getMachineArchitecture() { return machineArchitecture; } // Called from native code void windows(int major, int minor, int build, boolean workstation, String arch) { osName = toWindowsVersionName(major, minor, workstation); osVersion = String.format("%s.%s (build %s)", major, minor, build); machineArchitecture = arch; } private String toWindowsVersionName(int major, int minor, boolean workstation) { switch (major) { case 5: switch (minor) { case 0: return "Windows 2000"; case 1: return "Windows XP"; case 2: return "Windows Server 2003"; } break; case 6: switch (minor) { case 0: return workstation ? "Windows Vista" : "Windows Server 2008"; case 1: return workstation ? "Windows 7" : "Windows Server 2008 R2"; case 2: return workstation ? "Windows 8" : "Windows Server 2012"; } break; } return "Windows (unknown version)"; } } MutableTerminalSize.java000066400000000000000000000016301211277505600353450ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.TerminalSize; public class MutableTerminalSize implements TerminalSize { int rows; int cols; public int getCols() { return cols; } public int getRows() { return rows; } } NativeLibraryLoader.java000077500000000000000000000037601211277505600353400ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.NativeIntegrationUnavailableException; import java.io.File; import java.util.HashSet; import java.util.Set; public class NativeLibraryLoader { private final Set loaded = new HashSet(); private final Platform platform; private final NativeLibraryLocator nativeLibraryLocator; public NativeLibraryLoader(Platform platform, NativeLibraryLocator nativeLibraryLocator) { this.platform = platform; this.nativeLibraryLocator = nativeLibraryLocator; } public void load(String libraryFileName) { if (loaded.contains(libraryFileName)) { return; } try { File libFile = nativeLibraryLocator.find(libraryFileName); if (libFile == null) { throw new NativeIntegrationUnavailableException(String.format("Native library is not available for %s.", platform)); } System.load(libFile.getCanonicalPath()); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException(String.format("Failed to load native library '%s' for %s.", libraryFileName, platform), t); } loaded.add(libraryFileName); } } NativeLibraryLocator.java000077500000000000000000000077571211277505600355470ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import java.io.*; import java.net.URL; import java.nio.channels.FileLock; public class NativeLibraryLocator { private final File extractDir; public NativeLibraryLocator(File extractDir) { this.extractDir = extractDir; } public File find(String libraryFileName) throws IOException { if (extractDir != null) { File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryFileName)); File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock"); lockFile.getParentFile().mkdirs(); lockFile.createNewFile(); RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw"); try { // Take exclusive lock on lock file FileLock lock = lockFileAccess.getChannel().lock(); if (lockFile.length() > 0 && lockFileAccess.readBoolean()) { // Library has been extracted return libFile; } URL resource = getClass().getClassLoader().getResource(libraryFileName); if (resource != null) { // Extract library and write marker to lock file libFile.getParentFile().mkdirs(); copy(resource, libFile); lockFileAccess.seek(0); lockFileAccess.writeBoolean(true); return libFile; } } finally { // Also releases lock lockFileAccess.close(); } } else { URL resource = getClass().getClassLoader().getResource(libraryFileName); if (resource != null) { File libFile; File libDir = File.createTempFile("native-platform", "dir"); libDir.delete(); libDir.mkdirs(); libFile = new File(libDir, libraryFileName); libFile.deleteOnExit(); copy(resource, libFile); return libFile; } } File libFile = new File("build/binaries/" + libraryFileName); if (libFile.isFile()) { return libFile; } return null; } private static void copy(URL source, File dest) { try { InputStream inputStream = source.openStream(); try { OutputStream outputStream = new FileOutputStream(dest); try { byte[] buffer = new byte[4096]; while (true) { int nread = inputStream.read(buffer); if (nread < 0) { break; } outputStream.write(buffer, 0, nread); } } finally { outputStream.close(); } } finally { inputStream.close(); } } catch (IOException e) { throw new NativeException(String.format("Could not extract native JNI library."), e); } } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/Platform.java000077500000000000000000000200461211277505600332750ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.*; import net.rubygrapefruit.platform.Process; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import net.rubygrapefruit.platform.internal.jni.TerminfoFunctions; public abstract class Platform { private static Platform platform; public static Platform current() { synchronized (Platform.class) { if (platform == null) { String osName = getOperatingSystem().toLowerCase(); String arch = getArchitecture(); if (osName.contains("windows")) { if (arch.equals("x86")) { platform = new Window32Bit(); } else if (arch.equals("amd64")) { platform = new Window64Bit(); } } else if (osName.contains("linux")) { if (arch.equals("amd64")) { platform = new Linux64Bit(); } else if (arch.equals("i386") || arch.equals("x86")) { platform = new Linux32Bit(); } } else if (osName.contains("os x")) { if (arch.equals("i386") || arch.equals("x86_64") || arch.equals("amd64")) { platform = new OsX(); } } else if (osName.contains("sunos")) { platform = new Solaris(); } else { platform = new Unsupported(); } } return platform; } } public boolean isWindows() { return false; } @Override public String toString() { return String.format("%s %s", getOperatingSystem(), getArchitecture()); } public T get(Class type, NativeLibraryLoader nativeLibraryLoader) { throw new NativeIntegrationUnavailableException(String.format("Native integration %s is not supported for %s.", type.getSimpleName(), toString())); } public String getLibraryName() { throw new NativeIntegrationUnavailableException(String.format("Native integration is not available for %s.", toString())); } private static String getOperatingSystem() { return System.getProperty("os.name"); } private static String getArchitecture() { return System.getProperty("os.arch"); } private abstract static class Windows extends Platform { @Override public boolean isWindows() { return true; } @Override public T get(Class type, NativeLibraryLoader nativeLibraryLoader) { if (type.equals(Process.class)) { return type.cast(new WrapperProcess(new DefaultProcess(), true)); } if (type.equals(Terminals.class)) { return type.cast(new WindowsTerminals()); } if (type.equals(ProcessLauncher.class)) { return type.cast(new WrapperProcessLauncher(new WindowsProcessLauncher(new DefaultProcessLauncher()))); } if (type.equals(SystemInfo.class)) { return type.cast(new DefaultSystemInfo()); } if (type.equals(FileSystems.class)) { return type.cast(new PosixFileSystems()); } return super.get(type, nativeLibraryLoader); } } private static class Window32Bit extends Windows { @Override public String getLibraryName() { return "native-platform-windows-i386.dll"; } } private static class Window64Bit extends Windows { @Override public String getLibraryName() { return "native-platform-windows-amd64.dll"; } } private static abstract class Posix extends Platform { abstract String getCursesLibraryName(); @Override public T get(Class type, NativeLibraryLoader nativeLibraryLoader) { if (type.equals(PosixFile.class)) { return type.cast(new DefaultPosixFile()); } if (type.equals(Process.class)) { return type.cast(new WrapperProcess(new DefaultProcess(), false)); } if (type.equals(ProcessLauncher.class)) { return type.cast(new WrapperProcessLauncher(new DefaultProcessLauncher())); } if (type.equals(Terminals.class)) { nativeLibraryLoader.load(getCursesLibraryName()); int nativeVersion = TerminfoFunctions.getVersion(); if (nativeVersion != NativeLibraryFunctions.VERSION) { throw new NativeException(String.format("Unexpected native library version loaded. Expected %s, was %s.", nativeVersion, NativeLibraryFunctions.VERSION)); } return type.cast(new TerminfoTerminals()); } if (type.equals(SystemInfo.class)) { return type.cast(new DefaultSystemInfo()); } return super.get(type, nativeLibraryLoader); } } private abstract static class Unix extends Posix { } private abstract static class Linux extends Unix { @Override public T get(Class type, NativeLibraryLoader nativeLibraryLoader) { if (type.equals(FileSystems.class)) { return type.cast(new PosixFileSystems()); } return super.get(type, nativeLibraryLoader); } } private static class Linux32Bit extends Linux { @Override public String getLibraryName() { return "libnative-platform-linux-i386.so"; } @Override String getCursesLibraryName() { return "libnative-platform-curses-linux-i386.so"; } } private static class Linux64Bit extends Linux { @Override public String getLibraryName() { return "libnative-platform-linux-amd64.so"; } @Override String getCursesLibraryName() { return "libnative-platform-curses-linux-amd64.so"; } } private static class Solaris extends Unix { @Override public String getLibraryName() { return "libnative-platform-solaris.so"; } @Override String getCursesLibraryName() { return "libnative-platform-curses-solaris.so"; } } private static class OsX extends Posix { @Override public T get(Class type, NativeLibraryLoader nativeLibraryLoader) { if (type.equals(FileSystems.class)) { return type.cast(new PosixFileSystems()); } return super.get(type, nativeLibraryLoader); } @Override public String getLibraryName() { return "libnative-platform-osx-universal.dylib"; } @Override String getCursesLibraryName() { return "libnative-platform-curses-osx-universal.dylib"; } } private static class Unsupported extends Platform { } } PosixFileSystems.java000066400000000000000000000025751211277505600347300ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.FileSystem; import net.rubygrapefruit.platform.FileSystems; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.internal.jni.PosixFileSystemFunctions; import java.util.List; public class PosixFileSystems implements FileSystems { public List getFileSystems() { FunctionResult result = new FunctionResult(); FileSystemList fileSystems = new FileSystemList(); PosixFileSystemFunctions.listFileSystems(fileSystems, result); if (result.isFailed()) { throw new NativeException(String.format("Could not query file systems: %s", result.getMessage())); } return fileSystems.fileSystems; } } TerminalCapabilities.java000066400000000000000000000014501211277505600355120ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; public class TerminalCapabilities { String terminalName; boolean textAttributes; boolean colors; boolean cursorMotion; } TerminfoTerminal.java000077500000000000000000000141111211277505600347050ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Terminal; import net.rubygrapefruit.platform.TerminalSize; import net.rubygrapefruit.platform.Terminals; import net.rubygrapefruit.platform.internal.jni.PosixTerminalFunctions; import net.rubygrapefruit.platform.internal.jni.TerminfoFunctions; public class TerminfoTerminal extends AbstractTerminal { private final Terminals.Output output; private final TerminalCapabilities capabilities = new TerminalCapabilities(); private Color foreground; public TerminfoTerminal(Terminals.Output output) { this.output = output; } @Override public String toString() { return String.format("Curses terminal on %s", getOutputDisplay()); } private String getOutputDisplay() { return output.toString().toLowerCase(); } @Override protected void init() { FunctionResult result = new FunctionResult(); TerminfoFunctions.initTerminal(output.ordinal(), capabilities, result); if (result.isFailed()) { throw new NativeException(String.format("Could not open terminal for %s: %s", getOutputDisplay(), result.getMessage())); } } public TerminalSize getTerminalSize() { MutableTerminalSize terminalSize = new MutableTerminalSize(); FunctionResult result = new FunctionResult(); PosixTerminalFunctions.getTerminalSize(output.ordinal(), terminalSize, result); if (result.isFailed()) { throw new NativeException(String.format("Could not get terminal size for %s: %s", getOutputDisplay(), result.getMessage())); } return terminalSize; } public boolean supportsColor() { return capabilities.colors; } public boolean supportsCursorMotion() { return capabilities.cursorMotion; } public boolean supportsTextAttributes() { return capabilities.textAttributes; } public Terminal foreground(Color color) { if (!capabilities.colors) { return this; } FunctionResult result = new FunctionResult(); TerminfoFunctions.foreground(color.ordinal(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not switch foreground color for %s: %s", getOutputDisplay(), result.getMessage())); } foreground = color; return this; } public Terminal bold() { if (!capabilities.textAttributes) { return this; } FunctionResult result = new FunctionResult(); TerminfoFunctions.bold(result); if (result.isFailed()) { throw new NativeException(String.format("Could not switch to bold mode for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal normal() { reset(); if (foreground != null) { foreground(foreground); } return this; } public Terminal reset() { FunctionResult result = new FunctionResult(); TerminfoFunctions.reset(result); if (result.isFailed()) { throw new NativeException(String.format("Could not reset terminal for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorDown(int count) { FunctionResult result = new FunctionResult(); TerminfoFunctions.down(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor down for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorUp(int count) { FunctionResult result = new FunctionResult(); TerminfoFunctions.up(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor up for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorLeft(int count) { FunctionResult result = new FunctionResult(); TerminfoFunctions.left(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor left for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorRight(int count) { FunctionResult result = new FunctionResult(); TerminfoFunctions.right(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor right for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorStartOfLine() throws NativeException { FunctionResult result = new FunctionResult(); TerminfoFunctions.startLine(result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor to start of line for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal clearToEndOfLine() throws NativeException { FunctionResult result = new FunctionResult(); TerminfoFunctions.clearToEndOfLine(result); if (result.isFailed()) { throw new NativeException(String.format("Could not clear to end of line for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } } TerminfoTerminals.java000077500000000000000000000023351211277505600350750ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.Terminals; import net.rubygrapefruit.platform.internal.jni.PosixTerminalFunctions; import java.io.PrintStream; public class TerminfoTerminals extends AbstractTerminals { public boolean isTerminal(Output output) { return PosixTerminalFunctions.isatty(output.ordinal()); } @Override protected AbstractTerminal createTerminal(Output output) { PrintStream stream = output == Terminals.Output.Stdout ? System.out : System.err; return new WrapperTerminal(stream, new TerminfoTerminal(output)); } } WindowsProcessLauncher.java000077500000000000000000000022771211277505600361130ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internalpackage net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.ProcessLauncher; import net.rubygrapefruit.platform.internal.jni.WindowsHandleFunctions; public class WindowsProcessLauncher implements ProcessLauncher { private final ProcessLauncher launcher; public WindowsProcessLauncher(ProcessLauncher launcher) { this.launcher = launcher; } public Process start(ProcessBuilder processBuilder) throws NativeException { FunctionResult result = new FunctionResult(); WindowsHandleFunctions.markStandardHandlesUninheritable(result); if (result.isFailed()) { throw new NativeException(String.format("Could not start '%s': %s", processBuilder.command().get(0), result.getMessage())); } try { return launcher.start(processBuilder); } finally { WindowsHandleFunctions.restoreStandardHandles(result); if (result.isFailed()) { throw new NativeException(String.format("Could not restore process handles: %s", result.getMessage())); } } } } WindowsTerminal.java000077500000000000000000000137031211277505600345620ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Terminal; import net.rubygrapefruit.platform.Terminals; import net.rubygrapefruit.platform.TerminalSize; import net.rubygrapefruit.platform.internal.jni.WindowsConsoleFunctions; public class WindowsTerminal extends AbstractTerminal { private final Terminals.Output output; public WindowsTerminal(Terminals.Output output) { this.output = output; } @Override public String toString() { return String.format("Windows console on %s", getOutputDisplay()); } private String getOutputDisplay() { return output.toString().toLowerCase(); } @Override protected void init() { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.initConsole(output.ordinal(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not open console for %s: %s", getOutputDisplay(), result.getMessage())); } } public boolean supportsColor() { return true; } public boolean supportsTextAttributes() { return true; } public boolean supportsCursorMotion() { return true; } public TerminalSize getTerminalSize() { FunctionResult result = new FunctionResult(); MutableTerminalSize size = new MutableTerminalSize(); WindowsConsoleFunctions.getConsoleSize(output.ordinal(), size, result); if (result.isFailed()) { throw new NativeException(String.format("Could not determine console size for %s: %s", getOutputDisplay(), result.getMessage())); } return size; } public Terminal bold() { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.bold(result); if (result.isFailed()) { throw new NativeException(String.format("Could not switch console to bold mode for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal foreground(Color color) { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.foreground(color.ordinal(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not change console foreground color for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal normal() { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.normal(result); if (result.isFailed()) { throw new NativeException(String.format("Could not switch console to normal mode for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal reset() { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.reset(result); if (result.isFailed()) { throw new NativeException(String.format("Could not reset console for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorDown(int count) throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.down(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor down for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorUp(int count) throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.up(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor up for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorLeft(int count) throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.left(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor left for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorRight(int count) throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.right(count, result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor right for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal cursorStartOfLine() throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.startLine(result); if (result.isFailed()) { throw new NativeException(String.format("Could not move cursor to start of line for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } public Terminal clearToEndOfLine() throws NativeException { FunctionResult result = new FunctionResult(); WindowsConsoleFunctions.clearToEndOfLine(result); if (result.isFailed()) { throw new NativeException(String.format("Could clear to end of line for %s: %s", getOutputDisplay(), result.getMessage())); } return this; } } WindowsTerminals.java000077500000000000000000000030651211277505600347450ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Terminals; import net.rubygrapefruit.platform.internal.jni.WindowsConsoleFunctions; import java.io.PrintStream; public class WindowsTerminals extends AbstractTerminals { public boolean isTerminal(Output output) { FunctionResult result = new FunctionResult(); boolean console = WindowsConsoleFunctions.isConsole(output.ordinal(), result); if (result.isFailed()) { throw new NativeException(String.format("Could not determine if %s is a console: %s", output, result.getMessage())); } return console; } @Override protected AbstractTerminal createTerminal(Output output) { PrintStream stream = output == Terminals.Output.Stdout ? System.out : System.err; return new WrapperTerminal(stream, new WindowsTerminal(output)); } } WrapperProcess.java000077500000000000000000000105631211277505600344140ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Process; import net.rubygrapefruit.platform.ThreadSafe; import java.io.File; import java.lang.reflect.Field; import java.util.Map; /** * A {@link Process} implementation that wraps another to add thread-safety and to update the JVM's internal view of * various process properties. */ @ThreadSafe public class WrapperProcess implements Process { private final Process process; private final boolean windows; private final Object workingDirectoryLock = new Object(); private final Object environmentLock = new Object(); private Map environment; private Map windowsEnvironment; public WrapperProcess(Process process, boolean windows) { this.process = process; this.windows = windows; } @Override public String toString() { return process.toString(); } public int getProcessId() throws NativeException { return process.getProcessId(); } public File getWorkingDirectory() throws NativeException { synchronized (workingDirectoryLock) { return process.getWorkingDirectory(); } } public void setWorkingDirectory(File directory) throws NativeException { synchronized (workingDirectoryLock) { process.setWorkingDirectory(directory); System.setProperty("user.dir", directory.getAbsolutePath()); } } public String getEnvironmentVariable(String name) throws NativeException { synchronized (environmentLock) { String value = process.getEnvironmentVariable(name); return value == null || value.length() == 0 ? null : value; } } public void setEnvironmentVariable(String name, String value) throws NativeException { synchronized (environmentLock) { if (value == null || value.length() == 0) { process.setEnvironmentVariable(name, null); removeEnvInternal(name); } else { process.setEnvironmentVariable(name, value); setEnvInternal(name, value); } } } private void removeEnvInternal(String name) { getEnv().remove(name); if (windows) { getWindowsEnv().remove(name); } } private void setEnvInternal(String name, String value) { getEnv().put(name, value); if (windows) { getWindowsEnv().put(name, value); } } private Map getEnv() { if (environment == null) { try { Map theUnmodifiableEnvironment = System.getenv(); Class cu = theUnmodifiableEnvironment.getClass(); Field m = cu.getDeclaredField("m"); m.setAccessible(true); environment = (Map) m.get(theUnmodifiableEnvironment); } catch (Exception e) { throw new NativeException("Unable to get mutable environment variable map.", e); } } return environment; } private Map getWindowsEnv() { if (windowsEnvironment == null) { try { Class sc = Class.forName("java.lang.ProcessEnvironment"); Field caseinsensitive = sc.getDeclaredField("theCaseInsensitiveEnvironment"); caseinsensitive.setAccessible(true); windowsEnvironment = (Map) caseinsensitive.get(null); } catch (Exception e) { throw new NativeException("Unable to get mutable Windows environment variable map", e); } } return windowsEnvironment; } } WrapperProcessLauncher.java000077500000000000000000000026511211277505600360750ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.ProcessLauncher; import net.rubygrapefruit.platform.ThreadSafe; @ThreadSafe public class WrapperProcessLauncher implements ProcessLauncher { private final Object startLock = new Object(); private final ProcessLauncher launcher; public WrapperProcessLauncher(ProcessLauncher launcher) { this.launcher = launcher; } public Process start(ProcessBuilder processBuilder) throws NativeException { synchronized (startLock) { // Start a single process at a time, to avoid streams to child process being inherited by other // children before the parent can close them return launcher.start(processBuilder); } } } WrapperTerminal.java000066400000000000000000000072751211277505600345540ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal; import net.rubygrapefruit.platform.NativeException; import net.rubygrapefruit.platform.Terminal; import net.rubygrapefruit.platform.TerminalSize; import java.io.PrintStream; /** * A {@link Terminal} implementation that wraps another to add thread safety. */ public class WrapperTerminal extends AbstractTerminal { private final AbstractTerminal terminal; private final PrintStream stream; private final Object lock = new Object(); public WrapperTerminal(PrintStream stream, AbstractTerminal terminal) { this.stream = stream; this.terminal = terminal; } @Override protected void init() { stream.flush(); terminal.init(); } @Override public String toString() { return terminal.toString(); } public TerminalSize getTerminalSize() throws NativeException { return terminal.getTerminalSize(); } public boolean supportsColor() { return terminal.supportsColor(); } public boolean supportsCursorMotion() { return terminal.supportsCursorMotion(); } public boolean supportsTextAttributes() { return terminal.supportsTextAttributes(); } public Terminal normal() throws NativeException { stream.flush(); synchronized (lock) { terminal.normal(); } return this; } public Terminal bold() throws NativeException { stream.flush(); synchronized (lock) { terminal.bold(); } return this; } public Terminal reset() throws NativeException { stream.flush(); synchronized (lock) { terminal.reset(); } return this; } public Terminal foreground(Color color) throws NativeException { stream.flush(); synchronized (lock) { terminal.foreground(color); } return this; } public Terminal cursorLeft(int count) throws NativeException { stream.flush(); synchronized (lock) { terminal.cursorLeft(count); } return this; } public Terminal cursorRight(int count) throws NativeException { stream.flush(); synchronized (lock) { terminal.cursorRight(count); } return this; } public Terminal cursorUp(int count) throws NativeException { stream.flush(); synchronized (lock) { terminal.cursorUp(count); } return this; } public Terminal cursorDown(int count) throws NativeException { stream.flush(); synchronized (lock) { terminal.cursorDown(count); } return this; } public Terminal cursorStartOfLine() throws NativeException { stream.flush(); synchronized (lock) { terminal.cursorStartOfLine(); } return this; } public Terminal clearToEndOfLine() throws NativeException { stream.flush(); synchronized (lock) { terminal.clearToEndOfLine(); } return this; } } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/000077500000000000000000000000001211277505600314215ustar00rootroot00000000000000NativeLibraryFunctions.java000077500000000000000000000020341211277505600366530ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; import net.rubygrapefruit.platform.internal.MutableSystemInfo; public class NativeLibraryFunctions { public static final int VERSION = 15; public static native int getVersion(); public static native void getSystemInfo(MutableSystemInfo systemInfo, FunctionResult result); } PosixFileFunctions.java000077500000000000000000000022211211277505600360000ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FileStat; import net.rubygrapefruit.platform.internal.FunctionResult; public class PosixFileFunctions { public static native void chmod(String file, int perms, FunctionResult result); public static native void stat(String file, FileStat stat, FunctionResult result); public static native void symlink(String file, String content, FunctionResult result); public static native String readlink(String file, FunctionResult result); } PosixFileSystemFunctions.java000066400000000000000000000016501211277505600372070ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FileSystemList; import net.rubygrapefruit.platform.internal.FunctionResult; public class PosixFileSystemFunctions { public static native void listFileSystems(FileSystemList fileSystems, FunctionResult result); } PosixProcessFunctions.java000077500000000000000000000022651211277505600365470ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; public class PosixProcessFunctions { public static native int getPid(); public static native String getWorkingDirectory(FunctionResult result); public static native void setWorkingDirectory(String dir, FunctionResult result); public static native String getEnvironmentVariable(String var, FunctionResult result); public static native void setEnvironmentVariable(String var, String value, FunctionResult result); } PosixTerminalFunctions.java000077500000000000000000000020071211277505600366760ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; import net.rubygrapefruit.platform.internal.MutableTerminalSize; public class PosixTerminalFunctions { public static native boolean isatty(int filedes); public static native void getTerminalSize(int filedes, MutableTerminalSize size, FunctionResult result); } TerminfoFunctions.java000077500000000000000000000032531211277505600356670ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; import net.rubygrapefruit.platform.internal.TerminalCapabilities; public class TerminfoFunctions { public static native int getVersion(); /** * Sets up terminal info and switches output to normal mode. */ public static native void initTerminal(int filedes, TerminalCapabilities terminalCapabilities, FunctionResult result); public static native void bold(FunctionResult result); public static native void reset(FunctionResult result); public static native void foreground(int ansiColor, FunctionResult result); public static native void left(int count, FunctionResult result); public static native void right(int count, FunctionResult result); public static native void up(int count, FunctionResult result); public static native void down(int count, FunctionResult result); public static native void startLine(FunctionResult result); public static native void clearToEndOfLine(FunctionResult result); } WindowsConsoleFunctions.java000077500000000000000000000034631211277505600370640ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jni/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; import net.rubygrapefruit.platform.internal.MutableTerminalSize; public class WindowsConsoleFunctions { public static native boolean isConsole(int filedes, FunctionResult result); public static native void getConsoleSize(int filedes, MutableTerminalSize size, FunctionResult result); public static native void initConsole(int filedes, FunctionResult result); public static native void bold(FunctionResult result); public static native void normal(FunctionResult result); public static native void reset(FunctionResult result); public static native void foreground(int ansiColor, FunctionResult result); public static native void left(int count, FunctionResult result); public static native void right(int count, FunctionResult result); public static native void up(int count, FunctionResult result); public static native void down(int count, FunctionResult result); public static native void startLine(FunctionResult result); public static native void clearToEndOfLine(FunctionResult result); } WindowsHandleFunctions.java000077500000000000000000000005061211277505600366500ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/internal/jnipackage net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.internal.FunctionResult; public class WindowsHandleFunctions { public static native void markStandardHandlesUninheritable(FunctionResult result); public static native void restoreStandardHandles(FunctionResult result); } libnative-platform-java-0.3~rc2/src/main/java/net/rubygrapefruit/platform/package-info.java000066400000000000000000000014221211277505600322130ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The native integrations. Use {@link net.rubygrapefruit.platform.Native#get(Class)} to access a native integration. */ package net.rubygrapefruit.platform;libnative-platform-java-0.3~rc2/src/test/000077500000000000000000000000001211277505600204535ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/000077500000000000000000000000001211277505600220005ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/net/000077500000000000000000000000001211277505600225665ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/000077500000000000000000000000001211277505600256405ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/000077500000000000000000000000001211277505600274645ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/FileSystemsTest.groovy000077500000000000000000000022311211277505600340430ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.Specification class FileSystemsTest extends Specification { @Rule TemporaryFolder tmpDir final FileSystems fileSystems = Native.get(FileSystems.class) def "caches file systems instance"() { expect: Native.get(FileSystems.class) == fileSystems } def "can query filesystem details"() { expect: fileSystems.fileSystems.collect() { it.mountPoint }.containsAll(File.listRoots()) } } libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/PosixFileTest.groovy000077500000000000000000000074261211277505600335110ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import spock.lang.Specification import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.IgnoreIf import net.rubygrapefruit.platform.internal.Platform @IgnoreIf({Platform.current().windows}) class PosixFileTest extends Specification { @Rule TemporaryFolder tmpDir final PosixFile file = Native.get(PosixFile.class) def "caches file instance"() { expect: Native.get(PosixFile.class) == file } def "can set mode on a file"() { def testFile = tmpDir.newFile(fileName) when: file.setMode(testFile, 0740) then: file.getMode(testFile) == 0740 where: fileName << ["test.txt", "test\u03b1\u2295.txt"] } def "cannot set mode on file that does not exist"() { def testFile = new File(tmpDir.root, "unknown") when: file.setMode(testFile, 0660) then: NativeException e = thrown() e.message == "Could not set UNIX mode on $testFile: could not chmod file (ENOENT errno 2)" } def "cannot get mode on file that does not exist"() { def testFile = new File(tmpDir.root, "unknown") when: file.getMode(testFile) then: NativeException e = thrown() e.message == "Could not get UNIX mode on $testFile: could not stat file (ENOENT errno 2)" } def "can create symbolic link"() { def testFile = new File(tmpDir.root, "test.txt") testFile.text = "hi" def symlinkFile = new File(tmpDir.root, "symlink") when: file.symlink(symlinkFile, testFile.name) then: symlinkFile.file symlinkFile.text == "hi" symlinkFile.canonicalFile == testFile.canonicalFile } def "can read symbolic link"() { def symlinkFile = new File(tmpDir.root, "symlink") when: file.symlink(symlinkFile, "target") then: file.readLink(symlinkFile) == "target" } def "cannot read a symlink that does not exist"() { def symlinkFile = new File(tmpDir.root, "symlink") when: file.readLink(symlinkFile) then: NativeException e = thrown() e.message == "Could not read symlink $symlinkFile: could not lstat file (ENOENT errno 2)" } def "cannot read a symlink that is not a symlink"() { def symlinkFile = tmpDir.newFile("not-a-symlink.txt") when: file.readLink(symlinkFile) then: NativeException e = thrown() e.message == "Could not read symlink $symlinkFile: could not readlink (errno 22)" } def "can create and read symlink with unicode in its name"() { def testFile = new File(tmpDir.root, "target\u03b2\u2295") testFile.text = 'hi' def symlinkFile = new File(tmpDir.root, "symlink\u03b2\u2296") when: file.symlink(symlinkFile, testFile.name) then: file.readLink(symlinkFile) == testFile.name symlinkFile.file symlinkFile.canonicalFile == testFile.canonicalFile } } ProcessLauncherTest.groovy000077500000000000000000000026151211277505600346230ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import spock.lang.Specification class ProcessLauncherTest extends Specification { final ProcessLauncher launcher = Native.get(ProcessLauncher) def "can start a child process"() { def javaHome = System.getProperty("java.home") def exe = "${javaHome}/bin/java" ProcessBuilder builder = new ProcessBuilder(exe, "-version") builder.redirectErrorStream(true) when: def process = launcher.start(builder) def stdout = new ByteArrayOutputStream() def stdoutThread = process.consumeProcessOutputStream(stdout) def result = process.waitFor() stdoutThread.join() then: result == 0 stdout.toString().contains(System.getProperty('java.vm.version')) } } libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/ProcessTest.groovy000077500000000000000000000076711211277505600332270ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.Specification class ProcessTest extends Specification { @Rule TemporaryFolder tmpDir final Process process = Native.get(Process.class) def "caches process instance"() { expect: Native.get(Process.class) == process } def "can get PID"() { expect: process.getProcessId() != 0 } def "can get and change working directory"() { def newDir = tmpDir.newFolder(dir).canonicalFile assert newDir.directory when: def original = process.workingDirectory then: original == new File(".").canonicalFile original == new File(System.getProperty("user.dir")) when: process.workingDirectory = newDir then: process.workingDirectory == newDir new File(".").canonicalFile == newDir new File(System.getProperty("user.dir")) == newDir cleanup: process.workingDirectory = original where: dir << ['dir', 'dir\u03b1\u2295'] } def "cannot set working directory to a directory that does not exist"() { def newDir = new File(tmpDir.root, "does not exist"); when: process.workingDirectory = newDir then: NativeException e = thrown() e.message.startsWith("Could not set process working directory") } def "can get and set and remove environment variable"() { when: def value = process.getEnvironmentVariable(varName) then: value == null System.getenv(varName) == null System.getenv()[varName] == null when: process.setEnvironmentVariable(varName, varValue) then: process.getEnvironmentVariable(varName) == varValue System.getenv(varName) == varValue System.getenv()[varName] == varValue when: process.setEnvironmentVariable(varName, null) then: process.getEnvironmentVariable(varName) == null System.getenv(varName) == null System.getenv()[varName] == null where: varName | varValue 'TEST_ENV_VAR' | 'test value' 'TEST_ENV_VAR\u2295\u03b1' | 'value\u03b2\u2296' } def "setting environment variable to null or empty string remove the environment variable"() { when: def value = process.getEnvironmentVariable(varName) then: value == null System.getenv(varName) == null System.getenv()[varName] == null when: process.setEnvironmentVariable(varName, varValue) then: process.getEnvironmentVariable(varName) == null System.getenv(varName) == null System.getenv()[varName] == null where: varName | varValue 'TEST_ENV_VAR_EMPTY' | '' 'TEST_ENV_VAR_NULL' | null } def "can remove environment variable that does not exist"() { assert process.getEnvironmentVariable("TEST_ENV_UNKNOWN") == null when: process.setEnvironmentVariable("TEST_ENV_UNKNOWN", null) then: notThrown(NativeException) } } libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/SystemInfoTest.groovy000077500000000000000000000022261211277505600337000ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.Specification class SystemInfoTest extends Specification { @Rule TemporaryFolder tmpDir final SystemInfo systemInfo = Native.get(SystemInfo.class) def "caches system info instance"() { expect: Native.get(SystemInfo.class) == systemInfo } def "can query OS details"() { expect: systemInfo.kernelName systemInfo.kernelVersion systemInfo.machineArchitecture } } libnative-platform-java-0.3~rc2/src/test/groovy/net/rubygrapefruit/platform/TerminalsTest.groovy000077500000000000000000000036121211277505600335360ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.Specification import net.rubygrapefruit.platform.internal.Platform import spock.lang.IgnoreIf class TerminalsTest extends Specification { @Rule TemporaryFolder tmpDir final Terminals terminals = Native.get(Terminals.class) def "caches terminals instance"() { expect: Native.get(Terminals.class) == terminals } def "can check if attached to terminal"() { expect: !terminals.isTerminal(Terminals.Output.Stdout); !terminals.isTerminal(Terminals.Output.Stderr); } @IgnoreIf({Platform.current().windows}) def "cannot access posix terminal from a test"() { when: terminals.getTerminal(Terminals.Output.Stdout) then: NativeException e = thrown() e.message == 'Could not open terminal for stdout: not a terminal' } @IgnoreIf({!Platform.current().windows}) def "cannot access windows console from a test"() { when: terminals.getTerminal(Terminals.Output.Stdout) then: NativeException e = thrown() e.message == 'Could not open console for stdout: not a console' } } libnative-platform-java-0.3~rc2/test-app/000077500000000000000000000000001211277505600204425ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/build.gradle000066400000000000000000000011061211277505600227170ustar00rootroot00000000000000apply plugin: 'application' mainClassName = 'net.rubygrapefruit.platform.test.Main' applicationName = 'native-platform-test' archivesBaseName = 'native-platform-test' if (project.hasProperty('release')) { repositories { maven { url "$rootProject.buildDir/repo" } } dependencies { compile "net.rubygrapefruit:native-platform:${version}" } } else { dependencies { compile project(':') } } dependencies { compile 'net.sf.jopt-simple:jopt-simple:4.2' } configurations.archives.artifacts.clear() artifacts { archives distZip } libnative-platform-java-0.3~rc2/test-app/src/000077500000000000000000000000001211277505600212315ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/000077500000000000000000000000001211277505600221555ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/000077500000000000000000000000001211277505600230765ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/net/000077500000000000000000000000001211277505600236645ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/net/rubygrapefruit/000077500000000000000000000000001211277505600267365ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/net/rubygrapefruit/platform/000077500000000000000000000000001211277505600305625ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/net/rubygrapefruit/platform/test/000077500000000000000000000000001211277505600315415ustar00rootroot00000000000000libnative-platform-java-0.3~rc2/test-app/src/main/java/net/rubygrapefruit/platform/test/Main.java000077500000000000000000000140361211277505600332770ustar00rootroot00000000000000/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.test; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import net.rubygrapefruit.platform.*; import net.rubygrapefruit.platform.Process; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { OptionParser optionParser = new OptionParser(); optionParser.accepts("cache-dir", "The directory to cache native libraries in").withRequiredArg(); OptionSet result = null; try { result = optionParser.parse(args); } catch (OptionException e) { System.err.println(e.getMessage()); System.err.println(); optionParser.printHelpOn(System.err); System.exit(1); } if (result.has("cache-dir")) { Native.init(new File(result.valueOf("cache-dir").toString())); } System.out.println(); System.out.println("* OS: " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch")); System.out.println("* JVM: " + System.getProperty("java.vm.vendor") + ' ' + System.getProperty("java.version")); System.out.println("* Encoding: " + System.getProperty("file.encoding")); SystemInfo systemInfo = Native.get(SystemInfo.class); System.out.println("* Kernel: " + systemInfo.getKernelName() + ' ' + systemInfo.getKernelVersion() + ' ' + systemInfo.getMachineArchitecture()); Process process = Native.get(Process.class); System.out.println("* PID: " + process.getProcessId()); FileSystems fileSystems = Native.get(FileSystems.class); System.out.println("* File systems: "); for (FileSystem fileSystem : fileSystems.getFileSystems()) { System.out.println(" * " + fileSystem.getMountPoint() + ' ' + fileSystem.getFileSystemType() + ' ' + fileSystem.getDeviceName() + (fileSystem.isRemote() ? " remote" : " local")); } Terminals terminals = Native.get(Terminals.class); boolean stdoutIsTerminal = terminals.isTerminal(Terminals.Output.Stdout); boolean stderrIsTerminal = terminals.isTerminal(Terminals.Output.Stderr); System.out.println("* Stdout: " + (stdoutIsTerminal ? "terminal" : "not a terminal")); System.out.println("* Stderr: " + (stderrIsTerminal ? "terminal" : "not a terminal")); if (stdoutIsTerminal) { Terminal terminal = terminals.getTerminal(Terminals.Output.Stdout); TerminalSize terminalSize = terminal.getTerminalSize(); System.out.println("* Terminal implementation: " + terminal); System.out.println("* Terminal size: " + terminalSize.getCols() + " cols x " + terminalSize.getRows() + " rows"); System.out.println("* Text attributes: " + (terminal.supportsTextAttributes() ? "yes" : "no")); System.out.println("* Color: " + (terminal.supportsColor() ? "yes" : "no")); System.out.println("* Cursor motion: " + (terminal.supportsCursorMotion() ? "yes" : "no")); System.out.println(); System.out.println("TEXT ATTRIBUTES"); System.out.print("[normal] "); terminal.bold(); System.out.print("[bold]"); terminal.normal(); System.out.println(" [normal]"); System.out.println(); System.out.println("COLORS"); for (Terminal.Color color : Terminal.Color.values()) { terminal.foreground(color); terminal.bold(); System.out.print(String.format("[%s] ", color.toString().toLowerCase())); terminal.normal(); System.out.print(String.format("[%s]", color.toString().toLowerCase())); System.out.println(); } System.out.println(); terminal.reset(); if (terminal.supportsCursorMotion()) { System.out.println("CURSOR MOVEMENT"); System.out.println(" "); System.out.println(" "); System.out.print("[delete me]"); terminal.cursorLeft(11); terminal.cursorUp(1); terminal.cursorRight(10); System.out.print("[4]"); terminal.cursorUp(1); terminal.cursorLeft(3); System.out.print("[2]"); terminal.cursorLeft(13); System.out.print("[1]"); terminal.cursorLeft(3); terminal.cursorDown(1); System.out.print("[3]"); terminal.cursorDown(1); terminal.cursorStartOfLine(); terminal.foreground(Terminal.Color.Blue).bold(); System.out.print("done"); terminal.clearToEndOfLine(); System.out.println("!"); System.out.println(); } } else if (stderrIsTerminal) { Terminal terminal = terminals.getTerminal(Terminals.Output.Stderr); System.err.print("* this is "); terminal.bold().foreground(Terminal.Color.Red); System.err.print("red"); terminal.reset(); System.err.print(" text on "); terminal.bold(); System.err.print("stderr"); terminal.reset(); System.err.println("."); } } }