File: OSUtilities.java

package info (click to toggle)
libsis-base-java 18.09~pre1%2Bgit20180928.45fbd31%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,292 kB
  • sloc: java: 9,037; ansic: 813; xml: 160; sh: 139; makefile: 37
file content (257 lines) | stat: -rw-r--r-- 8,225 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
 * Copyright 2007 - 2018 ETH Zuerich, CISD and SIS.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.systemsx.cisd.base.utilities;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Some useful methods related to the operating system.
 * <p>
 * Does <em>not</em> depend on any library jar files. But before using or extending this class and
 * if you do not mind using <a href="http://jakarta.apache.org/commons/lang/">commons lang</a>, then
 * have a look on <code>SystemUtils</code>.
 * </p>
 * 
 * @author Bernd Rinn
 */
public class OSUtilities
{

    /** Platform specific line separator. */
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");

    /**
     * @return <code>true</code> if the operating system is UNIX like.
     */
    public static boolean isUnix()
    {
        return (File.separatorChar == '/');
    }

    /**
     * @return <code>true</code> if the operating system is a MS Windows type.
     */
    public static boolean isWindows()
    {
        return (File.separatorChar == '\\');
    }

    /**
     * @return <code>true</code> if the the operating system is a flavor of Mac OS X.
     */
    public static boolean isMacOS()
    {
        return "Mac OS X".equals(System.getProperty("os.name"));
    }

    /**
     * @return The name of the computer platform that is compatible with respect to executables (CPU
     *         architecture and OS name, both as precise as possible to be able to share libraries
     *         and binaries).
     */
    public static String getCompatibleComputerPlatform()
    {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows"))
        {
            osName = "Windows";
        }
        return System.getProperty("os.arch") + "-" + osName;
    }

    /**
     * @return The name of the CPU architecture.
     */
    public static String getCPUArchitecture()
    {
        return System.getProperty("os.arch");
    }

    /**
     * @return The name of the operating system.
     */
    public static String getOSName()
    {
        return System.getProperty("os.name");
    }

    /**
     * @return The name of the computer platform (CPU architecture and OS name).
     */
    public static String getComputerPlatform()
    {
        return System.getProperty("os.arch") + "-" + System.getProperty("os.name");
    }

    /**
     * @return The name of user that runs this program.
     */
    public static String getUsername()
    {
        return System.getProperty("user.name");
    }

    /**
     * @return <code>true</code> if the user that runs this program is known to have root privileges
     *         (based on his name).
     */
    public static boolean isRoot()
    {
        if (isUnix())
        {
            return "root".equals(getUsername());
        } else
        {
            return "Administrator".equals(getUsername());
        }
    }

    /**
     * @return The <var>PATH</var> as provided by the operating system.
     */
    public static Set<String> getOSPath()
    {
        final String[] pathEntries =
                System.getenv("PATH").split(Pattern.quote(System.getProperty("path.separator")));
        return new LinkedHashSet<String>(Arrays.asList(pathEntries));
    }

    /**
     * @param root Whether the path should be prepared for root or not.
     * @return The path as provided by the operating system plus some path entries that should
     *         always be available.
     * @see #getOSPath()
     */
    public static Set<String> getSafeOSPath(boolean root)
    {
        final Set<String> pathEntries = getOSPath();
        if (isUnix())
        {
            if (isMacOS())
            {
                pathEntries.add("/opt/local/bin"); // MacPorts
                pathEntries.add("/sw/bin"); // Fink
                if (root)
                {
                    pathEntries.add("/opt/local/sbin");
                    pathEntries.add("/sw/sbin");
                }
            }
            pathEntries.add("/usr/local/bin");
            pathEntries.add("/usr/bin");
            pathEntries.add("/bin");
            if (root)
            {
                pathEntries.add("/usr/local/sbin");
                pathEntries.add("/usr/sbin");
                pathEntries.add("/sbin");
            }
        }
        return pathEntries;
    }

    /**
     * Convenience method for {@link #getSafeOSPath(boolean)} with <code>root=false</code>.
     * 
     * @return The path as provided by the operating system plus some path entries that should
     *         always be available.
     * @see #getSafeOSPath(boolean)
     */
    public static Set<String> getSafeOSPath()
    {
        return getSafeOSPath(false);
    }

    /**
     * Search for the binary program with name <code>binaryName</code> in the operating system
     * path..
     * 
     * @param executableName The name of the executable to search for. Under Windows, a name with
     *            and without <code>.exe</code> appended will work, but the executable found needs
     *            to have the .exe extension.
     * @return The binary file that has been found in the path, or <code>null</code>, if no binary
     *         file could be found.
     */
    public static File findExecutable(String executableName)
    {
        return OSUtilities.findExecutable(executableName, getSafeOSPath());
    }

    /**
     * Search for the binary program with name <code>binaryName</code> in the set of paths denoted
     * by <code>pathSet</code>.
     * 
     * @param executableName The name of the executable to search for. Under Windows, a name with
     *            and without <code>.exe</code> appended will work, but the executable found needs
     *            to have the .exe extension.
     * @param pathSet The set of paths to search for. It is recommended to use an ordered set like
     *            the {@link LinkedHashSet} here in order to get results that are independent of the
     *            JRE implementation.
     * @return The binary file that has been found in the path, or <code>null</code>, if no binary
     *         file could be found.
     */
    public static File findExecutable(String executableName, Set<String> pathSet)
    {
        final String executableNameWithExtension =
                addWindowsExecutableExtensionIfNecessary(executableName);
        for (String dir : pathSet)
        {
            final File fileToCheck = new File(dir, executableNameWithExtension);
            if (fileToCheck.exists())
            {
                return fileToCheck;
            }
        }
        return null;
    }

    /**
     * @return <code>true</code> if and only if an executable of name <var>executableName</var>
     *         exists.
     */
    public static boolean executableExists(String executableName)
    {
        return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executableName)))
                .exists();
    }

    /**
     * @return <code>true</code> if and only if an executable of name <var>executableName</var>
     *         exists.
     */
    public static boolean executableExists(File executable)
    {
        return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executable.getPath())))
                .exists();
    }

    private static String addWindowsExecutableExtensionIfNecessary(String executableName)
    {
        if (isWindows() && executableName.indexOf('.') < 0)
        {
            return executableName + ".exe";
        } else
        {
            return executableName;
        }
    }

}