001/*----------------------------------------------------------------------------*/ 002/* Copyright (c) 2016-2018 FIRST. All Rights Reserved. */ 003/* Open Source Software - may be modified and shared by FRC teams. The code */ 004/* must be accompanied by the FIRST BSD license file in the root directory of */ 005/* the project. */ 006/*----------------------------------------------------------------------------*/ 007 008package edu.wpi.first.wpilibj.hal; 009 010import edu.wpi.first.wpiutil.RuntimeDetector; 011import java.io.File; 012import java.io.FileOutputStream; 013import java.io.IOException; 014import java.io.InputStream; 015import java.io.OutputStream; 016 017/** 018 * Base class for all JNI wrappers. 019 */ 020public class JNIWrapper { 021 static boolean libraryLoaded = false; 022 static File jniLibrary = null; 023 024 static { 025 if (!libraryLoaded) { 026 String jniFileName = "wpilibJNI"; 027 try { 028 System.loadLibrary(jniFileName); 029 } catch (UnsatisfiedLinkError ule) { 030 try { 031 String resname = RuntimeDetector.getLibraryResource(jniFileName); 032 InputStream is = JNIWrapper.class.getResourceAsStream(resname); 033 if (is != null) { 034 // create temporary file 035 if (System.getProperty("os.name").startsWith("Windows")) { 036 jniLibrary = File.createTempFile(jniFileName, ".dll"); 037 } else if (System.getProperty("os.name").startsWith("Mac")) { 038 jniLibrary = File.createTempFile(jniFileName, ".dylib"); 039 } else { 040 jniLibrary = File.createTempFile(jniFileName, ".so"); 041 } 042 // flag for delete on exit 043 jniLibrary.deleteOnExit(); 044 OutputStream os = new FileOutputStream(jniLibrary); 045 046 byte[] buffer = new byte[1024]; 047 int readBytes; 048 try { 049 while ((readBytes = is.read(buffer)) != -1) { 050 os.write(buffer, 0, readBytes); 051 } 052 } finally { 053 os.close(); 054 is.close(); 055 } 056 System.load(jniLibrary.getAbsolutePath()); 057 } else { 058 System.loadLibrary(jniFileName); 059 } 060 } catch (IOException ex) { 061 ex.printStackTrace(); 062 System.exit(1); 063 } 064 } 065 libraryLoaded = true; 066 } 067 } 068 069 public static native int getPortWithModule(byte module, byte channel); 070 071 public static native int getPort(byte channel); 072}