/
SystemUtils.java
403 lines (319 loc) · 11.5 KB
/
SystemUtils.java
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
* MIT License
*
* Copyright (c) 2017 Ralph Niemitz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package de.ralleytn.utils;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
/**
* Provides some helpful methods if you want to get some informations from the system.
* @author Ralph Niemitz/RalleYTN(ralph.niemitz@gmx.de)
*/
public final class SystemUtils {
private SystemUtils() {}
/**
* @return {@code true} if this program runs in a 64Bit Java Virtual Mashine, else {@code false}
*/
public static final boolean is64Bit() {
return System.getProperty("os.arch").contains("64");
}
/**
* @return {@code true} if num lock is activated, else {@code false}
*/
public static final boolean isNumLock() {
return Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_NUM_LOCK);
}
/**
* @return {@code true} if caps lock is activated, else {@code false}
*/
public static final boolean isCapsLock() {
return Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
}
/**
* Emits an audio beep depending on native system settings and hardware capabilities.
*/
public static final void beep() {
Toolkit.getDefaultToolkit().beep();
}
/**
* Adds a directory to the library path. This can get you in trouble with the security manager if you do not
* have full administration rights. The purpose of this method is to load native libraries dynamically without
* having to worry about the platform.
* @param directory the directory name. Can be relative or absolute.
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static final void addDirectoryToLibraryPath(String directory) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
System.setProperty("java.library.path", directory.replace("/", File.separator).replace("\\", File.separator) + ";" + System.getProperty("java.library.path"));
Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
/**
* Gets the value of the specified environment variable. An environment variable is a system-dependent external named value.
* @param name name of the variable
* @return the value of the environment variable
* @throws SecurityException If you do not have the permission to read the given variable
*/
public final String getEnvironmentVariable(String name) throws SecurityException {
return System.getenv(name);
}
/**
* @return an unmodifiable string map view of the current system environment. The environment is a
* system-dependent mapping from names to values which is passed from parent to child processes. If the
* system does not support environment variables, an empty map is returned. The returned map will never
* contain null keys or values.
* @throws SecurityException If you do not have the permission to read environment variables
*/
public final Map<String, String> getEnvironmentVariables() throws SecurityException {
return System.getenv();
}
/**
* Executes the given commands in a batch.
* @param cmd batch of commands
* @return the instance of {@linkplain Process} in which the commands are executed
* @throws IOException if an I/O error occurs
*/
public static final Process execute(String... cmd) throws IOException {
return Runtime.getRuntime().exec(cmd);
}
/**
* Opens the native internet browser
* @param url
* @return
* @throws IOException
* @throws URISyntaxException
*/
public final Process openNativeBrowser(String url) throws IOException, URISyntaxException {
Process process = null;
switch(SystemUtils.getOperatingSystem()) {
case LINUX:
String[] browsers = {
"epiphany",
"firefox",
"mozilla",
"konqueror",
"netscape",
"opera",
"links",
"lynx",
"vivaldi"
};
StringBuffer cmd = new StringBuffer();
for(int index = 0; index < browsers.length; index++) {
cmd.append((index == 0 ? "" : " || " ) + browsers[index] +" \"" + url + "\" ");
}
process = Runtime.getRuntime().exec(new String[] {"sh", "-c", cmd.toString()});
break;
case MAC:
process = Runtime.getRuntime().exec("open " + url);
break;
case WINDOWS:
process = Runtime.getRuntime().exec("cmd /c start " + url);
break;
default:
if(Desktop.isDesktopSupported()) {
if(Desktop.getDesktop().isSupported(Action.BROWSE)) {
Desktop.getDesktop().browse(new URL(url).toURI());
}
}
break;
}
return process;
}
/**
* @return the maximum amount of memory that the virtual machine will attempt to use, measured in bytes
*/
public static final long getMaximumMemory() {
return Runtime.getRuntime().maxMemory();
}
/**
* @return the total amount of memory currently available for current and future objects, measured in bytes
*/
public static final long getTotalMemory() {
return Runtime.getRuntime().totalMemory();
}
/**
* @return an approximation to the total amount of memory currently available for future allocated objects, measured in bytes
*/
public static final long getFreeMemory() {
return Runtime.getRuntime().freeMemory();
}
/**
* @return the maximum number of processors available to the virtual machine; never smaller than one
*/
public static final int getNumberOfProcessors() {
return Runtime.getRuntime().availableProcessors();
}
/**
* @return the {@linkplain GraphicsDevice} object representing the default screen
*/
public static final GraphicsDevice getDefaultScreen() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
/**
* @return an array containing all the {@linkplain GraphicsDevice} objects that represent screen devices
*/
public static final GraphicsDevice[] getScreens() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
}
/**
* @return A {@linkplain Dimension} object containg the screen size of the default screen
*/
public static final Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
/**
* @return a screenshot of the default screen
* @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when {@linkplain GraphicsEnvironment#isHeadless()} returns {@code true}
*/
public static final BufferedImage screenshot() throws AWTException {
Robot robot = new Robot();
Dimension screenSize = SystemUtils.getScreenSize();
return robot.createScreenCapture(new Rectangle(0, 0, screenSize.width, screenSize.height));
}
/**
* @param complete {@code true} if the screenshot should include all screens, {@code false} for the default screen only
* @return a screenshot
* @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when {@linkplain GraphicsEnvironment#isHeadless()} returns {@code true}
*/
public static final BufferedImage screenshot(boolean complete) throws AWTException {
if(complete) {
Rectangle size = new Rectangle();
for(GraphicsDevice screen : SystemUtils.getScreens()) {
size = size.union(screen.getDefaultConfiguration().getBounds());
}
return new Robot().createScreenCapture(size);
}
return SystemUtils.screenshot();
}
/**
* @return the number of buttons on the mouse... duh!
*/
public static final int getNumberOfMouseButtons() {
return MouseInfo.getNumberOfButtons();
}
/**
* @return the {@linkplain GraphicsDevice} object representing the screen the mouse cursor is currently in
*/
public static final GraphicsDevice getScreenWithMouseCursorInIt() {
return MouseInfo.getPointerInfo().getDevice();
}
/**
* @return the position of the mouse cursor
*/
public static final Point getMouseCursorLocation() {
return MouseInfo.getPointerInfo().getLocation();
}
/**
* @return the operating system in which this program is run
*/
public static final OperatingSystem getOperatingSystem() {
String osName = System.getProperty("os.name");
return System.getProperty("java.vendor").toLowerCase().contains("android") ? OperatingSystem.ANDROID : (osName.toLowerCase().contains("win") ? OperatingSystem.WINDOWS : (osName.toLowerCase().contains("mac") ? OperatingSystem.MAC : (osName.toLowerCase().contains("nix") || osName.toLowerCase().contains("nux") ? OperatingSystem.LINUX : (osName.toLowerCase().contains("sunos") ? OperatingSystem.SOLARIS : OperatingSystem.UNKNOWN))));
}
/**
* @return the system language
*/
public static final String getLanguage() {
return System.getProperty("user.language").toUpperCase();
}
/**
* @return the system country
*/
public static final String getCountry() {
return System.getProperty("user.country");
}
/**
* @return a {@linkplain File} object representing the temp directory of the JVM (by default also the system temp directory)
*/
public static final File getTempDirectory() {
return new File(System.getProperty("java.io.tmpdir"));
}
/**
* @return the home directory of the currently logged in user
*/
public static final File getUserHomeDirectory() {
return new File(System.getProperty("user.home"));
}
/**
* @return the name of the currently logged in user
*/
public static final String getUsername() {
return System.getProperty("user.name");
}
/**
* @return the java version with which this program is run
*/
public static final String getJavaVersion() {
return System.getProperty("java.version");
}
/**
* Representing an operating system.
* @author Ralph Niemitz/RalleYTN(ralph.niemitz@gmx.de)
*/
public static enum OperatingSystem {
/**
* Windows
*/
WINDOWS,
/**
* Linux
*/
LINUX,
/**
* Mac OS X
*/
MAC,
/**
* Android
*/
ANDROID,
/**
* Solaris
*/
SOLARIS,
/**
* Unknown
*/
UNKNOWN;
}
}