下面列出了怎么用org.apache.commons.lang.SystemUtils的API类实例代码及写法,或者点击链接到github查看源代码。
public static synchronized DialectFactory getInstance() {
if (me == null) {
me = new DialectFactory();
me.registerDialect(new DB2Dialect());
me.registerDialect(new MSSQLDialect());
me.registerDialect(new MySQLDialect());
me.registerDialect(new MySQLInnoDBDialect());
me.registerDialect(new OracleDialect());
me.registerDialect(new PostgresDialect());
me.registerDialect(new H2Dialect());
me.registerDialect(new HSQLDBDialect());
// provide MSAccessDialect only on Windows-Systems due to the
// requirement of the JET/ACE-Engine
if (SystemUtils.IS_OS_WINDOWS) {
me.registerDialect(new MSAccessDialect());
}
}
return me;
}
private void addFilePermissions(File file) throws IOException {
Set<PosixFilePermission> filePermissions = new HashSet<>();
filePermissions.add(PosixFilePermission.OWNER_READ);
File[] fileChildren = file.listFiles();
if (fileChildren != null) {
for (File child : fileChildren) {
if (SystemUtils.IS_OS_WINDOWS) {
child.setReadOnly();
} else {
Files.setPosixFilePermissions(child.toPath(), filePermissions);
}
}
}
}
public static Process createProcess(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.redirectErrorStream(true);
Process process = null;
try {
if (SystemUtils.IS_OS_LINUX) {
processBuilder.command("bash", "-c", command);
} else if (SystemUtils.IS_OS_WINDOWS) {
processBuilder.command("cmd.exe", "-c", command);
}
process = processBuilder.start();
} catch (IOException e) {
System.out.println("New process could not be created: " + e.getLocalizedMessage());
}
return process;
}
@Test
public void executeWithOutputInterpreter() {
Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
Script script = new Script("/bin/bash");
script.add("-c");
script.add("echo 'hello world!'");
String value = script.execute(new OutputInterpreter() {
@Override
public String interpret(BufferedReader reader) throws IOException {
throw new IllegalArgumentException();
}
});
// it is a stack trace in this case as string
Assert.assertNotNull(value);
}
public ResultEntity uploads(String category, String version, String type, MultipartFile jarFile) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentDispositionFormData("jarFile", jarFile.getOriginalFilename());
MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
File saveDir = new File(SystemUtils.getJavaIoTmpDir(), String.valueOf(System.currentTimeMillis()));
if (!saveDir.exists()) saveDir.mkdirs();
File tempFile = new File(saveDir, jarFile.getOriginalFilename());
jarFile.transferTo(tempFile);
FileSystemResource fsr = new FileSystemResource(tempFile);
data.add("jarFile", fsr);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(data, headers);
URLBuilder urlBulider = new URLBuilder(ServiceNames.KEEPER_SERVICE, "/jars/uploads/{0}/{1}/{2}");
ResponseEntity<ResultEntity> result = rest.postForEntity(urlBulider.build(), entity, ResultEntity.class, version, type, category);
if (tempFile.exists()) tempFile.delete();
if (saveDir.exists()) saveDir.delete();
return result.getBody();
}
/**
* Copies the HADOOP_HOME bin directory to the {@link MiniAccumuloCluster} temp directory.
* {@link MiniAccumuloCluster} expects to find bin/winutils.exe in the MAC temp
* directory instead of HADOOP_HOME for some reason.
* @throws IOException
*/
private void copyHadoopHomeToTemp() throws IOException {
if (IS_COPY_HADOOP_HOME_ENABLED && SystemUtils.IS_OS_WINDOWS) {
final String hadoopHomeEnv = PathUtils.clean(System.getenv("HADOOP_HOME"));
if (hadoopHomeEnv != null) {
final File hadoopHomeDir = new File(hadoopHomeEnv);
if (hadoopHomeDir.exists()) {
final File binDir = Paths.get(hadoopHomeDir.getAbsolutePath(), "/bin").toFile();
if (binDir.exists()) {
FileUtils.copyDirectoryToDirectory(binDir, tempDir);
} else {
log.warn("The specified path for the Hadoop bin directory does not exist: " + binDir.getAbsolutePath());
}
} else {
log.warn("The specified path for HADOOP_HOME does not exist: " + hadoopHomeDir.getAbsolutePath());
}
} else {
log.warn("The HADOOP_HOME environment variable was not found.");
}
}
}
@Override
public void run() {
try {
String line = br.readLine();
while (StringUtils.isNotBlank(line)) {
if (session != null)
session.getBasicRemote().sendText(line);
if (smt != null)
smt.convertAndSendToUser(uid, "/log", line);
sb.append(line);
sb.append(SystemUtils.LINE_SEPARATOR);
line = br.readLine();
}
} catch (Exception e) {
logger.error("stream runnable error", e);
} finally {
close(br);
close(reader);
}
}
/**
* <p>Produces a <code>List</code> of stack frames - the message
* is not included. Only the trace of the specified exception is
* returned, any caused by trace is stripped.</p>
*
* <p>This works in most cases - it will only fail if the exception
* message contains a line that starts with:
* <code>" at".</code></p>
*
* @param t is any throwable
* @return List of stack frames
*/
static List getStackFrameList(Throwable t) {
String stackTrace = getStackTrace(t);
String linebreak = SystemUtils.LINE_SEPARATOR;
StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
List list = new ArrayList();
boolean traceStarted = false;
while (frames.hasMoreTokens()) {
String token = frames.nextToken();
// Determine if the line starts with <whitespace>at
int at = token.indexOf("at");
if (at != -1 && token.substring(0, at).trim().length() == 0) {
traceStarted = true;
list.add(token);
} else if (traceStarted) {
break;
}
}
return list;
}
/**
* checks for correct configuration, and translates the fileName to
* a file, to check existence.
* If a fileName was specified, the contents of the file is put in the
* <code>returnString</code>, so that allways the <code>returnString</code>
* may be returned.
* @throws ConfigurationException
*/
@Override
public void configure() throws ConfigurationException {
super.configure();
if (StringUtils.isNotEmpty(fileName)) {
try {
returnString = Misc.resourceToString(ClassUtils.getResourceURL(getConfigurationClassLoader(), fileName), SystemUtils.LINE_SEPARATOR);
} catch (Throwable e) {
throw new ConfigurationException("Pipe [" + getName() + "] got exception loading ["+fileName+"]", e);
}
}
if ((StringUtils.isEmpty(fileName)) && returnString==null) { // allow an empty returnString to be specified
throw new ConfigurationException("Pipe [" + getName() + "] has neither fileName nor returnString specified");
}
if (StringUtils.isNotEmpty(replaceFrom)) {
returnString = replace(returnString, replaceFrom, replaceTo );
}
}
private void commitFile(String dirName, String fileName, boolean longpathsEnabled) throws Exception {
assertTrue("Didn't mkdir " + dirName, w.file(dirName).mkdir());
String fullName = dirName + File.separator + fileName;
w.touch(fullName, fullName + " content " + UUID.randomUUID().toString());
boolean shouldThrow = !longpathsEnabled &&
SystemUtils.IS_OS_WINDOWS &&
w.git instanceof CliGitAPIImpl &&
w.cgit().isAtLeastVersion(1, 9, 0, 0) &&
!w.cgit().isAtLeastVersion(2, 8, 0, 0) &&
(new File(fullName)).getAbsolutePath().length() > MAX_PATH;
try {
w.git.add(fullName);
w.git.commit("commit-" + fileName);
assertFalse("unexpected success " + fullName, shouldThrow);
} catch (GitException ge) {
assertEquals("Wrong message", "Cannot add " + fullName, ge.getMessage());
}
assertTrue("file " + fullName + " missing at commit", w.file(fullName).exists());
}
/**
* Create the documentation to provide an developer access with a
* <code>Perforce</code> SCM. For example, generate the following command
* line:
* <p>
* p4 -H hostname -p port -u username -P password path
* </p>
* <p>
* p4 -H hostname -p port -u username -P password path submit -c changement
* </p>
*
* @param perforceRepo
* @see <a
* href="http://www.perforce.com/perforce/doc.051/manuals/cmdref/index.html">http://www.perforce.com/
* perforce /doc.051/manuals/cmdref/index.html</>
*/
// CHECKSTYLE_ON: LineLength
private void developerAccessPerforce(PerforceScmProviderRepository perforceRepo) {
paragraph(getI18nString("devaccess.perforce.intro"));
StringBuilder command = new StringBuilder();
command.append("$ p4");
if (!StringUtils.isEmpty(perforceRepo.getHost())) {
command.append(" -H ").append(perforceRepo.getHost());
}
if (perforceRepo.getPort() > 0) {
command.append(" -p ").append(perforceRepo.getPort());
}
command.append(" -u username");
command.append(" -P password");
command.append(" ");
command.append(perforceRepo.getPath());
command.append(SystemUtils.LINE_SEPARATOR);
command.append("$ p4 submit -c \"A comment\"");
verbatimText(command.toString());
}
public static HdfsConfiguration initZeroCopyTest() {
Assume.assumeTrue(NativeIO.isAvailable());
Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
HdfsConfiguration conf = new HdfsConfiguration();
conf.setBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, true);
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
conf.setInt(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE, 3);
conf.setLong(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS, 100);
conf.set(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
new File(sockDir.getDir(),
"TestRequestMmapAccess._PORT.sock").getAbsolutePath());
conf.setBoolean(DFSConfigKeys.
DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY, true);
conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1);
conf.setLong(DFS_CACHEREPORT_INTERVAL_MSEC_KEY, 1000);
conf.setLong(DFS_NAMENODE_PATH_BASED_CACHE_REFRESH_INTERVAL_MS, 1000);
return conf;
}
/**
* <p>Produces a <code>List</code> of stack frames - the message
* is not included. Only the trace of the specified exception is
* returned, any caused by trace is stripped.</p>
*
* <p>This works in most cases - it will only fail if the exception
* message contains a line that starts with:
* <code>" at".</code></p>
*
* @param t is any throwable
* @return List of stack frames
*/
static List getStackFrameList(Throwable t) {
String stackTrace = getStackTrace(t);
String linebreak = SystemUtils.LINE_SEPARATOR;
StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
List list = new ArrayList();
boolean traceStarted = false;
while (frames.hasMoreTokens()) {
String token = frames.nextToken();
// Determine if the line starts with <whitespace>at
int at = token.indexOf("at");
if (at != -1 && token.substring(0, at).trim().length() == 0) {
traceStarted = true;
list.add(token);
} else if (traceStarted) {
break;
}
}
return list;
}
@UnstableAPI
public static int getUnixFileMode(final Path path) {
try {
int unixMode = (int) Files.readAttributes(path, "unix:mode").get("mode");
// Truncate mode bits for z/OS
if ("OS/390".equals(SystemUtils.OS_NAME) ||
"z/OS".equals(SystemUtils.OS_NAME) ||
"zOS".equals(SystemUtils.OS_NAME) ) {
unixMode &= TarConstants.MAXID;
unixMode |= Files.isDirectory(path) ? 040000 : 0100000;
}
return unixMode;
} catch (IOException | UnsupportedOperationException e) {
// fallback for non-posix environments
int mode = DEFAULT_FILE_MODE;
if (Files.isDirectory(path)) {
mode = DEFAULT_DIR_MODE;
} else if (Files.isExecutable(path)) {
mode |= 0111; // equiv to +x for user/group/others
}
return mode;
}
}
@Test
public void executeWithOutputInterpreter() {
Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
final Script script = new Script("/bin/bash");
script.add("-c");
script.add("echo 'hello world!'");
final String value = script.execute(new OutputInterpreter() {
@Override
public String interpret(final BufferedReader reader) throws IOException {
throw new IllegalArgumentException();
}
});
// it is a stack trace in this case as string
Assert.assertNotNull(value);
}
public static String findAtoumBinPath(VirtualFile dir)
{
String defaultBinPath = dir.getPath() + "/vendor/bin/atoum";
String atoumBinPath = defaultBinPath;
String binDir = getComposerBinDir(dir.getPath() + "/composer.json");
String binPath = dir.getPath() + "/" + binDir + "/atoum";
if (null != binDir && new File(binPath).exists()) {
atoumBinPath = binPath;
}
if (SystemUtils.IS_OS_WINDOWS) {
atoumBinPath += ".bat";
}
return atoumBinPath;
}
/**
* Note: we only support 64 bit Java on x86 and AMD machine
*
* @return true if the hardware architecture is supported
*/
private static boolean isSupportedArchitecture() {
if(SystemUtils.OS_ARCH.equals("x86_64") || SystemUtils.OS_ARCH.equals("amd64")) {
return true;
}
LOG.info("Unsupported architecture for native BLAS:" + SystemUtils.OS_ARCH);
return false;
}
public void testIsThrowableNested() {
if (SystemUtils.isJavaVersionAtLeast(140)) {
assertEquals(true, ExceptionUtils.isThrowableNested());
} else {
assertEquals(false, ExceptionUtils.isThrowableNested());
}
}
/**
* @param url
* @return
* @throws IOException
*/
public static String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.header("user-agent", String.format("RB/%s (%s/%s)", Application.VER, SystemUtils.OS_NAME, SystemUtils.JAVA_SPECIFICATION_VERSION))
.build();
try (Response response = getHttpClient().newCall(request).execute()) {
return Objects.requireNonNull(response.body()).string();
}
}
/**
* @param msgs
* @return
*/
protected static String formatBootMsg(String...msgs) {
List<String> msgsList = new ArrayList<>();
CollectionUtils.addAll(msgsList, msgs);
msgsList.add("\n Version : " + VER);
msgsList.add("OS : " + SystemUtils.OS_NAME + " " + SystemUtils.OS_ARCH);
msgsList.add("Report an issue :");
msgsList.add("https://getrebuild.com/report-issue?title=boot");
return "\n###################################################################\n\n "
+ StringUtils.join(msgsList, "\n ") +
"\n\n###################################################################";
}
/**
* Where everything starts. Takes in, and tries to parse as many commandline arguments as possible.
* Otherwise, it launches a GUI.
*
* @param args Array of command line arguments.
*/
public static void main(String[] args) throws MalformedURLException {
CommandLine cl = getArgs(args);
if (args.length > 0 && cl.hasOption('v')){
logger.info(UpdateUtils.getThisJarVersion());
System.exit(0);
}
if (Utils.getConfigString("proxy.http", null) != null) {
Proxy.setHTTPProxy(Utils.getConfigString("proxy.http", null));
} else if (Utils.getConfigString("proxy.socks", null) != null) {
Proxy.setSocks(Utils.getConfigString("proxy.socks", null));
}
// This has to be here instead of handleArgs because handleArgs isn't parsed until after a item is ripper
if (cl.hasOption("a")) {
logger.info(cl.getOptionValue("a"));
stringToAppendToFoldername = cl.getOptionValue("a");
}
if (GraphicsEnvironment.isHeadless() || args.length > 0) {
handleArguments(args);
} else {
if (SystemUtils.IS_OS_MAC_OSX) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "RipMe");
}
Utils.configureLogger();
logger.info("Initialized ripme v" + UpdateUtils.getThisJarVersion());
MainWindow mw = new MainWindow();
SwingUtilities.invokeLater(mw);
}
}
public int sendBatchMessages(List<StatMessage> list, long retryTimes) throws IOException {
StringBuilder contents = new StringBuilder();
int idx = 0;
for (StatMessage entry : list) {
contents.append(statMessageToLineProtocol(entry.getOffset(), entry));
if (idx < list.size())
contents.append(SystemUtils.LINE_SEPARATOR);
idx++;
}
LOG.info(String.format("submit influx batch size=%s content=%s", list.size(), contents.toString().length()));
int ret = sendMessage(contents.toString(), retryTimes);
return ret;
}
@BeforeClass
public static void setUpBeforeClass() {
// set the NO_EVENT_TIMEOUT_IN_SECONDS according to the operating system used
if (SystemUtils.IS_OS_MAC_OSX) {
NO_EVENT_TIMEOUT_IN_SECONDS = 15;
} else {
NO_EVENT_TIMEOUT_IN_SECONDS = 3;
}
}
/**
* Tests for consistency between the two methods for getting environment variables
* in EnvUtilities calling getEnv(String) and calling getEnv().getProperty(String).
*/
public void testGetEnvironmentConsistency() {
//Test if an only if HOME and USER is defined (Assumed to be true on unix)
if (SystemUtils.IS_OS_UNIX) {
Properties env = EnvUtilities.getEnv();
//Test values
String userHomeTest1 = env.getProperty("HOME");
String userNameTest1 = env.getProperty("USER");
String userHomeTest2 = EnvUtilities.getEnv("HOME");
String userNameTest2 = EnvUtilities.getEnv("USER");
//Check all three tests
assertEquals(userHomeTest1,userHomeTest2);
assertEquals(userNameTest1,userNameTest2);
}
}
/**
* Converts the path into cygwin notation on Windows platform.
*
* @param path the path to convert
* @return the (potentially) converted path
*/
public static String convertPath(String path) {
String result;
result = path;
if (SystemUtils.IS_OS_WINDOWS) {
result = result.replace("\\", "/");
if (result.matches("^[a-zA-Z]:.*"))
result = "/cygdrive/" + result.substring(0, 1).toLowerCase() + "/" + result.substring(2);
}
return result;
}
@Test
public void testAsURI_Linux_CreatedAsFile() throws Exception {
if (SystemUtils.IS_OS_LINUX) {
final Properties props = new Properties();
props.put("Kõik või", "tere");
final MMapURI uri = new MMapURI(null, new File("/Kõik/või/mitte/midagi.txt"), props);
assertEquals(new URI("file:///K%C3%B5ik/v%C3%B5i/mitte/midagi.txt?K%C3%B5ik+v%C3%B5i=tere"), uri.asURI());
assertEquals("tere", uri.getParameters().getProperty("Kõik või"));
assertEquals(new File("/Kõik/või/mitte/midagi.txt"), uri.asFile(null));
}
}
@Test
public void testMariaDBWithCustomIniFile() throws SQLException {
assumeFalse(SystemUtils.IS_OS_WINDOWS);
try (MariaDBContainer<?> mariadbCustomConfig = new MariaDBContainer<>("mariadb:10.1.16")
.withConfigurationOverride("somepath/mariadb_conf_override")) {
mariadbCustomConfig.start();
ResultSet resultSet = performQuery(mariadbCustomConfig, "SELECT @@GLOBAL.innodb_file_format");
String result = resultSet.getString(1);
assertEquals("The InnoDB file format has been set by the ini file content", "Barracuda", result);
}
}
public void testAppendNewLine() {
StrBuilder sb = new StrBuilder("---");
sb.appendNewLine().append("+++");
assertEquals("---" + SystemUtils.LINE_SEPARATOR + "+++", sb.toString());
sb = new StrBuilder("---");
sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine();
assertEquals("---#" + SystemUtils.LINE_SEPARATOR, sb.toString());
}
@Test(timeout=60000)
public void testInstall() throws Exception {
Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
SignalLogger.INSTANCE.register(LOG);
try {
SignalLogger.INSTANCE.register(LOG);
Assert.fail("expected IllegalStateException from double registration");
} catch (IllegalStateException e) {
// fall through
}
}
@Issue("JENKINS-21168")
private void checkSymlinkSetting(WorkingArea area) throws IOException {
String expected = SystemUtils.IS_OS_WINDOWS ? "false" : "";
String symlinkValue;
try {
symlinkValue = w.launchCommand(true, "git", "config", "core.symlinks").trim();
} catch (Exception e) {
symlinkValue = e.getMessage();
}
assertEquals(expected, symlinkValue);
}