Java 类com.sun.jna.Platform 实例源码

项目:marathonv5    文件:DragAndDropTest.java   
public void dndWithCopy() throws Throwable {
    DesiredCapabilities caps = new DesiredCapabilities();
    // caps.setCapability("nativeEvents", true);
    driver = new JavaDriver(caps, caps);
    WebElement list = driver.findElement(By.cssSelector("list"));
    assertEquals(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 4\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
    WebElement listitem1 = driver.findElement(By.cssSelector("list::nth-item(1)"));
    WebElement listitem5 = driver.findElement(By.cssSelector("list::nth-item(5)"));
    listitem1.click();
    driver.clearlogs(LogType.DRIVER);
    Keys copyKey = Keys.ALT;
    if (Platform.isWindows()) {
        copyKey = Keys.CONTROL;
    }
    new Actions(driver).keyDown(copyKey).dragAndDrop(listitem1, listitem5).keyUp(copyKey).perform();
    waitTillDropCompletes(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0(1)\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list);
    assertEquals(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0(1)\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
}
项目:marathonv5    文件:LaunchWebStartTest.java   
public static String findExecutableOnPath(String name) {
    if (!Platform.isWindows() || name.endsWith(".exe") || name.endsWith(".bat")) {
        return getPathTo(name);
    }
    String path;
    path = getPathTo(name + ".exe");
    if (path != null)
        return path;
    path = getPathTo(name + ".cmd");
    if (path != null)
        return path;
    return getPathTo(name + ".bat");
}
项目:gethostname4j    文件:Hostname.java   
/**
 * @return the hostname the of the current machine
 */
public static String getHostname() {
    if (Platform.isWindows()) {
        return Kernel32Util.getComputerName();
    } else {
        // For now, we'll consider anyhting other than Windows to be unix-ish enough to have gethostname
        // TODO - Consider http://stackoverflow.com/a/10543006 as a possibly better MacOS option

        byte[] hostnameBuffer = new byte[4097];
        // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html suggests
        // the actual limit would be 255.

        int result = UnixCLibrary.INSTANCE.gethostname(hostnameBuffer, hostnameBuffer.length);
        if (result != 0) {
            throw new RuntimeException("gethostname call failed");
        }

        return Native.toString(hostnameBuffer);
    }
}
项目:monarch    文件:NativeCallsJNAImpl.java   
private static final NativeCalls getImplInstance() {
  if (Platform.isLinux()) {
    return new LinuxNativeCalls();
  }
  if (Platform.isWindows()) {
    return new WinNativeCalls();
  }
  if (Platform.isSolaris()) {
    return new SolarisNativeCalls();
  }
  if (Platform.isMac()) {
    return new MacOSXNativeCalls();
  }
  if (Platform.isFreeBSD()) {
    return new FreeBSDNativeCalls();
  }
  return new POSIXNativeCalls();
}
项目:monarch    文件:GemFireCacheImpl.java   
public static void lockMemory() {
  int result = 0;
  try {
    Native.register(Platform.C_LIBRARY_NAME);
    result = mlockall(1);
    if (result == 0) {
      return;
    }
  } catch (Throwable t) {
    throw new IllegalStateException("Error trying to lock memory", t);
  }

  int errno = Native.getLastError();
  String msg = "mlockall failed: " + errno;
  if (errno == 1 || errno == 12) { // EPERM || ENOMEM
    msg = "Unable to lock memory due to insufficient free space or privileges.  "
        + "Please check the RLIMIT_MEMLOCK soft resource limit (ulimit -l) and "
        + "increase the available memory if needed";
  }
  throw new IllegalStateException(msg);
}
项目:webkit4j    文件:InstallLibs.java   
/**
 * 安装ssllib到c:\windown\system32下
 */
static void installSslLib(ClassLoader classLoader, String ospath, String name) {
    String libname = mapSharedLibraryName(name);//lib全名.dll .so
    if(Platform.isWindows()) {
        String fullPath = "C:\\Windows\\System32\\" + libname;
        File dest = new File(fullPath);
        if(!dest.exists()) {
            File dir = dest.getParentFile();
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String libClassPath = ospath + "/" + libname;
            extract(classLoader, libClassPath, dest);
        } else {
            System.out.println("have install : " + fullPath);
        }
    }
}
项目:mycore    文件:NativeLibExporter.java   
/**
 * @return an instance of this class.
 */
public static NativeLibExporter getInstance() {
    if (instance == null) {
        instance = new NativeLibExporter();

        try {
            if (Platform.isMac())
                instance.exportLibrary("lib/darwin/libmediainfo.dylib");
            else if (Platform.isWindows() && Platform.is64Bit())
                instance.exportLibrary("lib/win64/MediaInfo64.dll");
            else if (Platform.isWindows())
                instance.exportLibrary("lib/win32/MediaInfo.dll");
        } catch (Throwable e) {
            System.err.println(e.getMessage());
        }
    }

    return instance;
}
项目:WebIDE-Backend    文件:PtyUtil.java   
private static String getPlatformFolder() {
    String result;

    if (Platform.isMac()) {
        result = "macosx";
    } else if (Platform.isWindows()) {
        result = "win";
    } else if (Platform.isLinux()) {
        result = "linux";
    } else if (Platform.isFreeBSD()) {
        result = "freebsd";
    } else if (Platform.isOpenBSD()) {
        result = "openbsd";
    } else {
        throw new IllegalStateException("Platform " + Platform.getOSType() + " is not supported");
    }

    return result;
}
项目:DigitalMediaServer    文件:PlayerFactory.java   
/**
 * Registers known transcoding engines.
 *
 * @throws InterruptedException
 */
private static void registerPlayers() throws InterruptedException {
    if (Platform.isWindows()) {
        registerPlayer(new AviSynthFFmpeg());
        registerPlayer(new AviSynthMEncoder());
    }

    registerPlayer(new FFmpegAudio());
    registerPlayer(new MEncoderVideo());
    registerPlayer(new FFMpegVideo());
    registerPlayer(new VLCVideo());
    registerPlayer(new FFmpegWebVideo());
    registerPlayer(new MEncoderWebVideo());
    registerPlayer(new VLCWebVideo());
    registerPlayer(new TsMuxeRVideo());
    registerPlayer(new TsMuxeRAudio());
    registerPlayer(new VideoLanAudioStreaming());
    registerPlayer(new VideoLanVideoStreaming());
    registerPlayer(new DCRaw());
}
项目:DigitalMediaServer    文件:ProcessManager.java   
/**
 * Retrieves the process ID (PID) for the specified {@link Process}.
 *
 * @param process the {@link Process} for whose PID to retrieve.
 * @return The PID or zero if the PID couldn't be retrieved.
 */
public static int getProcessId(@Nullable Process process) {
    if (process == null) {
        return 0;
    }
    try {
        Field field;
        if (Platform.isWindows()) {
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            int pid = Kernel32.INSTANCE.GetProcessId(new HANDLE(new Pointer(field.getLong(process))));
            if (pid == 0 && LOGGER.isDebugEnabled()) {
                int lastError = Kernel32.INSTANCE.GetLastError();
                LOGGER.debug("KERNEL32.getProcessId() failed with error {}", lastError);
            }
            return pid;
        }
        field = process.getClass().getDeclaredField("pid");
        field.setAccessible(true);
        return field.getInt(process);
    } catch (Exception e) {
        LOGGER.warn("Failed to get process id for process \"{}\": {}", process, e.getMessage());
        LOGGER.trace("", e);
        return 0;
    }
}
项目:DigitalMediaServer    文件:FileUtil.java   
/**
 * Checks for valid file name syntax. Path is not allowed.
 *
 * @param fileName the file name to be verified
 * @return whether or not the file name is valid
 */
public static boolean isValidFileName(String fileName) {
    if (Platform.isWindows()) {
        if (fileName.matches("^[^\"*:<>?/\\\\]+$")) {
            return true;
        }
    } else if (Platform.isMac()) {
        if (fileName.matches("^[^:/]+$")) {
            return true;
        }
    } else {
        // Assuming POSIX
        if (fileName.matches("^[A-Za-z0-9._][A-Za-z0-9._-]*$")) {
            return true;
        }
    }
    return false;
}
项目:DigitalMediaServer    文件:FileUtil.java   
/**
 * Gets the user ID on Unix based systems. This should not change during a
 * session and the lookup is expensive, so we cache the result.
 *
 * @return The Unix user ID
 * @throws IOException
 */
public static int getUnixUID() throws IOException {
    if (
        Platform.isAIX() || Platform.isFreeBSD() || Platform.isGNU() || Platform.iskFreeBSD() ||
        Platform.isLinux() || Platform.isMac() || Platform.isNetBSD() || Platform.isOpenBSD() ||
        Platform.isSolaris()
    ) {
        synchronized (unixUIDLock) {
            if (unixUID < 0) {
                String response;
                Process id;
                id = Runtime.getRuntime().exec("id -u");
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(id.getInputStream(), Charset.defaultCharset()))) {
                    response = reader.readLine();
                }
                try {
                    unixUID = Integer.parseInt(response);
                } catch (NumberFormatException e) {
                    throw new UnsupportedOperationException("Unexpected response from OS: " + response, e);
                }
            }
            return unixUID;
        }
    }
    throw new UnsupportedOperationException("getUnixUID can only be called on Unix based OS'es");
}
项目:DigitalMediaServer    文件:RealFile.java   
@Override
public String getName() {
    if (this.getConf().getName() == null) {
        String name = null;
        File file = getFile();
        if (file.getName().trim().isEmpty()) {
            if (Platform.isWindows()) {
                name = BasicSystemUtils.INSTANCE.getDiskLabel(file);
            }
            if (name != null && name.length() > 0) {
                name = file.getAbsolutePath().substring(0, 1) + ":\\ [" + name + "]";
            } else {
                name = file.getAbsolutePath().substring(0, 1);
            }
        } else {
            name = file.getName();
        }
        this.getConf().setName(name);
    }
    return this.getConf().getName().replaceAll("_imdb([^_]+)_", "");
}
项目:DigitalMediaServer    文件:PipeIPCProcess.java   
@Override
public void runInNewThread() {
    if (!Platform.isWindows()) {
        mkin.getPipeProcess().runInNewThread();
        mkout.getPipeProcess().runInNewThread();

        // Allow the threads some time to do their work before
        // starting the main thread
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
        }
    }

    start();
}
项目:DigitalMediaServer    文件:PipeIPCProcess.java   
@Override
public void runInSameThread() {
    if (!Platform.isWindows()) {
        mkin.getPipeProcess().runInNewThread();
        mkout.getPipeProcess().runInNewThread();

        // Allow the threads some time to do their work before
        // running the main thread
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
        }
    }

    run();
}
项目:DigitalMediaServer    文件:PipeProcess.java   
public PipeProcess(String pipeName, OutputParams params, String... extras) {
    // Use device-specific DMS conf
    configuration = PMS.getConfiguration(params);
    forcereconnect = false;
    boolean in = true;

    if (extras != null && extras.length > 0 && extras[0].equals("out")) {
        in = false;
    }

    if (extras != null) {
        for (String extra : extras) {
            if (extra.equals("reconnect")) {
                forcereconnect = true;
            }
        }
    }

    if (Platform.isWindows()) {
        mk = new WindowsNamedPipe(pipeName, forcereconnect, in, params);
    } else {
        linuxPipeName = getPipeName(pipeName);
    }
}
项目:DigitalMediaServer    文件:PipeProcess.java   
public ProcessWrapper getPipeProcess() {
    if (!Platform.isWindows()) {
        OutputParams mkfifo_vid_params = new OutputParams(configuration);
        mkfifo_vid_params.maxBufferSize = 0.1;
        mkfifo_vid_params.log = true;
        String cmdArray[];

        if (Platform.isMac() || Platform.isFreeBSD() || Platform.isSolaris()) {
            cmdArray = new String[] {"mkfifo", "-m", "777", linuxPipeName};
        } else {
            cmdArray = new String[] {"mkfifo", "--mode=777", linuxPipeName};
        }

        ProcessWrapperImpl mkfifo_vid_process = new ProcessWrapperImpl(cmdArray, mkfifo_vid_params);
        return mkfifo_vid_process;
    }

    return mk;
}
项目:gemfirexd-oss    文件:NativeCallsJNAImpl.java   
private static final NativeCalls getImplInstance() {
  if (Platform.isLinux()) {
    return new LinuxNativeCalls();
  }
  if (Platform.isWindows()) {
    return new WinNativeCalls();
  }
  if (Platform.isSolaris()) {
    return new SolarisNativeCalls();
  }
  if (Platform.isMac()) {
    return new MacOSXNativeCalls();
  }
  if (Platform.isFreeBSD()) {
    return new FreeBSDNativeCalls();
  }
  return new POSIXNativeCalls();
}
项目:Java-Memory-Manipulation    文件:Processes.java   
public static Process byName(String name) {
    if (Platform.isWindows()) {
        Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference();
        Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0);
        try {
            while (Kernel32.Process32Next(snapshot, entry)) {
                String processName = Native.toString(entry.szExeFile);
                if (name.equals(processName)) {
                    return byId(entry.th32ProcessID.intValue());
                }
            }
        } finally {
            Kernel32.CloseHandle(snapshot);
        }
    } else if (Platform.isMac() || Platform.isLinux()) {
        return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'"));
    } else {
        throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")");
    }
    throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?");
}
项目:Java-Memory-Manipulation    文件:Processes.java   
public static Process byId(int id) {
    if ((Platform.isMac() || Platform.isLinux()) && !isSudo()) {
        throw new RuntimeException("You need to run as root/sudo for unix/osx based environments.");
    }

    if (Platform.isWindows()) {
        return new Win32Process(id, Kernel32.OpenProcess(0x438, true, id));
    } else if (Platform.isLinux()) {
        return new UnixProcess(id);
    } else if (Platform.isMac()) {
        IntByReference out = new IntByReference();
        if (mac.task_for_pid(mac.mach_task_self(), id, out) != 0) {
            throw new IllegalStateException("Failed to find mach task port for process, ensure you are running as sudo.");
        }
        return new MacProcess(id, out.getValue());
    }
    throw new IllegalStateException("Process " + id + " was not found. Are you sure its running?");
}
项目:jdivert    文件:DeployHandler.java   
/**
 * Deploys WinDivert DLL and SYS files based upon Platform architecture (32/64bit).
 *
 * @param deployDirManager The TemporaryDirManager to create the temp directory where to store the files.
 * @return The {@link WinDivertDLL} instance to use.
 */
public static WinDivertDLL deploy(TemporaryDirManager deployDirManager) {
    String jnaLibraryPath = System.getProperty("jna.library.path");
    try {
        File temp = deployDirManager.createTempDir();
        if (temp != null && temp.delete() && temp.mkdir()) {
            System.setProperty("jna.library.path", deployInTempDir(temp));
            return (WinDivertDLL) Native.loadLibrary(Platform.is64Bit() ? "WinDivert64" : "WinDivert32", WinDivertDLL.class);
        } else {
            throw new IOException("Could not create a proper temp dir");
        }
    } catch (Exception e) {
        throw new ExceptionInInitializerError(new Exception("Unable to deploy WinDivert", e));
    } finally {
        if (jnaLibraryPath != null)
            System.setProperty("jna.library.path", jnaLibraryPath);
    }
}
项目:BlocktopographPC-GUI    文件:WorldListUtil.java   
public static String getMinecraftFolderLocation() {
    if (Platform.isWindows()) {
        String worldFolder = System.getenv("APPDATA");

        if (worldFolder.endsWith("Roaming")) {
            worldFolder = worldFolder.replace("\\AppData\\Roaming", "\\AppData\\Local");
        }

        StringBuilder folder = new StringBuilder(worldFolder);
        folder.append("\\Packages")
                //.append(getMinecraftFolderName(folder.toString()))
                .append("\\Microsoft.MinecraftUWP_")
                .append(MicrosoftPublisherID)
                .append("\\LocalState\\games\\com.mojang\\minecraftWorlds");

        System.out.println("Minecraft worlds folder: " + folder.toString());

        if (new File(folder.toString()).exists()) {
            return folder.toString();
        }
    }

    return FileSystemView.getFileSystemView().getDefaultDirectory().getPath();
}
项目:BlocktopographPC-GUI    文件:Main.java   
public static boolean checkIsOSSupported() {
    switch(Platform.getOSType()) {
        case Platform.WINDOWS:
            return true;
        case Platform.MAC:
            return false;
        case Platform.LINUX:
            return true;
        case Platform.FREEBSD:
            return false;
        case Platform.OPENBSD:
            return false;
        default:
            return false;
    }
}
项目:crate    文件:MediaInfo.java   
public synchronized MediaInfo open(File file) throws IOException, IllegalArgumentException {
    if (!file.isFile() || file.length() < 64 * 1024) {
        throw new IllegalArgumentException("Invalid media file: " + file);
    }

    String path = file.getCanonicalPath();

    // on Mac files that contain accents cannot be opened via JNA WString file paths due to encoding differences so we use the buffer interface instead for these files
    if (Platform.isMac() && !StandardCharsets.US_ASCII.newEncoder().canEncode(path)) {
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            if (openViaBuffer(raf)) {
                throw new IOException("Failed to initialize media info buffer: " + path);
            }
        }
    }

    if (0 == MediaInfoLibrary.INSTANCE.Open(handle, new WString(path))) {
        // failed to open file
        throw new IOException("Failed to open media file: " + path);
    }

    return this;
}
项目:gstreamer1.x-java    文件:SWTOverlay.java   
/**
 * Helper function to get the proper handle for a given SWT Composite.
 *
 * @param composite the SWT Composite for what i like to get the handle. 
 * The type can't be Control since only Composite has embeddedHandle and
 * the Composite's style must be embedded.  
 * @return the handle of the Composite or 0 if the handle is not available.
 */
public static long getNativeHandle(Composite composite) {
    if (composite != null /*&& ((composite.getStyle() | SWT.EMBEDDED) != 0)*/)
     try {
         Class<? extends Composite> compositeClass = composite.getClass();
         Field handleField = Platform.isLinux() ? compositeClass.getField("embeddedHandle") : compositeClass.getField("handle");
         Class<?> t = handleField.getType();
         if (t.equals(long.class))
             return handleField.getLong(composite);
         else if (t.equals(int.class))
             return handleField.getInt(composite);
     } catch (Exception e) {
         throw new GstException("Cannot set window ID, in XOverlay interface, composite is null or not SWT.EMBEDDED");
     }
    return 0L;
}
项目:gstreamer1.x-java    文件:RegistryTest.java   
@Test
public void filterPlugins() {
    if (Platform.isWindows()) {
        return; // gst_registry_plugin_filter doesn't exist on windows
    }
    final String PLUGIN = "vorbis"; // Use something that is likely to be there
    Registry registry = Registry.getDefault();
    // Ensure some plugins are loaded
    ElementFactory.make("playbin", "test");
    ElementFactory.make("vorbisdec", "vorbis");
    ElementFactory.make("decodebin", "decoder");
    final boolean[] filterCalled = { false };
    List<Plugin> plugins = registry.getPluginList(new Registry.PluginFilter() {

        public boolean accept(Plugin plugin) {
            filterCalled[0] = true;
            return plugin.getName().equals(PLUGIN);
        }
    }, true);
    assertFalse("No plugins found", plugins.isEmpty());
    assertTrue("PluginFilter not called", filterCalled[0]);
    assertEquals("Plugin list should contain 1 item", 1, plugins.size());
    assertEquals(PLUGIN + " plugin not found", PLUGIN, plugins.get(0).getName());
}
项目:mmf4j    文件:Main.java   
public static void main(String[] args) throws IOException {
    MemoryMap mm = MemoryMapFactory.getInstance();
    mm.openFile(Platform.isWindows() ? "./test.txt" : System.getProperty("user.home") + "/test.txt");
    mm.openMapping(1000);
    ByteBuf b = mm.mapView(20, 30);
    b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
    //mm.truncateFile(30);
    b.writerIndex(0);
    b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
    b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));

    ByteBuf c = b.copy();
    c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));

    byte[] bytes = new byte[5];
    b.getBytes(0, bytes);
    System.out.println(new String(bytes, CharsetUtil.UTF_8));

    b.release();
    mm.truncateFile(25);
    mm.resize(50);
    mm.close();
}
项目:vso-intellij    文件:TfTool.java   
/**
 * This method returns the path to the TF command line program.
 * It relies on the vsts-settings file.
 * This method will throw if no valid path exists.
 */
public static String getValidLocation() {
    // Get the tf command location from file
    final String location = getLocation();
    if (StringUtil.isNullOrEmpty(location)) {
        // tfHome property not set
        throw new ToolException(ToolException.KEY_TF_HOME_NOT_SET);
    }

    final String[] filenames = Platform.isWindows() ? TF_WINDOWS_PROGRAMS : TF_OTHER_PROGRAMS;

    // Verify the path leads to a tf command and exists
    for (final String filename : filenames) {
        if (StringUtils.endsWith(location, filename) && (new File(location)).exists()) {
            return location;
        }
    }

    // The saved location does not point to the tf command
    throw new ToolException(ToolException.KEY_TF_EXE_NOT_FOUND);
}
项目:gemfirexd-oss    文件:NativeCallsJNAImpl.java   
private static final NativeCalls getImplInstance() {
  if (Platform.isLinux()) {
    return new LinuxNativeCalls();
  }
  if (Platform.isWindows()) {
    return new WinNativeCalls();
  }
  if (Platform.isSolaris()) {
    return new SolarisNativeCalls();
  }
  if (Platform.isMac()) {
    return new MacOSXNativeCalls();
  }
  if (Platform.isFreeBSD()) {
    return new FreeBSDNativeCalls();
  }
  return new POSIXNativeCalls();
}
项目:acquisition-server    文件:SocketUtils.java   
static int poll(final Pollfd pfd, final int nfds, final int timeout) {
    int ready;
    if (Platform.isWindows()) {
        final WsaPollfd wpfd = new WsaPollfd();
        wpfd.fd = pfd.fd;
        wpfd.events = (short) (pfd.events & ~POLLPRI); // WSAPoll() doesn't support 'POLLPRI' according to the MSDN
        wpfd.revents = pfd.revents;

        ready = LIBWS2.WSAPoll(wpfd, nfds, timeout);
        LOG.debug(String.format("WSAPoll(%s, %d, %d); result=%d", wpfd, nfds, timeout, ready));

        pfd.revents = wpfd.revents;
    }
    else {
        ready = LIBC.poll(pfd, nfds, timeout);
        LOG.debug(String.format("poll(%s, %d, %d); result=%d", pfd, nfds, timeout, ready));
    }

    return ready;
}
项目:mariadb-connector-j    文件:DriverTest.java   
@Test
public void localSocket() throws Exception {
    requireMinimumVersion(5, 1);
    Assume.assumeTrue(System.getenv("TRAVIS") == null);
    Assume.assumeTrue(isLocalConnection("localSocket"));

    Statement st = sharedConnection.createStatement();
    ResultSet rs = st.executeQuery("select @@version_compile_os,@@socket");
    if (!rs.next()) {
        return;
    }
    System.out.println("os:" + rs.getString(1) + " path:" + rs.getString(2));
    String os = rs.getString(1);
    if (os.toLowerCase().startsWith("win") || Platform.isWindows()) {
        return;
    }

    String path = rs.getString(2);
    try (Connection connection = setConnection("&localSocket=" + path + "&profileSql=true")) {
        rs = connection.createStatement().executeQuery("select 1");
        assertTrue(rs.next());
    }
}
项目:APICloud-Studio    文件:LibraryFinder.java   
private static String findMobileLibrary() {
    if (Platform.isWindows()) {
        String path;
        try {
            path = getMDPath(true);
            path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "iTunesMobileDeviceDLL");
        } catch (Exception ignored) {
            try {
                path = getMDPath(false);
                path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "iTunesMobileDeviceDLL");
            } catch (Exception ignored1) {
                log.info(ignored.getMessage());
                return "";
            }
        }
        File f = new File(path);
        if (f.exists())
            return path;
    } else {
        if (Platform.isMac()) {
            return "/System/Library/PrivateFrameworks/MobileDevice.framework/MobileDevice";
        }
    }
    return "";
}
项目:APICloud-Studio    文件:LibraryFinder.java   
private static String findCoreLibrary() {
    String path="";
    if (Platform.isWindows()) {
        try {
            path = getCPath(true);
            path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "InstallDir");
        } catch (Exception ignored) {
            try {
                path = getCPath(false);
                path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "InstallDir");
            } catch (Exception ignored1) {
                return "";
            }
        }
        path = path + "CoreFoundation.dll";
        File f = new File(path);
        if (f.exists())
            return path;
    } else if (Platform.isMac()) {
         return "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
    }
    return "";
}
项目:jpexs-decompiler    文件:CommandLineArgumentParser.java   
private static void parseAffinity(Stack<String> args) {
    if (Platform.isWindows()) {
        if (args.isEmpty()) {
            System.err.println("affinity parameter expected");
            badArguments("affinity");
        }
        try {
            int affinityMask = Integer.parseInt(args.pop());
            Kernel32.INSTANCE.SetProcessAffinityMask(Kernel32.INSTANCE.GetCurrentProcess(), affinityMask);
        } catch (NumberFormatException nex) {
            System.err.println("Bad affinityMask value");
        }
    } else {
        System.err.println("Process affinity setting is only available on Windows platform.");
    }
}
项目:jpexs-decompiler    文件:ContextMenuTools.java   
public static boolean isAddedToContextMenu() {
    if (!Platform.isWindows()) {
        return false;
    }
    final WinReg.HKEY REG_CLASSES_HKEY = WinReg.HKEY_LOCAL_MACHINE;
    final String REG_CLASSES_PATH = "Software\\Classes\\";
    try {
        if (!Advapi32Util.registryKeyExists(REG_CLASSES_HKEY, REG_CLASSES_PATH + ".swf")) {
            return false;
        }
        String clsName = Advapi32Util.registryGetStringValue(REG_CLASSES_HKEY, REG_CLASSES_PATH + ".swf", "");
        if (clsName == null) {
            return false;
        }
        return Advapi32Util.registryKeyExists(REG_CLASSES_HKEY, REG_CLASSES_PATH + clsName + "\\shell\\ffdec");
    } catch (Win32Exception ex) {
        return false;
    }
}
项目:opennmszh    文件:Dumper.java   
public void dump() throws Exception {
    NativeDatagramSocket m_pingSocket =  NativeDatagramSocket.create(NativeDatagramSocket.PF_INET6, Platform.isMac() ? NativeDatagramSocket.SOCK_DGRAM : NativeDatagramSocket.SOCK_RAW, NativeDatagramSocket.IPPROTO_ICMPV6);

    if (Platform.isWindows()) {
        ICMPv6EchoPacket packet = new ICMPv6EchoPacket(64);
        packet.setCode(0);
        packet.setType(Type.EchoRequest);
        packet.getContentBuffer().putLong(System.nanoTime());
        packet.getContentBuffer().putLong(System.nanoTime());
        m_pingSocket.send(packet.toDatagramPacket(InetAddress.getByName("::1")));
    }

    try {
        NativeDatagramPacket datagram = new NativeDatagramPacket(65535);
        while (true) {
            m_pingSocket.receive(datagram);
            System.err.println(datagram);
        }


    } catch(Throwable e) {
        e.printStackTrace();
    }

}
项目:NuProcess    文件:FastExitingProcessTest.java   
@Test
public void whenProcessWritesToStdoutThenExitsThenHandlerReceivesOutput() throws Exception
{
   Handler handler = new Handler();
   NuProcess process;
   if (Platform.isWindows()) {
      // We can't use an argument with a space here because the following command:
      //   cmd /c echo "Hello world!"
      // literally echoes the quotes around "Hello world!" to stdout.
      process = new NuProcessBuilder(handler, "cmd.exe", "/c", "echo", "hello").start();
   }
   else {
      process = new NuProcessBuilder(handler, "echo", "hello").start();
   }
   int retVal = process.waitFor(Long.MAX_VALUE, TimeUnit.SECONDS);
   assertThat("Process should exit cleanly", retVal, equalTo(0));
   assertThat("Process callback should indicate clean exit", handler.exitCode, equalTo(0));
   assertThat("No exceptions thrown writing to stdout", handler.stdoutException, is(nullValue()));
   assertThat("Stdout should contain expected output", handler.stdoutBytes.toString("UTF-8"), equalTo(String.format("hello%n")));
}
项目:pty4j    文件:PtyUtil.java   
private static String getPlatformFolder() {
  String result;

  if (Platform.isMac()) {
    result = "macosx";
  } else if (Platform.isWindows()) {
    result = "win";
  } else if (Platform.isLinux()) {
    result = "linux";
  } else if (Platform.isFreeBSD()) {
    result = "freebsd";
  } else if (Platform.isOpenBSD()) {
    result = "openbsd";
  } else {
    throw new IllegalStateException("Platform " + Platform.getOSType() + " is not supported");
  }

  return result;
}
项目:jnasmartcardio    文件:Winscard.java   
public static WinscardLibInfo openLib() {
    String libraryName = Platform.isWindows() ? WINDOWS_PATH : Platform.isMac() ? MAC_PATH : PCSC_PATH;
    HashMap<String, Object> options = new HashMap<String, Object>();
    if (Platform.isWindows()) {
        options.put(Library.OPTION_FUNCTION_MAPPER, new WindowsFunctionMapper());
    } else if (Platform.isMac()) {
        options.put(Library.OPTION_FUNCTION_MAPPER, new MacFunctionMapper());
    }
    WinscardLibrary lib = (WinscardLibrary) Native.loadLibrary(libraryName, WinscardLibrary.class, options);
    NativeLibrary nativeLibrary = NativeLibrary.getInstance(libraryName);
    // SCARD_PCI_* is #defined to the following symbols (both pcsclite and winscard)
    ScardIoRequest SCARD_PCI_T0 = new ScardIoRequest(nativeLibrary.getGlobalVariableAddress("g_rgSCardT0Pci"));
    ScardIoRequest SCARD_PCI_T1 = new ScardIoRequest(nativeLibrary.getGlobalVariableAddress("g_rgSCardT1Pci"));
    ScardIoRequest SCARD_PCI_RAW = new ScardIoRequest(nativeLibrary.getGlobalVariableAddress("g_rgSCardRawPci"));
    SCARD_PCI_T0.read();
    SCARD_PCI_T1.read();
    SCARD_PCI_RAW.read();
    SCARD_PCI_T0.setAutoSynch(false);
    SCARD_PCI_T1.setAutoSynch(false);
    SCARD_PCI_RAW.setAutoSynch(false);
    return new WinscardLibInfo(lib, SCARD_PCI_T0, SCARD_PCI_T1, SCARD_PCI_RAW);
}
项目:OpenNMS    文件:Dumper.java   
public void dump() throws Exception {
    NativeDatagramSocket m_pingSocket =  NativeDatagramSocket.create(NativeDatagramSocket.PF_INET6, Platform.isMac() ? NativeDatagramSocket.SOCK_DGRAM : NativeDatagramSocket.SOCK_RAW, NativeDatagramSocket.IPPROTO_ICMPV6);

    if (Platform.isWindows()) {
        ICMPv6EchoPacket packet = new ICMPv6EchoPacket(64);
        packet.setCode(0);
        packet.setType(Type.EchoRequest);
        packet.getContentBuffer().putLong(System.nanoTime());
        packet.getContentBuffer().putLong(System.nanoTime());
        m_pingSocket.send(packet.toDatagramPacket(InetAddress.getByName("::1")));
    }

    try {
        NativeDatagramPacket datagram = new NativeDatagramPacket(65535);
        while (true) {
            m_pingSocket.receive(datagram);
            System.err.println(datagram);
        }


    } catch(Throwable e) {
        e.printStackTrace();
    }

}