Java/Development Class/OS — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 10:00, 1 июня 2010
Содержание
- 1 Class representing a standard operating system platform, WIN, MAC, or POSIX.
- 2 Class to help determining the OS
- 3 Condition that tests the OS type.
- 4 Get OS
- 5 Get the operating system
- 6 Platform specific functionality.
- 7 Splits apart a OS separator delimited set of paths in a string into multiple Strings.
Class representing a standard operating system platform, WIN, MAC, or POSIX.
<source lang="java">
/*
* OS.java * 2007-04-14 */
//cb.aloe.util; import java.io.File; import java.util.ArrayList; /**
* Class representing a standard operating system platform, WIN, MAC, or POSIX. * * @author Christopher Bach */
public final class OS {
public static final OS WIN = new OS("WIN"); public static final OS MAC = new OS("MAC"); public static final OS POSIX = new OS("POSIX"); private String ourOS = ""; /** * Private constructor to avert instantiation. */ private OS(String os) { ourOS = os; } /** * Returns a String representing this OS object. */ public String toString() { return ourOS; } /** * Returns the first readable and writable application data folder appropriate * to this OS. */ public static File getAppDataFolder() { File[] folders = listAppDataFolders(); for (int i = 0; i < folders.length; i++) { File folder = folders[i]; if (folder.canRead() && folder.canWrite()) return folder; } return null; } /** * Returns the first readable and writable user data folder appropriate to * this OS. */ public static File getUserDataFolder() { File[] folders = listUserDataFolders(); for (int i = 0; i < folders.length; i++) { File folder = folders[i]; if (folder.canRead() && folder.canWrite()) return folder; } return null; } /** * Returns a list of the preferred locations for storing application- specific * data in descending order. */ public static File[] listAppDataFolders() { String home = System.getProperty("user.home"); ArrayList folders = new ArrayList(); if (isWinNT()) // NT/2000/XP { // C:\Documents and Settings\All Users\Application Data // Surmise that the "All Users" folder will be a child of the // parent of the current user"s home folder: File folder = new File(home).getParentFile(); folders.add(new File(folder, "All Users\\Application Data")); } else if (isWin9X()) // 95/98/ME { // C:\Windows folders.add(new File(home)); } else if (isVista()) { // C:\ProgramData File folder = new File(home).getParentFile().getParentFile(); folders.add(new File(folder, "ProgramData")); // C:\Users\Public\AppData folder = new File(home).getParentFile(); folders.add(new File(folder, "Public\\AppData")); } else if (isMac()) { folders.add(new File("/Library/Application Support")); } else { folders.add(new File("/var/local")); folders.add(new File("/var")); } // folders.addAll(Arrays.asList(listUserDataFolders())); File[] files = new File[folders.size()]; return (File[]) folders.toArray(files); } /** * Returns a list of the preferred locations for storing user- specific data * in descending order. */ public static File[] listUserDataFolders() { String home = System.getProperty("user.home"); ArrayList folders = new ArrayList(); if (isWinNT()) { folders.add(new File(home + "\\Application Data")); folders.add(new File(home + "\\Local Settings\\Application Data")); } else if (isVista()) { folders.add(new File(home + "\\AppData")); folders.add(new File(home + "\\AppData\\Local")); } else if (isMac()) { folders.add(new File(home + "/Library/Application Support")); } folders.add(new File(home)); File[] files = new File[folders.size()]; return (File[]) folders.toArray(files); } /** * Returns the name of the current operating system platform as listed in the * System properties. */ public static final String getOSName() { return System.getProperty("os.name"); } /** * Returns the OS representing the current operating system platform. */ public static final OS getOS() { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("windows") >= 0) return WIN; else if (os.indexOf("mac os") >= 0) return MAC; else return POSIX; } /** * Returns whether or not the current operating system is a Microsoft Windows * platform. */ public static final boolean isWindows() { return getOS() == WIN; } /** * Returns whether or not the current operating system is a Microsoft Windows * 9X platform (Windows 95/98/ME). */ public static boolean isWin9X() { if (getOS() != WIN) return false; String os = getOSName(); if (os.indexOf("95") >= 0 || os.indexOf("98") >= 0 || os.indexOf("me") >= 0) return true; return false; } /** * Returns whether or not the current operating system is a Microsoft Windows * NT platform (Windows NT/2000/2003/XP). */ public static boolean isWinNT() { if (getOS() != WIN) return false; String os = getOSName(); if (os.indexOf("NT") >= 0 || os.indexOf("2000") >= 0 || os.indexOf("2003") >= 0 || os.indexOf("XP") >= 0) return true; return false; } /** * Returns whether or not the current operating system is a Microsoft Windows * Vista platform. */ public static boolean isVista() { if (getOS() != WIN) return false; String os = getOSName(); return (os.indexOf("Vista") >= 0); } /** * Returns whether or not the current operating system is the Apple Macintosh * OS X platform. */ public static final boolean isMac() { return getOS() == MAC; } /** * Returns whether or not the current operating system is a Posix-compatible * platform (Unix, Linux, Solaris, etc). */ public static final boolean isPosix() { return getOS() == POSIX; }
}
</source>
Class to help determining the OS
<source lang="java">
/*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; /**
* Class to help determining the OS. * * @author * @version $Revision: 480428 $ $Date: 2006-11-29 07:15:24 +0100 (Mi, 29 Nov 2006) $ */ final class OsFamily
{
private final String name; private final OsFamily[] families; OsFamily(final String name) { this.name = name; families = new OsFamily[0]; } OsFamily(final String name, final OsFamily[] families) { this.name = name; this.families = families; } /** * Returns the name of this family. */ public String getName() { return name; } /** * Returns the OS families that this family belongs to. */ public OsFamily[] getFamilies() { return families; }
}
</source>
Condition that tests the OS type.
<source lang="java">
/*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * */
import java.util.Locale; /**
* Condition that tests the OS type. */
public final class OS {
private static final String FAMILY_OS_400 = "os/400"; private static final String FAMILY_Z_OS = "z/os"; private static final String FAMILY_WIN9X = "win9x"; private static final String FAMILY_OPENVMS = "openvms"; private static final String FAMILY_UNIX = "unix"; private static final String FAMILY_TANDEM = "tandem"; private static final String FAMILY_MAC = "mac"; private static final String FAMILY_DOS = "dos"; private static final String FAMILY_NETWARE = "netware"; private static final String FAMILY_OS_2 = "os/2"; private static final String FAMILY_WINDOWS = "windows"; private static final String OS_NAME = System.getProperty("os.name") .toLowerCase(Locale.US); private static final String OS_ARCH = System.getProperty("os.arch") .toLowerCase(Locale.US); private static final String OS_VERSION = System.getProperty("os.version") .toLowerCase(Locale.US); private static final String PATH_SEP = System.getProperty("path.separator"); /** * Default constructor */ private OS() { } /** * Determines if the OS on which Ant is executing matches the given OS * family. * Possible values:*
-
*
- dos *
- mac *
- netware *
- os/2 *
- tandem *
- unix *
- windows *
- win9x *
- z/os *
- os/400 *
* * @param family * the family to check for * @return true if the OS matches */ private static boolean isFamily(final String family) { return isOs(family, null, null, null); } public static boolean isFamilyDOS() { return isFamily(FAMILY_DOS); } public static boolean isFamilyMac() { return isFamily(FAMILY_MAC); } public static boolean isFamilyNetware() { return isFamily(FAMILY_NETWARE); } public static boolean isFamilyOS2() { return isFamily(FAMILY_OS_2); } public static boolean isFamilyTandem() { return isFamily(FAMILY_TANDEM); } public static boolean isFamilyUnix() { return isFamily(FAMILY_UNIX); } public static boolean isFamilyWindows() { return isFamily(FAMILY_WINDOWS); } public static boolean isFamilyWin9x() { return isFamily(FAMILY_WIN9X); } public static boolean isFamilyZOS() { return isFamily(FAMILY_Z_OS); } public static boolean isFamilyOS400() { return isFamily(FAMILY_OS_400); } public static boolean isFamilyOpenVms() { return isFamily(FAMILY_OPENVMS); } /** * Determines if the OS on which Ant is executing matches the given OS name. * * @param name * the OS name to check for * @return true if the OS matches */ public static boolean isName(final String name) { return isOs(null, name, null, null); } /** * Determines if the OS on which Ant is executing matches the given OS * architecture. * * @param arch * the OS architecture to check for * @return true if the OS matches */ public static boolean isArch(final String arch) { return isOs(null, null, arch, null); } /** * Determines if the OS on which Ant is executing matches the given OS * version. * * @param version * the OS version to check for * @return true if the OS matches */ public static boolean isVersion(final String version) { return isOs(null, null, null, version); } /** * Determines if the OS on which Ant is executing matches the given OS * family, name, architecture and version * * @param family * The OS family * @param name * The OS name * @param arch * The OS architecture * @param version * The OS version * @return true if the OS matches */ public static boolean isOs(final String family, final String name, final String arch, final String version) { boolean retValue = false; if (family != null || name != null || arch != null || version != null) { boolean isFamily = true; boolean isName = true; boolean isArch = true; boolean isVersion = true; if (family != null) { if (family.equals(FAMILY_WINDOWS)) { isFamily = OS_NAME.indexOf(FAMILY_WINDOWS) > -1; } else if (family.equals(FAMILY_OS_2)) { isFamily = OS_NAME.indexOf(FAMILY_OS_2) > -1; } else if (family.equals(FAMILY_NETWARE)) { isFamily = OS_NAME.indexOf(FAMILY_NETWARE) > -1; } else if (family.equals(FAMILY_DOS)) { isFamily = PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE); } else if (family.equals(FAMILY_MAC)) { isFamily = OS_NAME.indexOf(FAMILY_MAC) > -1; } else if (family.equals(FAMILY_TANDEM)) { isFamily = OS_NAME.indexOf("nonstop_kernel") > -1; } else if (family.equals(FAMILY_UNIX)) { isFamily = PATH_SEP.equals(":") && !isFamily(FAMILY_OPENVMS) && (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x")); } else if (family.equals(FAMILY_WIN9X)) { isFamily = isFamily(FAMILY_WINDOWS) && (OS_NAME.indexOf("95") >= 0 || OS_NAME.indexOf("98") >= 0 || OS_NAME.indexOf("me") >= 0 || OS_NAME .indexOf("ce") >= 0); } else if (family.equals(FAMILY_Z_OS)) { isFamily = OS_NAME.indexOf(FAMILY_Z_OS) > -1 || OS_NAME.indexOf("os/390") > -1; } else if (family.equals(FAMILY_OS_400)) { isFamily = OS_NAME.indexOf(FAMILY_OS_400) > -1; } else if (family.equals(FAMILY_OPENVMS)) { isFamily = OS_NAME.indexOf(FAMILY_OPENVMS) > -1; } else { throw new IllegalArgumentException( "Don\"t know how to detect os family \"" + family + "\""); } } if (name != null) { isName = name.equals(OS_NAME); } if (arch != null) { isArch = arch.equals(OS_ARCH); } if (version != null) { isVersion = version.equals(OS_VERSION); } retValue = isFamily && isName && isArch && isVersion; } return retValue; }
}
</source>
Get OS
<source lang="java">
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don"t indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */
/*
* OS.java * * Created on December 8, 2001, 5:48 PM */
import java.io.File; /**
* * @author bnevins * @version */
public class OS {
private OS() { } /////////////////////////////////////////////////////////////////////////// public static boolean isWindows() { return File.separatorChar == "\\"; } /////////////////////////////////////////////////////////////////////////// public static boolean isUNIX() { return File.separatorChar == "/"; } /////////////////////////////////////////////////////////////////////////// public static boolean isUnix() { // convenience method... return isUNIX(); } /////////////////////////////////////////////////////////////////////////// public static boolean isSun() { return isName("sun"); } /////////////////////////////////////////////////////////////////////////// public static boolean isSolaris10() { return isSun() && isVersion("5.10"); } /////////////////////////////////////////////////////////////////////////// public static boolean isSunSparc() { return isName("sun") && isArch("sparc"); } /////////////////////////////////////////////////////////////////////////// public static boolean isSunX86() { return isName("sun") && isArch("x86"); } /////////////////////////////////////////////////////////////////////////// public static boolean isLinux() { return isName("linux"); } /////////////////////////////////////////////////////////////////////////// public static boolean isDarwin() { return isName("Mac OS X"); } /////////////////////////////////////////////////////////////////////////// public static boolean isWindowsForSure() { return isName("windows") && isWindows(); } /////////////////////////////////////////////////////////////////////////// // There are 10 known Linux versions! /////////////////////////////////////////////////////////////////////////// public static boolean isDebianLinux() { return isLinux() && new File("/etc/debian_version").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isFedoraLinux() { return isLinux() && new File("/etc/fedora-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isGentooLinux() { return isLinux() && new File("/etc/gentoo-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isKnoppixLinux() { return isLinux() && new File("/etc/knoppix_version").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isMandrakeLinux() { return isLinux() && new File("/etc/mandrake-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isMandrivaLinux() { return isLinux() && new File("/etc/mandriva-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isRedHatLinux() { return isLinux() && new File("/etc/redhat-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isSlackwareLinux() { return isLinux() && new File("/etc/slackware-version").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isSuSELinux() { return isLinux() && new File("/etc/SuSE-release").exists(); } /////////////////////////////////////////////////////////////////////////// public static boolean isUbuntuLinux() { return isLinux() && new File("/etc/lsb-release").exists(); } /////////////////////////////////////////////////////////////////////////// private static boolean isArch(String name) { String archname = System.getProperty("os.arch"); if(archname == null || archname.length() <= 0) return false; // case insensitive compare... archname= archname.toLowerCase(); name= name.toLowerCase(); if(archname.indexOf(name) >= 0) return true; return false; } /////////////////////////////////////////////////////////////////////////// private static boolean isName(String name) { String osname = System.getProperty("os.name"); if(osname == null || osname.length() <= 0) return false; // case insensitive compare... osname = osname.toLowerCase(); name = name.toLowerCase(); if(osname.indexOf(name) >= 0) return true; return false; } /////////////////////////////////////////////////////////////////////////// private static boolean isVersion(String version) { String osversion = System.getProperty("os.version"); if(osversion == null || osversion.length() <= 0 || version == null || version.length() <= 0 ) return false; if(osversion.equals(version)) return true; return false; } /////////////////////////////////////////////////////////////////////////// public static final String WINDOWS_BATCH_FILE_EXTENSION = ".bat"; /** * @param args the command line arguments */ public static void main(String args[]) { System.out.println("os.version = " + System.getProperty("os.version")); System.out.println("os.name = " + System.getProperty("os.name")); System.out.println("os.arch = " + System.getProperty("os.arch")); System.out.println("isUNIX() returned: " + isUNIX()); System.out.println("isWindows() returned: " + isWindows()); System.out.println("isWindowsForSure() returned: " + isWindowsForSure()); System.out.println("isSun() returned: " + isSun()); System.out.println("isLinux() returned: " + isLinux()); System.out.println("isDebianLinux() returned: " + isDebianLinux()); System.out.println("isFedoraLinux() returned: " + isFedoraLinux()); System.out.println("isGentooLinux() returned: " + isGentooLinux()); System.out.println("isKnoppixLinux() returned: " + isKnoppixLinux()); System.out.println("isMandrakeLinux() returned: " + isMandrakeLinux()); System.out.println("isMandrivaLinux() returned: " + isMandrivaLinux()); System.out.println("isRedHatLinux() returned: " + isRedHatLinux()); System.out.println("isSlackwareLinux() returned: " + isSlackwareLinux()); System.out.println("isSuSELinux() returned: " + isSuSELinux()); System.out.println("isUbuntuLinux() returned: " + isUbuntuLinux()); System.out.println("isSunX86() returned: " + isSunX86()); System.out.println("isSunSparc() returned: " + isSunSparc()); System.out.println("isDarwin() returned: " + isDarwin()); System.out.println("isSolaris10() returned: " + isSolaris10()); }
}
</source>
Get the operating system
<source lang="java">
/*
* $Id: Utilities.java,v 1.11 2008/10/14 22:31:46 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
import java.awt.ruponent; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyEvent; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.text.BreakIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.NoSuchElementException; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; /**
* Contribution from NetBeans: Issue #319-swingx.*
*
* PENDING: need to reconcile with OS, JVM... added as-is because needed the
* shortcut handling to fix #
*
* @author apple
*/
public class Utilities {
private Utilities() {
}
private static final int CTRL_WILDCARD_MASK = 32768;
private static final int ALT_WILDCARD_MASK = CTRL_WILDCARD_MASK * 2;
/** Operating system is Windows NT. */
public static final int OS_WINNT = 1 << 0;
/** Operating system is Windows 95. */
public static final int OS_WIN95 = OS_WINNT << 1;
/** Operating system is Windows 98. */
public static final int OS_WIN98 = OS_WIN95 << 1;
/** Operating system is Solaris. */
public static final int OS_SOLARIS = OS_WIN98 << 1;
/** Operating system is Linux. */
public static final int OS_LINUX = OS_SOLARIS << 1;
/** Operating system is HP-UX. */
public static final int OS_HP = OS_LINUX << 1;
/** Operating system is IBM AIX. */
public static final int OS_AIX = OS_HP << 1;
/** Operating system is SGI IRIX. */
public static final int OS_IRIX = OS_AIX << 1;
/** Operating system is Sun OS. */
public static final int OS_SUNOS = OS_IRIX << 1;
/** Operating system is Compaq TRU64 Unix */
public static final int OS_TRU64 = OS_SUNOS << 1;
/** Operating system is OS/2. */
public static final int OS_OS2 = OS_TRU64 << 2;
/** Operating system is Mac. */
public static final int OS_MAC = OS_OS2 << 1;
/** Operating system is Windows 2000. */
public static final int OS_WIN2000 = OS_MAC << 1;
/** Operating system is Compaq OpenVMS */
public static final int OS_VMS = OS_WIN2000 << 1;
/**
*Operating system is one of the Windows variants but we don"t know which
*one it is
*/
public static final int OS_WIN_OTHER = OS_VMS << 1;
/** Operating system is unknown. */
public static final int OS_OTHER = OS_WIN_OTHER << 1;
/** Operating system is FreeBSD
* @since 4.50
*/
public static final int OS_FREEBSD = OS_OTHER << 1;
/** A mask for Windows platforms. */
public static final int OS_WINDOWS_MASK = OS_WINNT | OS_WIN95 | OS_WIN98 | OS_WIN2000 | OS_WIN_OTHER;
/** A mask for Unix platforms. */
public static final int OS_UNIX_MASK = OS_SOLARIS | OS_LINUX | OS_HP | OS_AIX | OS_IRIX | OS_SUNOS | OS_TRU64 |
OS_MAC | OS_FREEBSD;
/** A height of the windows"s taskbar */
public static final int TYPICAL_WINDOWS_TASKBAR_HEIGHT = 27;
/** A height of the Mac OS X"s menu */
private static final int TYPICAL_MACOSX_MENU_HEIGHT = 24;
private static int operatingSystem = -1;
/** reference to map that maps allowed key names to their values (String, Integer)
and reference to map for mapping of values to their names */
private static Reference<Object> namesAndValues;
/** Get the operating system.
* @return one of the OS_*
constants (such as {@link #OS_WINNT})
*/
public static int getOperatingSystem() {
if (operatingSystem == -1) {
String osName = System.getProperty("os.name");
if ("Windows NT".equals(osName)) { // NOI18N
operatingSystem = OS_WINNT;
} else if ("Windows 95".equals(osName)) { // NOI18N
operatingSystem = OS_WIN95;
} else if ("Windows 98".equals(osName)) { // NOI18N
operatingSystem = OS_WIN98;
} else if ("Windows 2000".equals(osName)) { // NOI18N
operatingSystem = OS_WIN2000;
} else if (osName.startsWith("Windows ")) { // NOI18N
operatingSystem = OS_WIN_OTHER;
} else if ("Solaris".equals(osName)) { // NOI18N
operatingSystem = OS_SOLARIS;
} else if (osName.startsWith("SunOS")) { // NOI18N
operatingSystem = OS_SOLARIS;
}
// JDK 1.4 b2 defines os.name for me as "Redhat Linux" -jglick
else if (osName.endsWith("Linux")) { // NOI18N
operatingSystem = OS_LINUX;
} else if ("HP-UX".equals(osName)) { // NOI18N
operatingSystem = OS_HP;
} else if ("AIX".equals(osName)) { // NOI18N
operatingSystem = OS_AIX;
} else if ("Irix".equals(osName)) { // NOI18N
operatingSystem = OS_IRIX;
} else if ("SunOS".equals(osName)) { // NOI18N
operatingSystem = OS_SUNOS;
} else if ("Digital UNIX".equals(osName)) { // NOI18N
operatingSystem = OS_TRU64;
} else if ("OS/2".equals(osName)) { // NOI18N
operatingSystem = OS_OS2;
} else if ("OpenVMS".equals(osName)) { // NOI18N
operatingSystem = OS_VMS;
} else if (osName.equals("Mac OS X")) { // NOI18N
operatingSystem = OS_MAC;
} else if (osName.startsWith("Darwin")) { // NOI18N
operatingSystem = OS_MAC;
} else if (osName.toLowerCase(Locale.US).startsWith("freebsd")) { // NOI18N
operatingSystem = OS_FREEBSD;
} else {
operatingSystem = OS_OTHER;
}
}
return operatingSystem;
}
/** Test whether NetBeans is running on some variant of Windows.
* @return true
if Windows, false
if some other manner of operating system
*/
public static boolean isWindows() {
return (getOperatingSystem() & OS_WINDOWS_MASK) != 0;
}
/** Test whether NetBeans is running on some variant of Unix.
* Linux is included as well as the commercial vendors, and Mac OS X.
* @return true
some sort of Unix, false
if some other manner of operating system
*/
public static boolean isUnix() {
return (getOperatingSystem() & OS_UNIX_MASK) != 0;
}
/** Test whether the operating system supports icons on frames (windows).
* @return true
if it does not
*
*/
public static boolean isLargeFrameIcons() {
return (getOperatingSystem() == OS_SOLARIS) || (getOperatingSystem() == OS_HP);
}
/**
* Finds out the monitor where the user currently has the input focus.
* This method is usually used to help the client code to figure out on
* which monitor it should place newly created windows/frames/dialogs.
*
* @return the GraphicsConfiguration of the monitor which currently has the
* input focus
*/
private static GraphicsConfiguration getCurrentGraphicsConfiguration() {
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (focusOwner != null) {
Window w = SwingUtilities.getWindowAncestor(focusOwner);
if (w != null) {
return w.getGraphicsConfiguration();
}
}
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
/**
* Returns the usable area of the screen where applications can place its
* windows. The method subtracts from the screen the area of taskbars,
* system menus and the like. The screen this method applies to is the one
* which is considered current, ussually the one where the current input
* focus is.
*
* @return the rectangle of the screen where one can place windows
*
* @since 2.5
*/
public static Rectangle getUsableScreenBounds() {
return getUsableScreenBounds(getCurrentGraphicsConfiguration());
}
/**
* Returns the usable area of the screen where applications can place its
* windows. The method subtracts from the screen the area of taskbars,
* system menus and the like.
*
* @param gconf the GraphicsConfiguration of the monitor
* @return the rectangle of the screen where one can place windows
*
* @since 2.5
*/
public static Rectangle getUsableScreenBounds(GraphicsConfiguration gconf) {
if (gconf == null) {
gconf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
Rectangle bounds = new Rectangle(gconf.getBounds());
String str;
str = System.getProperty("netbeans.screen.insets"); // NOI18N
if (str != null) {
StringTokenizer st = new StringTokenizer(str, ", "); // NOI18N
if (st.countTokens() == 4) {
try {
bounds.y = Integer.parseInt(st.nextToken());
bounds.x = Integer.parseInt(st.nextToken());
bounds.height -= (bounds.y + Integer.parseInt(st.nextToken()));
bounds.width -= (bounds.x + Integer.parseInt(st.nextToken()));
} catch (NumberFormatException ex) {
Logger.getAnonymousLogger().log(Level.WARNING, null, ex);
}
}
return bounds;
}
str = System.getProperty("netbeans.taskbar.height"); // NOI18N
if (str != null) {
bounds.height -= Integer.getInteger(str, 0).intValue();
return bounds;
}
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Insets insets = toolkit.getScreenInsets(gconf);
bounds.y += insets.top;
bounds.x += insets.left;
bounds.height -= (insets.top + insets.bottom);
bounds.width -= (insets.left + insets.right);
} catch (Exception ex) {
Logger.getAnonymousLogger().log(Level.WARNING, null, ex);
}
return bounds;
}
/** Initialization of the names and values
* @return array of two hashmaps first maps
* allowed key names to their values (String, Integer)
* and second
* hashtable for mapping of values to their names (Integer, String)
*/
private static synchronized HashMap[] initNameAndValues() {
if (namesAndValues != null) {
HashMap[] arr = (HashMap[]) namesAndValues.get();
if (arr != null) {
return arr;
}
}
Field[] fields;
// JW - fix Issue #353-swingx: play nicer inside sandbox.
try {
fields = KeyEvent.class.getDeclaredFields();
// fields = KeyEvent.class.getFields();
} catch (SecurityException e) {
// JW: need to do better? What are the use-cases where we don"t have
// any access to the fields?
fields = new Field[0];
}
HashMap<String,Integer> names = new HashMap<String,Integer>(((fields.length * 4) / 3) + 5, 0.75f);
HashMap<Integer,String> values = new HashMap<Integer,String>(((fields.length * 4) / 3) + 5, 0.75f);
for (int i = 0; i < fields.length; i++) {
if (Modifier.isStatic(fields[i].getModifiers())) {
String name = fields[i].getName();
if (name.startsWith("VK_")) { // NOI18N
// exclude VK
name = name.substring(3);
try {
int numb = fields[i].getInt(null);
Integer value = new Integer(numb);
names.put(name, value);
values.put(value, name);
} catch (IllegalArgumentException ex) {
} catch (IllegalAccessException ex) {
}
}
}
}
if (names.get("CONTEXT_MENU") == null) { // NOI18N
Integer n = new Integer(0x20C);
names.put("CONTEXT_MENU", n); // NOI18N
values.put(n, "CONTEXT_MENU"); // NOI18N
n = new Integer(0x20D);
names.put("WINDOWS", n); // NOI18N
values.put(n, "WINDOWS"); // NOI18N
}
HashMap[] arr = { names, values };
namesAndValues = new SoftReference<Object>(arr);
return arr;
}
/** Converts a Swing key stroke descriptor to a familiar Emacs-like name.
* @param stroke key description
* @return name of the key (e.g. CS-F1
for control-shift-function key one)
* @see #stringToKey
*/
public static String keyToString(KeyStroke stroke) {
StringBuffer sb = new StringBuffer();
// add modifiers that must be pressed
if (addModifiers(sb, stroke.getModifiers())) {
sb.append("-");
}
HashMap[] namesAndValues = initNameAndValues();
String c = (String) namesAndValues[1].get(new Integer(stroke.getKeyCode()));
if (c == null) {
sb.append(stroke.getKeyChar());
} else {
sb.append(c);
}
return sb.toString();
}
/** Construct a new key description from a given universal string
* description.
* Provides mapping between Emacs-like textual key descriptions and the
* KeyStroke
object used in Swing.
* <P>
* This format has following form:
* <P>[C][A][S][M]-identifier
* <p>Where:
*
-
*
-
C
stands for the Control key * -
A
stands for the Alt key * -
S
stands for the Shift key * -
M
stands for the Meta key *
* The format also supports two wildcard codes, to support differences in * platforms. These are the preferred choices for registering keystrokes, * since platform conflicts will automatically be handled:*
-
*
-
D
stands for the default menu accelerator - the Control * key on most platforms, the Command (meta) key on Macintosh
* -
O
stands for the alternate accelerator - the Alt key on * most platforms, the Ctrl key on Macintosh (Macintosh uses Alt as a * secondary shift key for composing international characters - if you bind * Alt-8 to an action, a mac user with a French keyboard will not be able * to type the[
character, which is a significant handicap
*
* If you use the wildcard characters, and specify a key which will conflict * with keys the operating system consumes, it will be mapped to whichever * choice can work - for example, on Macintosh, Command-Q is always consumed * by the operating system, soD-Q
will always map to Control-Q. * <p> * Every modifier before the hyphen must be pressed. * identifier can be any text constant from {@link KeyEvent} but * without the leadingVK_
characters. So {@link KeyEvent#VK_ENTER} is described as *ENTER
. * * @param s the string with the description of the key * @return key description object, ornull
if the string does not represent any valid key */ public static KeyStroke stringToKey(String s) { StringTokenizer st = new StringTokenizer(s.toUpperCase(Locale.ENGLISH), "-", true); // NOI18N int needed = 0; HashMap names = initNameAndValues()[0]; int lastModif = -1; try { for (;;) { String el = st.nextToken(); // required key if (el.equals("-")) { // NOI18N if (lastModif != -1) { needed |= lastModif; lastModif = -1; } continue; } // if there is more elements if (st.hasMoreElements()) { // the text should describe modifiers lastModif = readModifiers(el); } else { // last text must be the key code Integer i = (Integer) names.get(el); boolean wildcard = (needed & CTRL_WILDCARD_MASK) != 0; //Strip out the explicit mask - KeyStroke won"t know //what to do with it needed = needed & ~CTRL_WILDCARD_MASK; boolean macAlt = (needed & ALT_WILDCARD_MASK) != 0; needed = needed & ~ALT_WILDCARD_MASK; if (i != null) { //#26854 - Default accelerator should be Command on mac if (wildcard) { needed |= getMenuShortCutKeyMask(); if ((getOperatingSystem() & OS_MAC) != 0) { if (!usableKeyOnMac(i.intValue(), needed)) { needed &= ~getMenuShortCutKeyMask(); needed |= KeyEvent.CTRL_MASK; } } } if (macAlt) { if (getOperatingSystem() == OS_MAC) { needed |= KeyEvent.CTRL_MASK; } else { needed |= KeyEvent.ALT_MASK; } } return KeyStroke.getKeyStroke(i.intValue(), needed); } else { return null; } } } } catch (NoSuchElementException ex) { return null; } } /** * need to guard against headlessExceptions when testing. * @return the acceletor mask for shortcuts. */ private static int getMenuShortCutKeyMask() { if (GraphicsEnvironment.isHeadless()) { return ((getOperatingSystem() & OS_MAC) != 0) ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK; } return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } private static boolean usableKeyOnMac(int key, int mask) { //All permutations fail for Q except ctrl if (key == KeyEvent.VK_Q) { return false; } boolean isMeta = ((mask & KeyEvent.META_MASK) != 0) || ((mask & KeyEvent.CTRL_DOWN_MASK) != 0); boolean isAlt = ((mask & KeyEvent.ALT_MASK) != 0) || ((mask & KeyEvent.ALT_DOWN_MASK) != 0); boolean isOnlyMeta = isMeta && ((mask & ~(KeyEvent.META_DOWN_MASK | KeyEvent.META_MASK)) == 0); //Mac OS consumes keys Command+ these keys - the app will never see //them, so CTRL should not be remapped for these if (isOnlyMeta) { return (key != KeyEvent.VK_H) && (key != KeyEvent.VK_SPACE) && (key != KeyEvent.VK_TAB); } else return !((key == KeyEvent.VK_D) && isMeta && isAlt); } /** Convert a space-separated list of Emacs-like key binding names to a list of Swing key strokes. * @param s the string with keys * @return array of key strokes, ornull
if the string description is not valid * @see #stringToKey */ public static KeyStroke[] stringToKeys(String s) { StringTokenizer st = new StringTokenizer(s.toUpperCase(Locale.ENGLISH), " "); // NOI18N ArrayList<KeyStroke> arr = new ArrayList<KeyStroke>(); while (st.hasMoreElements()) { s = st.nextToken(); KeyStroke k = stringToKey(s); if (k == null) { return null; } arr.add(k); } return arr.toArray(new KeyStroke[arr.size()]); } /** Adds characters for modifiers to the buffer. * @param buf buffer to add to * @param modif modifiers to add (KeyEvent.XXX_MASK) * @return true if something has been added */ private static boolean addModifiers(StringBuffer buf, int modif) { boolean b = false; if ((modif & KeyEvent.CTRL_MASK) != 0) { buf.append("C"); // NOI18N b = true; } if ((modif & KeyEvent.ALT_MASK) != 0) { buf.append("A"); // NOI18N b = true; } if ((modif & KeyEvent.SHIFT_MASK) != 0) { buf.append("S"); // NOI18N b = true; } if ((modif & KeyEvent.META_MASK) != 0) { buf.append("M"); // NOI18N b = true; } if ((modif & CTRL_WILDCARD_MASK) != 0) { buf.append("D"); b = true; } if ((modif & ALT_WILDCARD_MASK) != 0) { buf.append("O"); b = true; } return b; } /** Reads for modifiers and creates integer with required mask. * @param s string with modifiers * @return integer with mask * @exception NoSuchElementException if some letter is not modifier */ private static int readModifiers(String s) throws NoSuchElementException { int m = 0; for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case "C": m |= KeyEvent.CTRL_MASK; break; case "A": m |= KeyEvent.ALT_MASK; break; case "M": m |= KeyEvent.META_MASK; break; case "S": m |= KeyEvent.SHIFT_MASK; break; case "D": m |= CTRL_WILDCARD_MASK; break; case "O": m |= ALT_WILDCARD_MASK; break; default: throw new NoSuchElementException(s); } } return m; }
}
</source>
Platform specific functionality.
<source lang="java">
import java.awt.Frame; import java.lang.reflect.Method; /**
* Platform specific functionality. * * @author * @version $Id: Platform.java 582434 2007-10-06 02:11:51Z cam $ */
public abstract class Platform {
/** * Whether we are running on Mac OS X. */ public static boolean isOSX = System.getProperty("os.name").equals("Mac OS X"); /** * Whether we are running on JRE 1.3. */ public static boolean isJRE13 = System.getProperty("java.version").startsWith("1.3"); /** * Unmaximizes the specified Frame. */ public static void unmaximize(Frame f) { if (!isJRE13) { try { Method m1 = Frame.class.getMethod("getExtendedState", (Class[]) null); Method m2 = Frame.class.getMethod("setExtendedState", new Class[] { Integer.TYPE }); int i = ((Integer) m1.invoke(f, (Object[]) null)).intValue(); m2.invoke(f, new Object[] { new Integer(i & ~6) }); } catch (java.lang.reflect.InvocationTargetException ite) { } catch (NoSuchMethodException nsme) { } catch (IllegalAccessException iae) { } } }
}
</source>
Splits apart a OS separator delimited set of paths in a string into multiple Strings.
<source lang="java">
import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*
* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */
/**
* Various string manipulation methods that are more efficient then chaining * string operations: all is done in the same buffer without creating a bunch of * string objects. * * @author */
public class Main {
/** * Splits apart a OS separator delimited set of paths in a string into * multiple Strings. File component path strings are returned within a List * in the order they are found in the composite path string. Optionally, a * file filter can be used to filter out path strings to control the * components returned. If the filter is null all path components are * returned. * * @param paths * a set of paths delimited using the OS path separator * @param filter * a FileFilter used to filter the return set * @return the filter accepted path component Strings in the order * encountered */ public static final List getPaths( String paths, FileFilter filter ) { int start = 0; int stop = -1; String path = null; ArrayList<String> list = new ArrayList<String>(); // Abandon with no values if paths string is null if ( paths == null || paths.trim().equals( "" ) ) { return list; } final int max = paths.length() - 1; // Loop spliting string using OS path separator: terminate // when the start index is at the end of the paths string. while ( start < max ) { stop = paths.indexOf( File.pathSeparatorChar, start ); // The is no file sep between the start and the end of the string if ( stop == -1 ) { // If we have a trailing path remaining without ending separator if ( start < max ) { // Last path is everything from start to the string"s end path = paths.substring( start ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the // path only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } } break; // Exit loop no more path components left! } // There is a separator between start and the end if we got here! // start index is now at 0 or the index of last separator + 1 // stop index is now at next separator in front of start index path = paths.substring( start, stop ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the path // only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } // Advance start index past separator to start of next path comp start = stop + 1; } return list; }
}
</source>