Java Code Examples for com.sun.jna.Native#loadLibrary()

The following examples show how to use com.sun.jna.Native#loadLibrary() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SystemHealthMonitor.java    From consulo with Apache License 2.0 7 votes vote down vote up
private void checkSignalBlocking() {
  if (SystemInfo.isUnix && JnaLoader.isLoaded()) {
    try {
      LibC lib = Native.loadLibrary("c", LibC.class);
      Memory buf = new Memory(1024);
      if (lib.sigaction(LibC.SIGINT, null, buf) == 0) {
        long handler = Native.POINTER_SIZE == 8 ? buf.getLong(0) : buf.getInt(0);
        if (handler == LibC.SIG_IGN) {
          showNotification(new KeyHyperlinkAdapter("ide.sigint.ignored.message"));
        }
      }
    }
    catch (Throwable t) {
      LOG.warn(t);
    }
  }
}
 
Example 2
Source File: LibNotifyWrapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
private LibNotifyWrapper() {
  myLibNotify = (LibNotify)Native.loadLibrary("libnotify.so.4", LibNotify.class);

  String appName = ApplicationNamesInfo.getInstance().getProductName();
  if (myLibNotify.notify_init(appName) == 0) {
    throw new IllegalStateException("notify_init failed");
  }

  String icon = AppUIUtil.findIcon(ContainerPathManager.get().getAppHomeDirectory().getPath());
  myIcon = icon != null ? icon : "dialog-information";

  MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
  connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() {
    @Override
    public void appClosing() {
      synchronized (myLock) {
        myDisposed = true;
        myLibNotify.notify_uninit();
      }
    }
  });
}
 
Example 3
Source File: UnixSensorsManager.java    From jSensors with Apache License 2.0 6 votes vote down vote up
private CSensors loadDynamicLibrary() {
	Object jnaProxy;

	try {
		jnaProxy = Native.loadLibrary("sensors", CSensors.class);
	} catch (UnsatisfiedLinkError err) {
		LOGGER.info("Cannot find library in system, using embedded one");
		try {
			String libPath = SensorsUtils.generateLibTmpPath("/lib/linux/", "libsensors.so.4.4.0");
			jnaProxy = Native.loadLibrary(libPath, CSensors.class);
			new File(libPath).delete();
		} catch (UnsatisfiedLinkError err1) {
			jnaProxy = null;
			LOGGER.error("Cannot load sensors dinamic library", err1);
		}
	}

	return (CSensors) jnaProxy;
}
 
Example 4
Source File: UnixSocketSyslog.java    From syslog4j with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected synchronized void loadLibrary() {
	if (!OSDetectUtility.isUnix()) {
		throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
	}
	
	if (!this.libraryLoaded) {
		this.libraryInstance = (CLibrary) Native.loadLibrary(this.unixSocketSyslogConfig.getLibrary(),CLibrary.class);
		this.libraryLoaded = true;
	}
}
 
Example 5
Source File: WkHtmlToPdfLoader.java    From htmltopdf-java with MIT License 5 votes vote down vote up
static WkHtmlToPdf load() {
    if ((!tmpDir.exists() && !tmpDir.mkdirs())) {
        throw new IllegalStateException("htmltopdf temporary directory cannot be created");
    }
    if (!tmpDir.canWrite()) {
        throw new IllegalStateException("htmltopdf temporary directory is not writable");
    }

    File libraryFile = new File(tmpDir, getLibraryResource());
    if (!libraryFile.exists()) {
        try {
            File dirPath = libraryFile.getParentFile();
            if (!dirPath.exists() && !dirPath.mkdirs()) {
                throw new IllegalStateException("unable to create directories for native library");
            }
            try (InputStream in = WkHtmlToPdfLoader.class.getResourceAsStream(getLibraryResource())) {
                Files.copy(in, libraryFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    WkHtmlToPdf instance = (WkHtmlToPdf)Native.loadLibrary(libraryFile.getAbsolutePath(), WkHtmlToPdf.class);
    instance.wkhtmltopdf_init(0);

    return instance;
}
 
Example 6
Source File: CLibrary.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static CLibrary init() {
    if (Platform.isMac() || Platform.isOpenBSD()) {
        return (CLibrary) Native.loadLibrary("c", BSDCLibrary.class);
    } else if (Platform.isFreeBSD()) {
        return (CLibrary) Native.loadLibrary("c", FreeBSDCLibrary.class);
    } else if (Platform.isSolaris()) {
        return (CLibrary) Native.loadLibrary("c", SolarisCLibrary.class);
    } else if (Platform.isLinux()) {
        return (CLibrary) Native.loadLibrary("c", LinuxCLibrary.class);
    } else {
        return (CLibrary) Native.loadLibrary("c", CLibrary.class);
    }
}
 
Example 7
Source File: TestSensorsLinux.java    From jSensors with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);

	System.err.println("Return method: " + INSTANCE.sensors_init(null));

	CChip result;
	int numSensor = 0;
	while ((result = INSTANCE.sensors_get_detected_chips(null, new IntByReference(numSensor))) != null) {
		// System.out.println("Found " + result);
		numSensor++;
		System.out.println("Adapter " + INSTANCE.sensors_get_adapter_name(result.bus));

		CFeature feature;
		int numFeature = 0;
		while ((feature = INSTANCE.sensors_get_features(result, new IntByReference(numFeature))) != null) {
			// System.out.println("Found " + feature);
			numFeature++;

			String label = INSTANCE.sensors_get_label(result, feature);

			CSubFeature subFeature;
			int numSubFeature = 0;
			while ((subFeature = INSTANCE.sensors_get_all_subfeatures(result, feature,
					new IntByReference(numSubFeature))) != null) {
				double value = 0.0;
				DoubleByReference pValue = new DoubleByReference(value);

				int returnValue = INSTANCE.sensors_get_value(result, subFeature.number, pValue);
				System.out.println(label + " feature " + subFeature.name + ": " + pValue.getValue());
				System.out.println(label + "returnValue: " + returnValue);
				System.out.println();

				numSubFeature++;
			}
		}
	}

}
 
Example 8
Source File: SecureStorageWindowsManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public static Advapi32Lib getInstance()
{
  if (INSTANCE == null)
  {
    synchronized (Advapi32LibManager.class)
    {
      if (INSTANCE == null)
      {
        INSTANCE = (Advapi32Lib) Native.loadLibrary("advapi32", Advapi32Lib.class, W32APIOptions.UNICODE_OPTIONS);
      }
    }
  }
  return INSTANCE;
}
 
Example 9
Source File: SecureStorageAppleManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public static SecurityLib getInstance()
{
  if (INSTANCE == null)
  {
    synchronized (SecurityLibManager.class)
    {
      if (INSTANCE == null)
      {
        INSTANCE = (SecurityLib) Native.loadLibrary("Security", SecurityLib.class);
      }
    }
  }
  return INSTANCE;
}
 
Example 10
Source File: Kernel32Utils.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
static Kernel32 load ()
{
    try {
        return (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
    } catch (Throwable e) {
        LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);

        return InitializationErrorInvocationHandler.create(
                Kernel32.class,
                e);
    }
}
 
Example 11
Source File: WdmDll.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initialize the wdm library.
 *
 * @param wdmDllPath Full path specification of the native DLL.
 */
public static void initialize(File wdmDllPath) {

    // Initialize the DLL, if not done yet
    if (dllYetToBeInitialized) {
        Results.putMessage(WdmDll.class.getSimpleName() + ": initializing wdm dll " + wdmDllPath.getAbsolutePath());

        String nativeDllPath = wdmDllPath.getAbsolutePath();
        File nativeDll = new File(nativeDllPath);
        if (!nativeDll.exists()) {
            throw new RuntimeException("WdmDll: Native DLL/SO does not exist: " + wdmDllPath.getAbsolutePath());
        }

        if(BBUtils.RUNNING_ON_WINDOWS) {
            nativeDLL = (IWdmFortranNativeDLL) Native.loadLibrary(nativeDllPath, IWdmFortranNativeDLL.class);
        } else {
        	// For now assumes that gfortran is used for linux and ifort for windows
        	GfortranWdmFunctionMapper gfortranMapper = new GfortranWdmFunctionMapper();
        	HashMap<String, String> gfortranMap = gfortranMapper.getMap();
            nativeDLL = (IWdmFortranNativeDLL) Native.loadLibrary(nativeDllPath, IWdmFortranNativeDLL.class, gfortranMap);
        }

        dllYetToBeInitialized = false;

        Results.putMessage(WdmDll.class.getSimpleName() + ": wdm dll initialized.");
    }
}
 
Example 12
Source File: SystemdJournalAppender.java    From log4j-systemd-journal-appender with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PluginFactory
public static SystemdJournalAppender createAppender(@PluginAttribute("name") final String name,
        @PluginAttribute("ignoreExceptions") final String ignoreExceptionsString,
        @PluginAttribute("logSource") final String logSourceString,
        @PluginAttribute("logStacktrace") final String logStacktraceString,
        @PluginAttribute("logLoggerName") final String logLoggerNameString,
        @PluginAttribute("logAppenderName") final String logAppenderNameString,
        @PluginAttribute("logThreadName") final String logThreadNameString,
        @PluginAttribute("logThreadContext") final String logThreadContextString,
        @PluginAttribute("threadContextPrefix") final String threadContextPrefix,
        @PluginAttribute("syslogIdentifier") final String syslogIdentifier,
        @PluginAttribute("syslogFacility") final String syslogFacility,
        @PluginElement("Layout") final Layout<?> layout,
        @PluginElement("Filter") final Filter filter,
        @PluginConfiguration final Configuration config) {
    final boolean ignoreExceptions = Booleans.parseBoolean(ignoreExceptionsString, true);
    final boolean logSource = Booleans.parseBoolean(logSourceString, false);
    final boolean logStacktrace = Booleans.parseBoolean(logStacktraceString, true);
    final boolean logThreadName = Booleans.parseBoolean(logThreadNameString, true);
    final boolean logLoggerName = Booleans.parseBoolean(logLoggerNameString, true);
    final boolean logAppenderName = Booleans.parseBoolean(logAppenderNameString, true);
    final boolean logThreadContext = Booleans.parseBoolean(logThreadContextString, true);

    if (name == null) {
        LOGGER.error("No name provided for SystemdJournalAppender");
        return null;
    }

    final SystemdJournalLibrary journalLibrary;
    try {
        journalLibrary = Native.loadLibrary("systemd", SystemdJournalLibrary.class);
    } catch (UnsatisfiedLinkError e) {
        throw new RuntimeException("Failed to load systemd library." +
            " Please note that JNA requires an executable temporary folder." +
            " It can be explicitly defined with -Djna.tmpdir", e);
    }

    return new SystemdJournalAppender(name, filter, layout, ignoreExceptions, journalLibrary, logSource, logStacktrace,
            logThreadName, logLoggerName, logAppenderName, logThreadContext, threadContextPrefix, syslogIdentifier, syslogFacility);
}
 
Example 13
Source File: UnixSyslog.java    From syslog4j with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static synchronized void loadLibrary(UnixSyslogConfig config) throws SyslogRuntimeException {
	if (!OSDetectUtility.isUnix()) {
		throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
	}
	
	if (libraryInstance == null) {
		libraryInstance = (CLibrary) Native.loadLibrary(config.getLibrary(),CLibrary.class);
	}
}
 
Example 14
Source File: OsNativeApiWindowsImpl.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
private Kernel32 getKernel32() {
	if (kernel32 == null) {
		kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
	}
	return kernel32;
}
 
Example 15
Source File: OsNativeApiWindowsImpl.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
private Shell32 getShell32() {
	if (shell32 == null) {
		shell32 = (Shell32) Native.loadLibrary("shell32", Shell32.class);
	}
	return shell32;
}
 
Example 16
Source File: Hunspell.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/**
     * hunspell 运行实例
     */
    public Hunspell(Shell shell){
    	this.shell = shell;
    	
    	try {
    		root = ResourcesPlugin.getWorkspace().getRoot();
    		// 先求出所有所支持的语言
    		xmlHandler = new QAXmlHandler();
//    		Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
//    		String configXml = FileLocator.toFileURL(bundle.getEntry(QAConstant.QA_SPELL_hunspellConfigFile)).getPath();
//    		String configXml = root.getLocation().append(QAConstant.QA_SPELL_hunspellConfigFile).toOSString() ;
    		String configXml = Platform.getConfigurationLocation().getURL().getPath() + QAConstant.QA_SPELL_hunspellConfigFile;
    		
//    		if (!new File(configXml).exists() || new File(configXml).isDirectory()) {
//    			copyHunspellData();
//			}
    		
    		if (!new File(configXml).exists() || new File(configXml).isDirectory()) {
    			isError = true;
				MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), 
						Messages.getString("qa.spell.hunspell.notFindHunpsellConfigTip"));
				return;
			}
    		availableLangMap = xmlHandler.getHunspellAvailableLang(configXml);
    		if (availableLangMap == null) {
    			MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), 
    					Messages.getString("qa.spell.hunspell.hunspellConfigErrorTip"));
				isError = true;
				return;
			}
    		
//    		libFile = FileLocator.toFileURL(bundle.getEntry(QAConstant.QA_SPELL_hunspellLibraryFolder)).getFile();
//    		libFile = new File(libFile).getAbsolutePath() + System.getProperty("file.separator") + libName();
//    		libFile = "C:\\Documents and Settings\\Administrator\\桌面\\h\\lib\\" + libName();
//    		libFile = root.getLocation().append(".metadata/h/native-library").append(libName()).toOSString();
//    		libFile = new File(Platform.getConfigurationLocation().getURL().getPath() + "h/native-library"  + System.getProperty("file.separator") + libName()).getAbsolutePath();
    		libFile = root.getLocation().append(QAConstant.QA_SPELL_hunspellLibraryFolder).append(libName()).toOSString() ;
    		if (!new File(libFile).exists() || new File(libFile).isDirectory()) {
    			copyHunspellLibFile();
			}
    		
    		if (!new File(libFile).exists()) {
    			MessageFormat.format(Messages.getString("qa.spell.hunspell.notFindHunspellLibTip"), new Object[]{libFile});
    			isError = true;
    			return;
			}
    		// 加载运行库
			hunspellLibrary = (HunspellLibrary)Native.loadLibrary(libFile, HunspellLibrary.class);
		} catch (Exception e) {
			isError = true;
			e.printStackTrace();
		}
    }
 
Example 17
Source File: Hunspell.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
protected void tryLoad(String libFile) throws UnsupportedOperationException {
hunspellLibrary = (HunspellLibrary)Native.loadLibrary(libFile, HunspellLibrary.class);
  }
 
Example 18
Source File: KSE.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Start the KeyStore Explorer application. Takes one optional argument -
 * the location of a KeyStore file to open upon startup.
 *
 * @param args
 *            the command line arguments
 */
public static void main(String args[]) {
	try {
		// To take affect these must be set before the splash screen is instantiated
		if (OperatingSystem.isMacOs()) {
			setAppleSystemProperties();
		} else if (OperatingSystem.isWindows7() || OperatingSystem.isWindows8() || OperatingSystem.isWindows10()) {
			String appId = props.getString("KSE.AppUserModelId");
			Shell32 shell32 = Native.loadLibrary("shell32", Shell32.class);
			shell32.SetCurrentProcessExplicitAppUserModelID(new WString(appId)).longValue();
		} else if (OperatingSystem.isLinux()) {
			fixAppClassName();
		}

		setInstallDirProperty();

		SplashScreen splash = SplashScreen.getSplashScreen();

		updateSplashMessage(splash, res.getString("KSE.LoadingApplicationSettings.splash.message"));
		ApplicationSettings applicationSettings = ApplicationSettings.getInstance();
		setCurrentDirectory(applicationSettings);

		String languageCode = applicationSettings.getLanguage();
		if (!ApplicationSettings.SYSTEM_LANGUAGE.equals(languageCode)) {
			Locale.setDefault(new Locale(languageCode));
		}

		updateSplashMessage(splash, res.getString("KSE.InitializingSecurity.splash.message"));
		initialiseSecurity();

		// list of files to open after start
		List<File> parameterFiles = new ArrayList<>();
		for (String arg : args) {
			File parameterFile = new File(arg);
			if (parameterFile.exists()) {
				parameterFiles.add(parameterFile);
			}
		}

		// Create application GUI on the event handler thread
		updateSplashMessage(splash, res.getString("KSE.CreatingApplicationGui.splash.message"));
		SwingUtilities.invokeLater(new CreateApplicationGui(applicationSettings, splash, parameterFiles));
	} catch (Throwable t) {
		DError dError = new DError(new JFrame(), t);
		dError.setLocationRelativeTo(null);
		dError.setVisible(true);
		System.exit(1);
	}
}
 
Example 19
Source File: LoadLibs.java    From tess4j with Apache License 2.0 2 votes vote down vote up
/**
 * Loads Tesseract library via JNA.
 *
 * @return TessAPI instance being loaded using
 * <code>Native.loadLibrary()</code>.
 */
public static TessAPI getTessAPIInstance() {
    return (TessAPI) Native.loadLibrary(getTesseractLibName(), TessAPI.class);
}
 
Example 20
Source File: EpanetWrapper.java    From hortonmachine with GNU General Public License v3.0 1 votes vote down vote up
/**
 * Contructor for the {@link EpanetWrapper}.
 * 
 * <p>This also takes care to load the native library, if needed. 
 * 
 * @param lib the name of the library (ex. "epanet2_64bit").
 * @param nativeLibPath the path in which to search the native library.
 *              If the native library is already in the java library path
 *              this is not needed and may be <code>null</code>
 * @throws Exception if the library could not be loaded.
 */
public EpanetWrapper( String lib, String nativeLibPath ) throws Exception {
    if (epanet == null) {
        try {
            if (nativeLibPath != null)
                NativeLibrary.addSearchPath(lib, nativeLibPath);
            epanet = (EpanetNativeFunctions) Native.loadLibrary(lib, EpanetNativeFunctions.class);
        } catch (Exception e) {
            throw new Exception("An error occurred while trying to load the epanet library.", e);
        }
    }
}