Java Code Examples for org.apache.commons.lang3.SystemUtils#IS_OS_UNIX

The following examples show how to use org.apache.commons.lang3.SystemUtils#IS_OS_UNIX . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JobsAutoConfiguration.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link ProcessChecker.Factory} suitable for UNIX systems.
 *
 * @param executor       The executor where checks are executed
 * @param jobsProperties The jobs properties
 * @return a {@link ProcessChecker.Factory}
 */
@Bean
@ConditionalOnMissingBean(ProcessChecker.Factory.class)
public ProcessChecker.Factory processCheckerFactory(
    final Executor executor,
    final JobsProperties jobsProperties
) {
    if (SystemUtils.IS_OS_UNIX) {
        return new UnixProcessChecker.Factory(
            executor,
            jobsProperties.getUsers().isRunAsUserEnabled()
        );
    } else {
        throw new BeanCreationException("No implementation available for non-UNIX systems");
    }
}
 
Example 2
Source File: ConfigurationSettings.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @return A default Settings Files Path value.
 */
public static String getDefaultSettingsFilesPath()
{
	String fType;
	if (SystemUtils.IS_OS_MAC_OSX)
	{
		fType = SettingsFilesPath.mac_user.name();
	}
	else if (SystemUtils.IS_OS_UNIX)
	{
		fType = SettingsFilesPath.FD_USER.name();
	}
	else
	{
		fType = SettingsFilesPath.user.name();
	}
	return fType;
}
 
Example 3
Source File: CheckForUpdatesListener.java    From collect-earth with MIT License 6 votes vote down vote up
private String getAutoUpdateExecutable() {
	String autoUpdateExecutable = "autoupdate" ;  //$NON-NLS-1$
	try {
		
		
		if (SystemUtils.IS_OS_WINDOWS){
			autoUpdateExecutable += ".exe"; //$NON-NLS-1$
		}else if (SystemUtils.IS_OS_MAC){
			autoUpdateExecutable += ".app"; //$NON-NLS-1$
		}else if ( SystemUtils.IS_OS_UNIX && System.getProperty("sun.arch.data.model").equals("64")){
			autoUpdateExecutable += "-x64.run"; //$NON-NLS-1$
		}else if ( SystemUtils.IS_OS_UNIX ) {
			autoUpdateExecutable += ".run"; //$NON-NLS-1$
		}

	} catch (Exception e) {
		e.printStackTrace(); // ATTENTION do not use a logger here!
	}
	return autoUpdateExecutable;
}
 
Example 4
Source File: StringUtils.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public static void startupShutdownMessage(VersionInfo versionInfo,
    Class<?> clazz, String[] args, Logger log) {
  final String hostname = NetUtils.getHostname();
  final String className = clazz.getSimpleName();
  if (log.isInfoEnabled()) {
    log.info(createStartupShutdownMessage(versionInfo, className, hostname,
        args));
  }

  if (SystemUtils.IS_OS_UNIX) {
    try {
      SignalLogger.INSTANCE.register(log);
    } catch (Throwable t) {
      log.warn("failed to register any UNIX signal loggers: ", t);
    }
  }
  ShutdownHookManager.get().addShutdownHook(
      () -> log.info(toStartupShutdownString("SHUTDOWN_MSG: ",
          "Shutting down " + className + " at " + hostname)),
      SHUTDOWN_HOOK_PRIORITY);

}
 
Example 5
Source File: ConfigurationSettings.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @return A default Settings Files Path value.
 */
public static String getDefaultSettingsFilesPath()
{
	String fType;
	if (SystemUtils.IS_OS_MAC_OSX)
	{
		fType = SettingsFilesPath.mac_user.name();
	}
	else if (SystemUtils.IS_OS_UNIX)
	{
		fType = SettingsFilesPath.FD_USER.name();
	}
	else
	{
		fType = SettingsFilesPath.user.name();
	}
	return fType;
}
 
Example 6
Source File: OptionsPathDialogController.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@FXML
void initialize()
{
	model.directoryProperty().bindBidirectional(dirSelection.textProperty());
	select.selectedProperty().addListener((
			(observable, oldValue, newValue) -> {
				dirSelection.setDisable(!select.isSelected());
				dirSelection.setEditable(select.isSelected());
				selectButton.setDisable(!select.isSelected());
			}));

	if (!SystemUtils.IS_OS_MAC_OSX)
	{
		macUserDir.setVisible(false);
	}
	if (!SystemUtils.IS_OS_UNIX)
	{
		freedesktop.setVisible(false);
	}

	directoryGroup.selectedToggleProperty().addListener((observable, oldValue, newValue)  -> {
		Logging.debugPrint("toggle changed " + observable);
		if (newValue.getUserData() != null)
		{
			String userData = (String) newValue.getUserData();
			Logging.debugPrint("user data is " + userData);
			String newDir = ConfigurationSettings.getSettingsDirFromFilePath(userData);
			model.directoryProperty().setValue(newDir);
		}
	});
}
 
Example 7
Source File: UnixProcessChecker.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param pid           The process id to check.
 * @param executor      The executor to use for generating system commands.
 * @param timeout       The time which after this job should be killed due to timeout
 * @param checkWithSudo Whether the checker requires sudo
 */
UnixProcessChecker(
    @Min(1) final int pid,
    @NotNull final Executor executor,
    @NotNull final Instant timeout,
    final boolean checkWithSudo
) {
    if (!SystemUtils.IS_OS_UNIX) {
        throw new IllegalArgumentException("Not running on a Unix system.");
    }

    this.executor = executor;

    // Use POSIX compliant 'kill -0 <PID>' to check if process is still running.
    if (checkWithSudo) {
        this.commandLine = new CommandLine("sudo");
        this.commandLine.addArgument("kill");
        this.commandLine.addArgument("-0");
        this.commandLine.addArgument(Integer.toString(pid));
    } else {
        this.commandLine = new CommandLine("kill");
        this.commandLine.addArgument("-0");
        this.commandLine.addArgument(Integer.toString(pid));
    }

    this.timeout = timeout;
}
 
Example 8
Source File: DiskCleanupTask.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor. Schedules this task to be run by the task scheduler.
 *
 * @param properties      The disk cleanup properties to use.
 * @param scheduler       The scheduler to use to schedule the cron trigger.
 * @param jobsDir         The resource representing the location of the job directory
 * @param dataServices    The {@link DataServices} instance to use
 * @param jobsProperties  The jobs properties to use
 * @param processExecutor The process executor to use to delete directories
 * @param registry        The metrics registry
 * @throws IOException When it is unable to open a file reference to the job directory
 */
public DiskCleanupTask(
    @NotNull final DiskCleanupProperties properties,
    @NotNull final TaskScheduler scheduler,
    @NotNull final Resource jobsDir,
    @NotNull final DataServices dataServices,
    @NotNull final JobsProperties jobsProperties,
    @NotNull final Executor processExecutor,
    @NotNull final MeterRegistry registry
) throws IOException {
    // Job Directory is guaranteed to exist by the MvcConfig bean creation but just in case someone overrides
    if (!jobsDir.exists()) {
        throw new IOException("Jobs dir " + jobsDir + " doesn't exist. Unable to create task to cleanup.");
    }

    this.properties = properties;
    this.jobsDir = jobsDir.getFile();
    this.persistenceService = dataServices.getPersistenceService();
    this.runAsUser = jobsProperties.getUsers().isRunAsUserEnabled();
    this.processExecutor = processExecutor;

    this.numberOfDeletedJobDirs = registry.gauge(
        "genie.tasks.diskCleanup.numberDeletedJobDirs.gauge",
        new AtomicLong()
    );
    this.numberOfDirsUnableToDelete = registry.gauge(
        "genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge",
        new AtomicLong()
    );
    this.unableToGetJobCounter = registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate");
    this.unableToDeleteJobDirCounter = registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate");

    // Only schedule the task if we don't need sudo while on a non-unix system
    if (this.runAsUser && !SystemUtils.IS_OS_UNIX) {
        log.error("System is not UNIX like. Unable to schedule disk cleanup due to needing Unix commands");
    } else {
        final CronTrigger trigger = new CronTrigger(properties.getExpression(), JobConstants.UTC);
        scheduler.schedule(this, trigger);
    }
}
 
Example 9
Source File: JobMonitor.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param execution      The job execution object including the pid
 * @param stdOut         The std out output file
 * @param stdErr         The std err output file
 * @param genieEventBus  The event bus implementation to use
 * @param registry       The metrics event registry
 * @param jobsProperties The properties for jobs
 * @param processChecker The process checker
 */
JobMonitor(
    @Valid final JobExecution execution,
    @NotNull final File stdOut,
    @NotNull final File stdErr,
    @NonNull final GenieEventBus genieEventBus,
    @NotNull final MeterRegistry registry,
    @NotNull final JobsProperties jobsProperties,
    @NotNull final ProcessChecker processChecker
) {
    if (!SystemUtils.IS_OS_UNIX) {
        throw new UnsupportedOperationException("Genie doesn't currently support " + SystemUtils.OS_NAME);
    }

    this.errorCount = 0;
    this.id = execution.getId().orElseThrow(IllegalArgumentException::new);
    this.execution = execution;
    this.genieEventBus = genieEventBus;
    this.processChecker = processChecker;

    this.stdOut = stdOut;
    this.stdErr = stdErr;

    this.maxStdOutLength = jobsProperties.getMax().getStdOutSize();
    this.maxStdErrLength = jobsProperties.getMax().getStdErrSize();

    this.trigger = new ExponentialBackOffTrigger(
        ExponentialBackOffTrigger.DelayType.FROM_PREVIOUS_SCHEDULING,
        jobsProperties.getCompletionCheckBackOff().getMinInterval(),
        execution.getCheckDelay().orElse(jobsProperties.getCompletionCheckBackOff().getMaxInterval()),
        jobsProperties.getCompletionCheckBackOff().getFactor()
    );

    this.successfulCheckRate = registry.counter("genie.jobs.successfulStatusCheck.rate");
    this.timeoutRate = registry.counter("genie.jobs.timeout.rate");
    this.finishedRate = registry.counter("genie.jobs.finished.rate");
    this.unsuccessfulCheckRate = registry.counter("genie.jobs.unsuccessfulStatusCheck.rate");
    this.stdOutTooLarge = registry.counter("genie.jobs.stdOutTooLarge.rate");
    this.stdErrTooLarge = registry.counter("genie.jobs.stdErrTooLarge.rate");
}
 
Example 10
Source File: FolderFinder.java    From collect-earth with MIT License 5 votes vote down vote up
private static String getUserHome() {
	String userHome = "" ; 
	
	if (SystemUtils.IS_OS_WINDOWS){
		userHome = System.getenv("APPDATA") + File.separatorChar;
	}else if (SystemUtils.IS_OS_MAC){
		userHome = System.getProperty("user.home") + "/Library/Application Support/";
	}else if ( SystemUtils.IS_OS_UNIX){
		userHome = System.getProperty("user.home") + "/";
	}
	return userHome;
}
 
Example 11
Source File: CollectEarthUtils.java    From collect-earth with MIT License 5 votes vote down vote up
public static void openFolderInExplorer(String folder) throws IOException {
	if (Desktop.isDesktopSupported()) {
		Desktop.getDesktop().open(new File(folder));
	}else{
		if (SystemUtils.IS_OS_WINDOWS){
			new ProcessBuilder("explorer.exe", "/open," + folder).start(); //$NON-NLS-1$ //$NON-NLS-2$
		}else if (SystemUtils.IS_OS_MAC){
			new ProcessBuilder("usr/bin/open", folder).start(); //$NON-NLS-1$ //$NON-NLS-2$
		}else if ( SystemUtils.IS_OS_UNIX){
			tryUnixFileExplorers(folder);
		}
	}
}
 
Example 12
Source File: AO_InkscapeExecutable.java    From svg2vector with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the new option.
 * @param shortOption character for sort version of the option
 * @throws NullPointerException - if description parameter is null
 * @throws IllegalArgumentException - if description parameter is empty
 */
public AO_InkscapeExecutable(Character shortOption){
	super("path to Inkscape executable",
			"This option, if used, needs to point to the Inkscape executable. " +
			"Some default values are set in the following way: " +
			"first, the environment variable <" + ENV_KEY + "> is tested. If it is not null, it's value is set as default for the option. " +
			"Next, if the underlying operating system is a Windows system (using Apache SystemUtils), the default value is set to <" + DEFAULT_WINDOWS + ">. " +
			"Next, if the underlying operating system is a UNIX system (using Apache SystemUtils), the default value is set to <" + DEFAULT_UNIX + ">. " +
			"In all other cases, no default value will be set." +
			"\n" +
			"Using the option in the command line will use the given executable and ignore any default settings."
	);

	Option.Builder builder = (shortOption==null)?Option.builder():Option.builder(shortOption.toString());
	builder.longOpt("is-exec");
	builder.hasArg().argName("PATH");
	builder.required(false);
	this.setCliOption(builder.build());

	String env = System.getenv(ENV_KEY);
	if(env!=null){
		this.setDefaultValue(env);
	}
	else if(SystemUtils.IS_OS_WINDOWS){
		this.setDefaultValue("C:/Program Files/Inkscape/inkscape.exe");
	}
	else if(SystemUtils.IS_OS_UNIX){
		this.setDefaultValue("/usr/bin/inkscape");
	}
}
 
Example 13
Source File: OptionsPathDialogController.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@FXML
void initialize()
{
	model.directoryProperty().bindBidirectional(dirSelection.textProperty());
	select.selectedProperty().addListener((
			(observable, oldValue, newValue) -> {
				dirSelection.setDisable(!select.isSelected());
				dirSelection.setEditable(select.isSelected());
				selectButton.setDisable(!select.isSelected());
			}));

	if (!SystemUtils.IS_OS_MAC_OSX)
	{
		macUserDir.setVisible(false);
	}
	if (!SystemUtils.IS_OS_UNIX)
	{
		freedesktop.setVisible(false);
	}

	directoryGroup.selectedToggleProperty().addListener((observable, oldValue, newValue)  -> {
		Logging.debugPrint("toggle changed " + observable);
		if (newValue.getUserData() != null)
		{
			String userData = (String) newValue.getUserData();
			Logging.debugPrint("user data is " + userData);
			String newDir = ConfigurationSettings.getSettingsDirFromFilePath(userData);
			model.directoryProperty().setValue(newDir);
		}
	});
}
 
Example 14
Source File: DefaultTagsListeners.java    From DeskChan with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static String fillOS(){
    String os = null;
    if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) os = "mac";
    else if (SystemUtils.IS_OS_UNIX) os = "linux";
    else if (SystemUtils.IS_OS_WINDOWS) os = "windows";

    return os;
}
 
Example 15
Source File: LocalComputationManager.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static LocalCommandExecutor getLocalCommandExecutor() {
    if (SystemUtils.IS_OS_WINDOWS) {
        return new WindowsLocalCommandExecutor();
    } else if (SystemUtils.IS_OS_UNIX) {
        return new UnixLocalCommandExecutor();
    } else {
        throw new UnsupportedOperationException("OS not supported for local execution");
    }
}
 
Example 16
Source File: OS.java    From arquillian-governor with Apache License 2.0 4 votes vote down vote up
@Override
public boolean detected() {
    return SystemUtils.IS_OS_UNIX;
}
 
Example 17
Source File: CondisOS.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean check(Event e) {
  Boolean chk = false;
  switch (ty) {
    case (0):
      chk = SystemUtils.IS_OS_WINDOWS;
      break;
    case (1):
      chk = SystemUtils.IS_OS_MAC;
      break;
    case (2):
      chk = SystemUtils.IS_OS_LINUX;
      break;
    case (3):
      chk = SystemUtils.IS_OS_UNIX;
      break;
    case (4):
      chk = SystemUtils.IS_OS_SOLARIS;
      break;
    case (5):
      chk = SystemUtils.IS_OS_SUN_OS;
      break;
    case (6):
      chk = SystemUtils.IS_OS_HP_UX;
      break;
    case (7):
      chk = SystemUtils.IS_OS_AIX;
      break;
    case (8):
      chk = SystemUtils.IS_OS_IRIX;
      break;
    case (9):
      chk = SystemUtils.IS_OS_FREE_BSD;
      break;
    case (10):
      chk = SystemUtils.IS_OS_OPEN_BSD;
      break;
    case (11):
      chk = SystemUtils.IS_OS_NET_BSD;
      break;
  }
  return (isNegated() ? !chk : chk);
}
 
Example 18
Source File: WebServerApi.java    From aceql-http with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts the embedded Web Server.
 *
 * @param host
 *            the host of the Web Server
 * @param port
 *            the port of the Web Server
 * @param propertiesFile
 *            properties file to use for configuration of the Web Server
 *
 * @throws ConnectException
 *             if the port is not available
 * @throws IOException
 *             if an IOException occurs
 * @throws DatabaseConfigurationException
 *             if there is a configuration error, either in Configurators or in
 *             the <code>server-sql.properties</code> file
 * @throws LifecycleException
 *             thrown by the embedded Tomcat engine for any lifecycle related
 *             problem
 */
public void startServer(String host, int port, File propertiesFile)
		throws ConnectException, IOException, DatabaseConfigurationException, LifecycleException {

	debug("propertiesFiles: " + propertiesFile);

	if (host == null) {
		throw new DatabaseConfigurationException("host parameter can not be null.");
	}

	if (port <= 0) {
		throw new DatabaseConfigurationException("port parameter can not be null.");
	}

	if (propertiesFile == null) {
		throw new DatabaseConfigurationException("propertiesFile parameter can not be null.");
	}

	if (!propertiesFile.exists()) {
		throw new DatabaseConfigurationException(
				"The properties file " + propertiesFile + " does not exists. " + SqlTag.PLEASE_CORRECT);
	}

	if (!TomcatStarterUtil.available(port)) {
		throw new ConnectException(
				"The port " + port + " is not available for starting Web server. " + SqlTag.PLEASE_CORRECT);
	}

	PortSemaphoreFile portSemaphoreFile = new PortSemaphoreFile(port);

	try {
		if (!portSemaphoreFile.exists()) {
			portSemaphoreFile.create();
		}
	} catch (IOException e) {
		throw new IOException("Web server can not start. Impossible to create the semaphore file: "
				+ portSemaphoreFile.getSemaphoreFile() + CR_LF
				+ "Create manually the semapahore file to start the Web server on port " + port + ".", e);
	}

	// Do not use SecureRandom class
	if (SystemUtils.IS_OS_UNIX) {
		System.setProperty("java.security.egd", "file:/dev/./urandom");
		debug("java.security.egd: " + System.getProperty("java.security.egd"));
	}

	// OK build the Servlet
	TomcatStarter tomcatStarter = new TomcatStarter(host, port, propertiesFile);
	tomcatStarter.startTomcat();

}