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

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

Introduction

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

Prototype

boolean IS_OS_WINDOWS

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

Click Source Link

Document

Is true if this is Windows.

The field will return false if OS_NAME is null.

Usage

From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java

/**
 * Writes a byte-array to a temporary file and executes the given command
 * with the file as argument. The function will, depending on its
 * parameters, fail if output to standard error from the command was
 * detected or the command returns with an non-zero exit code.
 * //from   ww  w . j a v a  2  s.  c om
 * @param externalCommand
 *            The command to run.
 * @param bytes
 *            The buffer with content to write to the file.
 * @param failOnCode
 *            Determines if the method should fail on a non-zero exit code.
 * @param failOnOutput
 *            Determines if the method should fail on output to standard
 *            error.
 * @param additionalArguments
 *            Added to the command after the tempfiles name
 * @throws PublisherException
 */
private void runWithTempFile(String externalCommand, byte[] bytes, boolean failOnCode, boolean failOnOutput,
        List<String> additionalArguments) throws PublisherException {
    // Create temporary file
    File tempFile = null;
    FileOutputStream fos = null;
    try {
        tempFile = File.createTempFile("GeneralPurposeCustomPublisher", ".tmp");
        fos = new FileOutputStream(tempFile);
        fos.write(bytes);
        // fos.close();
    } catch (FileNotFoundException e) {
        String msg = intres.getLocalizedMessage("publisher.errortempfile");
        log.error(msg, e);
        throw new PublisherException(msg);
    } catch (IOException e) {
        try {
            fos.close();
        } catch (IOException e1) {
        }
        tempFile.delete();
        String msg = intres.getLocalizedMessage("publisher.errortempfile");
        log.error(msg, e);
        throw new PublisherException(msg);
    }
    // Exec file from properties with the file as an argument
    String tempFileName = null;
    try {
        tempFileName = tempFile.getCanonicalPath();
        String[] cmdcommand = (externalCommand).split("\\s");
        additionalArguments.add(0, tempFileName);
        if (SystemUtils.IS_OS_WINDOWS) {
            /*
             * Hack needed for Windows, where Runtime.exec won't consistently encapsulate arguments, leading to arguments
             * containing spaces (such as Subject DNs) sometimes being parsed as multiple arguments. Bash, on the other hand,
             * won't parse quote surrounded arguments. 
             */
            for (int i = 0; i < additionalArguments.size(); i++) {
                String argument = additionalArguments.get(i);
                //Add quotes to encapsulate argument. 
                if (!argument.startsWith("\"") && !argument.endsWith("\"")) {
                    additionalArguments.set(i, "\"" + argument + "\"");
                }
            }
        }
        String[] cmdargs = additionalArguments.toArray(new String[additionalArguments.size()]);
        String[] cmdarray = new String[cmdcommand.length + cmdargs.length];
        System.arraycopy(cmdcommand, 0, cmdarray, 0, cmdcommand.length);
        System.arraycopy(cmdargs, 0, cmdarray, cmdcommand.length, cmdargs.length);
        Process externalProcess = Runtime.getRuntime().exec(cmdarray, null, null);
        BufferedReader stdError = new BufferedReader(new InputStreamReader(externalProcess.getErrorStream()));
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(externalProcess.getInputStream()));
        while (stdInput.readLine() != null) {
        } // NOPMD: Required under win32 to avoid lock
        String stdErrorOutput = null;
        // Check errorcode and the external applications output to stderr
        if (((externalProcess.waitFor() != 0) && failOnCode) || (stdError.ready() && failOnOutput)) {
            tempFile.delete();
            String errTemp = null;
            while (stdError.ready() && (errTemp = stdError.readLine()) != null) {
                if (stdErrorOutput == null) {
                    stdErrorOutput = errTemp;
                } else {
                    stdErrorOutput += "\n" + errTemp;
                }
            }
            String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand);
            if (stdErrorOutput != null) {
                msg += " - " + stdErrorOutput + " - " + tempFileName;
            }
            log.error(msg);
            throw new PublisherException(msg);
        }
    } catch (IOException e) {
        String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand);
        throw new PublisherException(msg);
    } catch (InterruptedException e) {
        String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand);
        Thread.currentThread().interrupt();
        throw new PublisherException(msg);
    } finally {
        try {
            fos.close();
        } catch (IOException e1) {
        }
        // Remove temporary file or schedule for delete if delete fails.
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
            log.info(intres.getLocalizedMessage("publisher.errordeletetempfile", tempFileName));
        }
    }
}

From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java

/**
 * Get the tile layout with opj_dump/*from w w  w .j ava 2s . c o  m*/
 *
 * @param opjdumpPath path to opj_dump
 * @param jp2FilePath the path to the jpeg file
 * @return the tile layout for the openjpeg file
 * @throws IOException
 * @throws InterruptedException
 */
public static TileLayout getTileLayoutWithOpenJPEG(String opjdumpPath, Path jp2FilePath)
        throws IOException, InterruptedException {

    if (opjdumpPath == null) {
        throw new IllegalStateException("Cannot retrieve tile layout, opj_dump cannot be found");
    }

    TileLayout tileLayout;

    String pathToImageFile = jp2FilePath.toAbsolutePath().toString();
    if (SystemUtils.IS_OS_WINDOWS) {
        pathToImageFile = Utils.GetIterativeShortPathName(pathToImageFile);
    }

    ProcessBuilder builder = new ProcessBuilder(opjdumpPath, "-i", pathToImageFile);
    builder.redirectErrorStream(true);

    CommandOutput exit = OpenJpegUtils.runProcess(builder);

    if (exit.getErrorCode() != 0) {
        StringBuilder sbu = new StringBuilder();
        for (String fragment : builder.command()) {
            sbu.append(fragment);
            sbu.append(' ');
        }

        throw new IOException(
                String.format("Command [%s] failed with error code [%d], stdoutput [%s] and stderror [%s]",
                        sbu.toString(), exit.getErrorCode(), exit.getTextOutput(), exit.getErrorOutput()));
    }
    tileLayout = OpenJpegUtils.parseOpjDump(exit.getTextOutput());

    return tileLayout;
}

From source file:org.esa.s2tbx.dataio.s2.ShortenTest.java

@Before
public void beforeMethod() {
    Assume.assumeTrue(SystemUtils.IS_OS_WINDOWS);
}

From source file:org.geopublishing.atlasStyler.swing.AtlasStylerGUI.java

/**
 * Creates a nre {@link JMenuBar} instance
 *//*www.ja  v  a2  s  .  c  o  m*/
private JMenuBar createMenuBar() {
    JMenuBar jMenuBar = new JMenuBar();

    JMenu fileMenu = new JMenu(AsSwingUtil.R("MenuBar.FileMenu"));

    jMenuBar.add(fileMenu);

    { // Import WIzard
        JMenuItem mi = new JMenuItem(new AbstractAction(AsSwingUtil.R("MenuBar.FileMenu.ImportWizard")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                ImportWizard.showWizard(AtlasStylerGUI.this, AtlasStylerGUI.this);
            }
        });
        mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK, true));
        fileMenu.add(mi);
    }

    fileMenu.add(SwingUtil.createChangeLog4JLevelJMenu());

    /**
     * MenuItem to create a new language
     */
    JMenuItem manageLanguageJMenuitem = new JMenuItem(
            new AbstractAction(ASUtil.R("TranslateSoftwareDialog.Title"), Icons.ICON_FLAGS_SMALL) {

                @Override
                public void actionPerformed(ActionEvent e) {
                    String resPath = IOUtil
                            .escapePath(System.getProperty("user.home") + File.separator + ".Geopublishing");
                    ResourceProviderManagerFrame manLanguagesFrame = new ResourceProviderManagerFrame(
                            AtlasStylerGUI.this, true, AsSwingUtil.R("TranslateSoftwareDialog.Explanation.Html",
                                    resPath, SystemUtils.IS_OS_WINDOWS ? "bat" : "sh"));
                    manLanguagesFrame.setRootPath(new File(resPath));
                    manLanguagesFrame.setTitle(ASUtil.R("TranslateSoftwareDialog.Title"));
                    manLanguagesFrame.setPreferredSize(new Dimension(780, 450));
                    manLanguagesFrame.setVisible(true);
                }
            });
    fileMenu.add(manageLanguageJMenuitem);

    AbstractAction optionsButton = new AbstractAction(AtlasStylerVector.R("Options.ButtonLabel")) {

        @Override
        public void actionPerformed(ActionEvent e) {
            new ASOptionsDialog(AtlasStylerGUI.this, AtlasStylerGUI.this);
        }
    };

    fileMenu.add(optionsButton);

    { // Exit
        JMenuItem mi = new JMenuItem(new AbstractAction(
                GpCoreUtil.R("AtlasViewer.FileMenu.ExitMenuItem.exit_application"), Icons.ICON_EXIT_SMALL) {

            @Override
            public void actionPerformed(ActionEvent e) {
                exitAS(0);
            }
        });
        fileMenu.add(mi);
    }

    return jMenuBar;
}

From source file:org.geopublishing.atlasViewer.GpCoreUtil.java

/**
 * Fix an ugly bug that disables the "Create Folder" button on Windows for
 * the MyDocuments//  w  ww  .j a va2  s.  c  o m
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4847375
 * 
 * @see http://code.google.com/p/winfoldersjava/
 */
public static void fixBug4847375() {

    try {
        if (SystemUtils.IS_OS_WINDOWS) {
            final String myDocumentsDirectoryName = javax.swing.filechooser.FileSystemView.getFileSystemView()
                    .getDefaultDirectory().getName();
            Runtime.getRuntime().exec("attrib -r \"%USERPROFILE%\\" + myDocumentsDirectoryName + "\"");
        }

    } catch (final Throwable e) {
        LOGGER.error("While fixing bug 4847375: ", e);
    }

    // try {
    // Runtime.getRuntime().exec(
    // "attrib -r \"%USERPROFILE%\\My Documents\"");
    // } catch (IOException e) {
    // }
    // try {
    // Runtime.getRuntime().exec(
    // "attrib -r \"%USERPROFILE%\\Mes documents\"");
    // } catch (IOException e) {
    // }
    // try {
    // String cmd = "attrib -r \"%USERPROFILE%\\Eigene Dateien\"";
    // Runtime.getRuntime().exec(cmd);
    // } catch (IOException e) {
    // }

}

From source file:org.geoserver.backuprestore.BackupRestoreTestSupport.java

@Override
protected boolean isMemoryCleanRequired() {
    return SystemUtils.IS_OS_WINDOWS;
}

From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java

/**
 * Locates and executable in the system path. On windows it will automatically append .exe to
 * the searched file name//from w w  w. j a  v a  2s. com
 * 
 * @param name
 *
 * @throws IOException
 */
protected File getExecutableFromPath(String name) throws IOException {
    if (SystemUtils.IS_OS_WINDOWS) {
        name = name + ".exe";
    }
    String systemPath = System.getenv("PATH");
    if (systemPath == null) {
        systemPath = System.getenv("path");
    }
    if (systemPath == null) {
        throw new IOException("Path is not set, cannot locate " + name);
    }
    String[] paths = systemPath.split(File.pathSeparator);

    for (String pathDir : paths) {
        File file = new File(pathDir, name);
        if (file.exists() && file.isFile() && file.canExecute()) {
            return file;
        }
    }
    throw new IOException(
            "Could not locate executable (or could locate, but does not have execution rights): " + name);
}

From source file:org.geoserver.rest.resources.ResourceControllerTest.java

@Test
public void testSpecialCharacterNames() throws Exception {
    // if the file system encoded the file with a ? we need to skip this test
    Assume.assumeTrue(//www  .ja v  a  2s  . c om
            SystemUtils.IS_OS_WINDOWS || getDataDirectory().get("po?zie").getType() == Type.UNDEFINED);
    Assert.assertEquals(Type.DIRECTORY, getDataDirectory().get("pozie").getType());
    XMLUnit.setXpathNamespaceContext(NS_XML);
    Document doc = getAsDOM(RestBaseController.ROOT_PATH + "/resource/po%c3%abzie?format=xml");
    XMLAssert.assertXpathEvaluatesTo(
            "http://localhost:8080/geoserver" + RestBaseController.ROOT_PATH
                    + "/resource/po%C3%ABzie/caf%C3%A9",
            "/ResourceDirectory/children/child/atom:link/@href", doc);

    MockHttpServletResponse response = getAsServletResponse(
            RestBaseController.ROOT_PATH + "/resource/po%c3%abzie/caf%c3%a9?format=xml");
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("resource", response.getHeader("Resource-Type"));
    Assert.assertEquals(
            "http://localhost:8080/geoserver" + RestBaseController.ROOT_PATH + "/resource/po%C3%ABzie",
            response.getHeader("Resource-Parent"));
}

From source file:org.glite.slcs.util.Utils.java

/**
 * Sets permissions on a given file. The permissions are set using the
 * <i>chmod</i> command and will only work on Unix machines. Chmod command
 * must be in the path./*from  w ww .ja  v  a 2s . c o  m*/
 * 
 * @param file
 *            the file to set the permissions of.
 * @param mode
 *            the Unix style permissions.
 * @return true, if change was successful, otherwise false. It can return
 *         false, in many instances, e.g. when file does not exits, when
 *         chmod is not found, or other error occurs.
 */
public static boolean setFilePermissions(File file, int mode) {
    String filename = file.getPath();
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            // ignored e.printStackTrace();
            LOG.warn("Failed to create new empty file: " + filename, e);
        }
    }
    // only on Unix
    if (!SystemUtils.IS_OS_WINDOWS) {
        Runtime runtime = Runtime.getRuntime();
        String[] cmd = new String[] { "chmod", String.valueOf(mode), filename };
        try {
            Process process = runtime.exec(cmd);
            return (process.waitFor() == 0) ? true : false;
        } catch (Exception e) {
            LOG.warn("Command 'chmod " + mode + " " + filename + "' failed", e);
            return false;
        }
    }
    // on Windows always return true
    else {
        LOG.info("Windows: Not possible to set file permissions " + mode + " on " + filename);
        return true;
    }

}

From source file:org.goobi.export.ExportMetsIT.java

@BeforeClass
public static void setUp() throws Exception {
    MockDatabase.startNode();//w w  w.  j a  v  a 2 s. c  o  m
    MockDatabase.insertProcessesFull();

    User user = serviceManager.getUserService().getById(1);
    process = serviceManager.getProcessService().getById(1);
    metadataDirectory = process.getId().toString();
    userDirectory = user.getLogin();
    exportUri = Config.getUri(Parameters.DIR_USERS, userDirectory);

    fileService.createDirectory(URI.create(""), metadataDirectory);
    fileService.copyFileToDirectory(URI.create("metadata/testmetaOldFormat.xml"),
            URI.create(metadataDirectory));
    fileService.renameFile(URI.create(metadataDirectory + "/testmetaOldFormat.xml"), "meta.xml");
    SecurityTestUtils.addUserDataToSecurityContext(user);
    FileLoader.createConfigProjectsFile();

    if (!SystemUtils.IS_OS_WINDOWS) {
        ExecutionPermission.setExecutePermission(scriptCreateDirUserHome);
    }

    File userdataDirectory = new File(Config.getParameter(Parameters.DIR_USERS));
    if (!userdataDirectory.exists() && !userdataDirectory.mkdir()) {
        throw new IOException("Could not create users directory");
    }
}