Example usage for org.apache.commons.lang SystemUtils IS_OS_UNIX

List of usage examples for org.apache.commons.lang SystemUtils IS_OS_UNIX

Introduction

In this page you can find the example usage for org.apache.commons.lang SystemUtils IS_OS_UNIX.

Prototype

boolean IS_OS_UNIX

To view the source code for org.apache.commons.lang SystemUtils IS_OS_UNIX.

Click Source Link

Document

Is true if this is a POSIX compilant system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.

The field will return false if OS_NAME is null.

Usage

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user./*from   w  w w .jav  a  2s.c o m*/
 * @param file {@link Path} to test.
 * @param user {@link UserPrincipal} to test. If {@code null}, defaults to
 * current user.
 * @param symlinkDepth Number of symbolic links allowed.
 * @return {@code true} if file's directory is secure.
 */
public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) {
    if (!file.isAbsolute()) {
        file = file.toAbsolutePath();
    }
    if (symlinkDepth <= 0) {
        // Too many levels of symbolic links
        return false;
    }
    // Get UserPrincipal for specified user and superuser
    final Path fileRoot = file.getRoot();
    if (fileRoot == null) {
        return false;
    }
    final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem();
    final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService();
    UserPrincipal root = null;
    try {
        if (SystemUtils.IS_OS_UNIX) {
            root = upls.lookupPrincipalByName("root");
        } else {
            root = upls.lookupPrincipalByName("Administrators");
        }
        if (user == null) {
            user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        }
        if (root == null || user == null) {
            return false;
        }
    } catch (final IOException x) {
        return false;
    }
    // If any parent dirs (from root on down) are not secure, dir is not secure
    for (int i = 1; i <= file.getNameCount(); i++) {
        final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString());
        try {
            if (Files.isSymbolicLink(partialPath)) {
                if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) {
                    // Symbolic link, linked-to dir not secure
                    return false;
                }
            } else {
                final UserPrincipal owner = Files.getOwner(partialPath);
                if (!user.equals(owner) && !root.equals(owner)) {
                    // dir owned by someone else, not secure
                    return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath);
                }
            }
        } catch (final IOException x) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.tajo.util.StringUtils.java

/**
 * Print a log message for starting up and shutting down
 * @param clazz the class of the server/*from w w w  . j av  a 2  s.  c  o m*/
 * @param args arguments
 * @param LOG the target log object
 */
public static void startupShutdownMessage(Class<?> clazz, String[] args,
        final org.apache.commons.logging.Log LOG) {
    final String hostname = org.apache.hadoop.net.NetUtils.getHostname();
    final String classname = clazz.getSimpleName();
    LOG.info(toStartupShutdownString("STARTUP_MSG: ",
            new String[] { "Starting " + classname, "  host = " + hostname, "  args = " + Arrays.asList(args),
                    "  version = " + org.apache.tajo.util.VersionInfo.getVersion(),
                    "  classpath = " + System.getProperty("java.class.path"),
                    "  build = " + org.apache.tajo.util.VersionInfo.getUrl() + " -r "
                            + org.apache.tajo.util.VersionInfo.getRevision() + "; compiled by '"
                            + org.apache.tajo.util.VersionInfo.getUser() + "' on "
                            + org.apache.tajo.util.VersionInfo.getDate(),
                    "  java = " + System.getProperty("java.version") }));

    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(new Runnable() {
        @Override
        public void run() {
            LOG.info(toStartupShutdownString("SHUTDOWN_MSG: ",
                    new String[] { "Shutting down " + classname + " at " + hostname }));
        }
    }, SHUTDOWN_HOOK_PRIORITY);
}

From source file:org.apache.tika.parser.ocr.TesseractOCRConfigTest.java

@Test
public void testFullConfig() throws Exception {

    InputStream stream = TesseractOCRConfigTest.class
            .getResourceAsStream("/test-properties/TesseractOCRConfig-full.properties");

    TesseractOCRConfig config = new TesseractOCRConfig(stream);
    if (SystemUtils.IS_OS_UNIX) {
        assertEquals("Invalid overridden tesseractPath value", "/opt/tesseract" + File.separator,
                config.getTesseractPath());
        assertEquals("Invalid overridden tesseractPath value", "/usr/local/share" + File.separator,
                config.getTessdataPath());
        assertEquals("Invalid overridden ImageMagickPath value", "/usr/local/bin/",
                config.getImageMagickPath());
    }//from  w  w w  .  j a v  a 2 s  . c o m
    assertEquals("Invalid overridden language value", "fra+deu", config.getLanguage());
    assertEquals("Invalid overridden pageSegMode value", "2", config.getPageSegMode());
    assertEquals("Invalid overridden minFileSizeToOcr value", 1, config.getMinFileSizeToOcr());
    assertEquals("Invalid overridden maxFileSizeToOcr value", 2000000, config.getMaxFileSizeToOcr());
    assertEquals("Invalid overridden timeout value", 240, config.getTimeout());
    assertEquals("Invalid overridden density value", 200, config.getDensity());
    assertEquals("Invalid overridden depth value", 8, config.getDepth());
    assertEquals("Invalid overridden filter value", "box", config.getFilter());
    assertEquals("Invalid overridden resize value", 300, config.getResize());
}

From source file:org.eclim.command.Main.java

public static void usage(String cmd, PrintStream out) {
    ArrayList<org.eclim.annotation.Command> commands = new ArrayList<org.eclim.annotation.Command>();
    for (Class<? extends Command> command : Services.getCommandClasses()) {
        commands.add(command.getAnnotation(org.eclim.annotation.Command.class));
    }/*from  w ww  .  j  av a 2s .c o m*/
    Collections.sort(commands, new Comparator<org.eclim.annotation.Command>() {
        public int compare(org.eclim.annotation.Command o1, org.eclim.annotation.Command o2) {
            return o1.name().compareTo(o2.name());
        }
    });

    boolean cmdFound = cmd == null;
    if (cmd == null) {
        String osOpts = StringUtils.EMPTY;
        if (SystemUtils.IS_OS_UNIX) {
            osOpts = " [-f eclimrc] [--nailgun-port port]";
        }
        out.println("Usage: eclim" + osOpts + " -command command [args]");
        out.println("  To view a full list of available commands:");
        out.println("    eclim -? commands");
        out.println("  To view info for a specific command:");
        out.println("    eclim -? <command_name>");
        out.println("  Ex.");
        out.println("    eclim -? project_create");
    } else if (cmd.equals("commands")) {
        out.println("Available Commands:");
    } else {
        out.println("Requested Command:");
    }

    for (org.eclim.annotation.Command command : commands) {
        if (cmd == null || (!cmd.equals(command.name()) && !cmd.equals("commands"))) {
            continue;
        }
        cmdFound = true;

        Collection<Option> options = new Options().parseOptions(command.options());
        StringBuffer opts = new StringBuffer();
        Iterator<Option> iterator = options.iterator();
        for (int ii = 0; iterator.hasNext(); ii++) {
            Option option = iterator.next();
            opts.append(option.isRequired() ? " " : " [");
            opts.append('-').append(option.getOpt());
            if (option.hasArg()) {
                opts.append(' ').append(option.getLongOpt());
            }
            if (!option.isRequired()) {
                opts.append(']');
            }
            // wrap every 4 options
            if ((ii + 1) % 4 == 0 && ii != options.size() - 1) {
                opts.append(StringUtils.rightPad("\n", command.name().length() + 5));
            }
        }
        StringBuffer info = new StringBuffer().append("    ").append(command.name()).append(opts);
        out.println(info);
        if (!command.description().equals(StringUtils.EMPTY)) {
            out.println("      " + command.description());
        }
    }

    if (!cmdFound) {
        out.println("    No Such Command: " + cmd);
    }
}

From source file:org.geopublishing.geopublisher.GpUtil.java

/**
 * this method checks for permission on java.io.tmpdir and changes it to a
 * given path if files in current tmpDir may not be executed. (Possibly due
 * to noexec mountoption on /tmp)// w ww .j ava 2s .  co m
 */
public static void checkAndResetTmpDir(String path) {
    if (SystemUtils.IS_OS_UNIX) {
        String tmpDir = System.getProperty("java.io.tmpdir");
        try {
            File file = File.createTempFile("geopublisher", "tmpDirTest", new File(tmpDir));
            file.setExecutable(true);
            if (!file.canExecute()) {
                System.setProperty("java.io.tmpdir", path);
                LOGGER.debug("tmpDir has no execute rights, changing to " + path);
            }
            FileUtils.deleteQuietly(file);
        } catch (IOException e) {
            LOGGER.log(Level.ERROR, e);
        }
    }
}

From source file:org.graylog.plugins.backup.strategy.AbstractMongoBackupStrategy.java

protected String osShellPath() {

    if (SystemUtils.IS_OS_UNIX) {
        return "/bin/sh";
    }/*from w w  w  . j a  v  a2 s  .c o  m*/

    throw new IllegalArgumentException("At the moment your system is not supported");
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Get Java process builder with basic command line execution based on
 * given os nature./*from w  w  w. ja  va 2 s  .c  o m*/
 * @return
 */
private ProcessBuilder getProcessBuilder() {
    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);
        commands.add(BASH_OPTION_C);
    } else {
        commands.add(CMD);
        commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(Paths.get("").toFile().getAbsoluteFile());

    log.trace("Returning ProcessBuilder for command:" + commands);
    return pb;
}

From source file:org.jodconverter.office.LocalOfficeUtilsTest.java

/** Tests the LocalOfficeUtils.toUrl function on unix OS. */
@Test//ww w  .j ava2s.  co m
public void unixToUrl() {

    assumeTrue(SystemUtils.IS_OS_UNIX);

    assertThat(toUrl(new File("/tmp/document.odt"))).isEqualTo("file:///tmp/document.odt");
    assertThat(toUrl(new File("/tmp/document with spaces.odt")))
            .isEqualTo("file:///tmp/document%20with%20spaces.odt");
}

From source file:org.jodconverter.process.ProcessManagerTest.java

/**
 * Tests the UnixProcessManager class./*from   w w w .j a  v  a 2 s.  co  m*/
 *
 * @throws Exception if an error occurs.
 */
@Test
public void unixProcessManager() throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX && !SystemUtils.IS_OS_MAC);

    final ProcessManager processManager = UnixProcessManager.getDefault();
    final Process process = Runtime.getRuntime().exec("sleep 5s");
    final ProcessQuery query = new ProcessQuery("sleep", "5s");

    final long pid = processManager.findPid(query);
    assertThat(pid).isNotEqualTo(ProcessManager.PID_NOT_FOUND);
    final Number javaPid = (Number) FieldUtils.readDeclaredField(process, "pid", true);
    assertThat(pid).isEqualTo(javaPid.longValue());

    processManager.kill(process, pid);
    assertThat(processManager.findPid(query)).isEqualTo(ProcessManager.PID_NOT_FOUND);
}

From source file:org.mule.transport.sftp.AbstractSftpTestCase.java

protected void recursiveDeleteInLocalFilesystem(File parent) throws IOException {
    // If this file is a directory then first delete all its children
    if (parent.isDirectory()) {
        for (File child : parent.listFiles()) {
            recursiveDeleteInLocalFilesystem(child);
        }//w ww  .  j  a v a 2 s  . c  o  m
    }

    // Now delete this file, but first check write permissions on its parent...
    File parentParent = parent.getParentFile();

    if (!parentParent.canWrite()) {
        // setWritable is only available on JDK6 and beyond
        //if (!parentParent.setWritable(true))
        //throw new IOException("Failed to set readonly-folder: " + parentParent + " to writeable");
        // FIXME DZ: since setWritable doesnt exist on jdk5, need to detect os to make dir writable
        if (SystemUtils.IS_OS_WINDOWS) {
            Runtime.getRuntime().exec("attrib -r /D" + parentParent.getAbsolutePath());
        } else if (SystemUtils.IS_OS_UNIX || SystemUtils.IS_OS_LINUX) {
            Runtime.getRuntime().exec("chmod +w " + parentParent.getAbsolutePath());
        } else {
            throw new IOException(
                    "This test is not supported on your detected platform : " + SystemUtils.OS_NAME);
        }
    }

    if (parent.exists()) {
        // FIXME DZ: since setWritable doesnt exist on jdk5, need to detect os to make dir writable
        if (SystemUtils.IS_OS_WINDOWS) {
            Runtime.getRuntime().exec("attrib -r /D" + parent.getAbsolutePath());
        } else if (SystemUtils.IS_OS_UNIX || SystemUtils.IS_OS_LINUX) {
            Runtime.getRuntime().exec("chmod +w " + parent.getAbsolutePath());
        } else {
            throw new IOException(
                    "This test is not supported on your detected platform : " + SystemUtils.OS_NAME);
        }
        if (!parent.delete())
            throw new IOException("Failed to delete folder: " + parent);
    }
}