Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

In this page you can find the example usage for java.lang Process exitValue.

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.faces.WSClientBean.java

/**
 * runs the WSI Check using the official WS-I Testing Tool (and runs
 * this tool via Runtime.exec(..))// w  ww.  ja va2  s  .  com
 * @param configFile - the path to the confguration file used by the 
 *                     official WS-I Testing Tool
 */
private void runWSICheck(String configFile) {
    String[] args;
    log.debug("WSI_HOME = " + System.getenv("WSI_HOME"));
    log.debug("os.name = " + System.getProperty("os.name"));
    if (System.getProperty("os.name").contains("indows")) {
        args = new String[5];
        args[0] = "cmd.exe";
        args[1] = "/C";
        args[2] = "%WSI_HOME%/java/bin/Analyzer.bat";
        args[3] = "-config";
        args[4] = configFile;
    } else {
        args = new String[4];
        args[0] = "sh";
        //args[1] = "-c";
        //args[1] = "$WSI_HOME/java/bin/Analyzer.sh";
        args[1] = System.getenv("WSI_HOME") + "/java/bin/Analyzer.sh";
        args[2] = "-config";
        args[3] = configFile;
    }

    log.debug("Execution stmt: ");
    for (int i = 0; i < args.length; i++) {
        log.debug(args[i] + " ");
    }

    try {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(args);
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
        errorGobbler.start();
        outputGobbler.start();

        try {
            if (proc.waitFor() != 0) {
                log.error("exit value = " + proc.exitValue());
            } else
                log.debug("Terminated gracefully");
        } catch (InterruptedException e) {
            log.error(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.stallion.utils.ProcessHelper.java

public CommandResult run() {

    String cmdString = String.join(" ", args);
    System.out.printf("----- Execute command: %s ----\n", cmdString);
    ProcessBuilder pb = new ProcessBuilder(args);
    if (!empty(directory)) {
        pb.directory(new File(directory));
    }/*  www. ja va  2 s.  c o m*/
    Map<String, String> env = pb.environment();
    CommandResult commandResult = new CommandResult();
    Process p = null;
    try {
        if (showDotsWhileWaiting == null) {
            showDotsWhileWaiting = !inheritIO;
        }

        if (inheritIO) {
            p = pb.inheritIO().start();
        } else {
            p = pb.start();
        }

        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));

        if (!empty(input)) {
            Log.info("Writing input to pipe {0}", input);
            IOUtils.write(input, p.getOutputStream(), UTF8);
            p.getOutputStream().flush();
        }

        while (p.isAlive()) {
            p.waitFor(1000, TimeUnit.MILLISECONDS);
            if (showDotsWhileWaiting == true) {
                System.out.printf(".");
            }
        }

        commandResult.setErr(IOUtils.toString(err));
        commandResult.setOut(IOUtils.toString(out));
        commandResult.setCode(p.exitValue());

        if (commandResult.succeeded()) {
            info("\n---- Command execution completed ----\n");
        } else {
            Log.warn("Command failed with error code: " + commandResult.getCode());
        }

    } catch (IOException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(999);
        commandResult.setEx(e);
    } catch (InterruptedException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(998);
        commandResult.setEx(e);
    }
    Log.fine(
            "\n\n----Start shell command result----:\nCommand:  {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n",
            cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr());
    return commandResult;
}

From source file:org.mashupmedia.encode.ProcessManager.java

public void startProcess(ProcessQueueItem processQueueItem) throws IOException {

    try {//from ww  w  . ja  v a2  s.c om
        logger.info("Starting process...");
        List<String> commands = processQueueItem.getCommands();

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        // The started on date should have already been set
        Date startedOn = processQueueItem.getProcessStartedOn();
        if (startedOn == null) {
            processQueueItem.setProcessStartedOn(new Date());
        }

        processQueueItem.setProcess(process);

        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            logger.info(line);
        }
        IOUtils.closeQuietly(inputStream);

        try {
            int waitForValue = process.waitFor();
            logger.info("Process waitFor value = " + waitForValue);
        } catch (InterruptedException e) {
            logger.error("Error waiting for waitFor.", e);
        }

        int exitValue = process.exitValue();
        logger.info("Process exit value = " + exitValue);

    } finally {
        processQueueItems.remove(processQueueItem);
        encodeMediaItemTaskManager.processQueue();
    }

}

From source file:com.microsoft.alm.plugin.external.commands.CommandTest.java

/**
 * This test makes sure that output from a command is flushed before the completion event is fired.
 *
 * @throws Exception//from  w  ww  .j  ava  2  s.  c o m
 */
@Test
public void testRaceCondition() throws Exception {
    // Fake the tool location so this works on any machine
    PowerMockito.mockStatic(TfTool.class);
    when(TfTool.getValidLocation()).thenReturn("/path/tf_home");

    Process proc = Mockito.mock(Process.class);
    PowerMockito.mockStatic(ProcessHelper.class);
    when(ProcessHelper.startProcess(anyString(), anyList())).thenReturn(proc);
    when(proc.getErrorStream()).thenReturn(new InputStream() {
        @Override
        public int read() throws IOException {
            return -1;
        }
    });
    when(proc.getInputStream()).thenReturn(new InputStream() {
        private String result = "12345";
        private int index = 0;

        @Override
        public int read() throws IOException {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (index < result.length()) {
                return result.charAt(index++);
            } else {
                return -1;
            }
        }
    });
    when(proc.waitFor()).thenAnswer(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            return 0;
        }
    });
    when(proc.exitValue()).thenReturn(0);

    final MyCommand cmd = new MyCommand(null);
    final String output = cmd.runSynchronously();
    Assert.assertEquals("12345", StringUtils.strip(output));
}

From source file:com.twinsoft.convertigo.engine.Engine.java

public static synchronized void start() throws EngineException {
    if (Engine.theApp == null) {
        System.out.println("Starting Convertigo Enterprise Mobility Server");

        // If the engine has been stopped by the admin, we must reload
        // properties
        EnginePropertiesManager.loadProperties();

        boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean(
                EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE));

        if (bProjectsDataCompatibilityMode) {
            System.out.println("Projects data compatibility mode required");
            try {
                Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath();
                File projectsDir = new File(Engine.PROJECTS_PATH);
                projectsDir.mkdir();/*w ww . j a  v a 2 s  . c om*/
            } catch (IOException e) {
                throw new EngineException("Unable to update projects path for compatibility mode", e);
            }
        }

        isStarted = false;
        isStartFailed = false;
        RequestableObject.nbCurrentWorkerThreads = 0;

        Engine.startStopDate = System.currentTimeMillis();

        System.out.println("Creating/updating loggers");

        String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE);
        System.out.println("Log file: " + logFile);

        // Main loggers
        Engine.logConvertigo = Logger.getLogger("cems");
        Engine.logEngine = Logger.getLogger("cems.Engine");
        Engine.logAdmin = Logger.getLogger("cems.Admin");
        Engine.logBeans = Logger.getLogger("cems.Beans");
        Engine.logBillers = Logger.getLogger("cems.Billers");
        Engine.logEmulators = Logger.getLogger("cems.Emulators");
        Engine.logContext = Logger.getLogger("cems.Context");
        Engine.logUser = Logger.getLogger("cems.Context.User");
        Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor");
        Engine.logStatistics = Logger.getLogger("cems.Statistics");
        Engine.logScheduler = Logger.getLogger("cems.Scheduler");
        Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper");
        /** #3437 : Disabled ExternalBrowser feature because it's not terminated
        Engine.logExternalBrowser = Logger.getLogger("cems.ExternalBrowser");
        */
        Engine.logAudit = Logger.getLogger("cems.Context.Audit");

        // Managers
        Engine.logContextManager = Logger.getLogger("cems.ContextManager");
        Engine.logCacheManager = Logger.getLogger("cems.CacheManager");
        Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager");
        Engine.logJobManager = Logger.getLogger("cems.JobManager");
        Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager");
        Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager");
        Engine.logProxyManager = Logger.getLogger("cems.ProxyManager");
        Engine.logDevices = Logger.getLogger("cems.Devices");
        Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager");
        Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager");

        // Logger for compatibility issues
        Engine.log = new LogWrapper(Engine.logConvertigo);
        LogWrapper.initWrapper(Engine.logEmulators);

        try {
            Engine.logEngine.info("===========================================================");
            Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH);
            Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH);
            Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH);

            Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH);
            if (bProjectsDataCompatibilityMode) {
                Engine.logEngine.warn("Projects data compatibility mode required");
            }

            Engine.logEngine.info("Log: " + Engine.LOG_PATH);

            if (cloud_customer_name != null) {
                Engine.logEngine.info("Cloud customer: " + cloud_customer_name);
            }

            // Check environment and native dependencies
            if (!isStudioMode()) {
                StartupDiagnostics.run();
            }

            // Initializing the engine
            Engine.theApp = new Engine();

            CachedIntrospector.prefetchDatabaseObjectsAsync();

            try {
                Engine.theApp.usageMonitor = new UsageMonitor();
                Engine.theApp.usageMonitor.init();

                Thread vulture = new Thread(Engine.theApp.usageMonitor);
                vulture.setName("UsageMonitor");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the usage monitor.", e);
            }

            Engine.theApp.eventManager = new EventManager();
            Engine.theApp.eventManager.init();

            Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager();
            Engine.theApp.databaseObjectsManager.init();

            Engine.theApp.sqlConnectionManager = new JdbcConnectionManager();
            Engine.theApp.sqlConnectionManager.init();

            Engine.theApp.filePropertyManager = new FilePropertyManager();
            Engine.theApp.filePropertyManager.init();

            try {
                Engine.theApp.proxyManager = new ProxyManager();
                Engine.theApp.proxyManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the proxy manager.", e);
            }

            try {
                Engine.theApp.billingManager = new BillingManager();
                Engine.theApp.billingManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the billing manager.", e);
            }

            // Initialization of the trace player
            try {
                Engine.theApp.tracePlayerManager = new TracePlayerManager();
                Engine.theApp.tracePlayerManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the trace player.", e);
            }

            try {
                Engine.theApp.minificationManager = new MinificationManager();
                Engine.theApp.minificationManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the minification manager.", e);
            }

            try {
                Engine.theApp.couchDbManager = new CouchDbManager();
                Engine.theApp.couchDbManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the couchDbProxy manager.", e);
            }

            try {
                Engine.theApp.pluginsManager = new PluginsManager();
                Engine.theApp.pluginsManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the plugins manager.", e);
            }

            try {
                Engine.theApp.restApiManager = RestApiManager.getInstance();
                Engine.theApp.restApiManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the rest api manager.", e);
            }

            Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'.");

            // Creating the Carioca Authentication objects
            Engine.logEngine.debug("Creating the Carioca Authentication objects");
            String cariocaUserName = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
            String cariocaPassword = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
            Engine.theApp.authentications = new HashMap<String, Authentication>();

            // Initialization of the default TAS properties
            try {
                KeyManager.log = new LogWrapper(Engine.logEngine);
                Authentication auth = Engine.theApp.getAuthenticationObject("", null);
                auth.login(cariocaUserName, cariocaPassword);
            } catch (Exception e) {
                Engine.logEngine.error("The authentication to Carioca has failed (user name: \""
                        + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e);
            }

            // TODO : retrieve SOA flag from KeyManager
            isSOA = true;

            // Creation of the session manager
            Engine.theApp.sessionManager = new SessionManager();
            Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine));
            Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO);

            String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING);
            Engine.theApp.setMonitored(s.equalsIgnoreCase("true"));

            // Create Projects directory if needed
            File projectsDirFile = new File(Engine.PROJECTS_PATH);
            try {
                if (!projectsDirFile.exists())
                    projectsDirFile.mkdirs();
            } catch (Exception e) {
                Engine.logEngine.error("An error occured while creating projects directory.", e);
            }

            // Starts projects migration process
            MigrationManager.performProjectsMigration();

            // Security providers registration
            try {
                File dir = new File(Engine.CERTIFICATES_PATH);
                String[] files = dir.list(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith((".pkcs11"));
                    }
                });

                if (files != null && files.length > 0) {
                    Engine.logEngine.info("Registering security providers...");
                    try {
                        Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
                        String file;

                        for (int i = 0; i < files.length; i++) {
                            file = Engine.CERTIFICATES_PATH + "/" + files[i];
                            try {
                                Constructor<?> constructor = sunPKCS11Class
                                        .getConstructor(new Class[] { String.class });
                                Provider provider = (Provider) constructor.newInstance(new Object[] { file });
                                Security.addProvider(provider);
                                Engine.logEngine.info("Provider '" + provider.getName()
                                        + "' has been successfully registered.");
                            } catch (Exception e) {
                                Engine.logEngine.error("Unable to register security provider from file: " + file
                                        + " . Please check that the implementation library is in the Java lib path.");
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        Engine.logEngine.error(
                                "Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication.");
                    }
                }

                Provider[] providers = Security.getProviders();
                String sProviders = "";
                for (int i = 0; i < providers.length; i++) {
                    sProviders += providers[i].getName() + ", ";
                }
                Engine.logEngine.debug("Registered providers: " + sProviders);
            } catch (Exception e) {
                Engine.logEngine.error("Unable to register security providers.", e);
            }

            // Launch the cache manager
            try {
                String cacheManagerClassName = EnginePropertiesManager
                        .getProperty(PropertyName.CACHE_MANAGER_CLASS);
                Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName);
                Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).newInstance();
                Engine.theApp.cacheManager.init();

                Thread vulture = new Thread(Engine.theApp.cacheManager);
                Engine.theApp.cacheManager.executionThread = vulture;
                vulture.setName("CacheManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the cache manager.", e);
            }

            // Launch the thread manager
            try {
                Engine.theApp.threadManager = new ThreadManager();
                Engine.theApp.threadManager.init();

                Thread vulture = new Thread(Engine.theApp.threadManager);
                Engine.theApp.threadManager.executionThread = vulture;
                vulture.setName("ThreadManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.threadManager = null;
                Engine.logEngine.error("Unable to launch the thread manager.", e);
            }

            // Launch the context manager
            try {
                Engine.theApp.contextManager = new ContextManager();
                Engine.theApp.contextManager.init();

                Thread vulture = new Thread(Engine.theApp.contextManager);
                Engine.theApp.contextManager.executionThread = vulture;
                vulture.setName("ContextManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.contextManager = null;
                Engine.logEngine.error("Unable to launch the context manager.", e);
            }

            // Launch the security token manager
            Engine.theApp.securityTokenManager = new SecurityTokenManager();
            Engine.theApp.securityTokenManager.init();

            // Initialize the HttpClient
            try {
                Engine.logEngine.debug("HttpClient initializing...");

                Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true);
                Engine.theApp.httpClient4 = HttpUtils.makeHttpClient4(true);

                Engine.logEngine.debug("HttpClient initialized!");
            } catch (Exception e) {
                Engine.logEngine.error("Unable to initialize the HttpClient.", e);
            }

            // Initialization of the schedule manager
            Engine.theApp.schedulerManager = new SchedulerManager(true);

            // Initialization of the RSA manager
            Engine.theApp.rsaManager = new RsaManager();
            Engine.theApp.rsaManager.init();

            // Initialization of the External Browser manager
            /** #3437 : Disabled ExternalBrowser feature because it's not terminated
            Engine.theApp.externalBrowserManager = new ExternalBrowserManager();
            Engine.theApp.externalBrowserManager.init();
            */

            // Initialization of the Schema manager
            Engine.theApp.schemaManager = new SchemaManager();
            Engine.theApp.schemaManager.init();

            // XUL initialization
            String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
            if (xulrunner_url == null || xulrunner_url.equals("")) {
                xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL);
            }

            File f = new File(xulrunner_url);
            if (f.exists()) {
                xulrunner_url = f.getAbsolutePath();
                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
            } else {
                Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url
                        + " doesn't exist, fix it with xulrunner.url");
            }

            if (Engine.isEngineMode() && Engine.isLinux()
                    && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) {

                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                final String display = System.getenv("DISPLAY");
                if (display != null) {
                    try {
                        String port = System.getProperty("xvnc.port");
                        if (port == null) {
                            port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900);
                            System.setProperty("xvnc.port", port);
                        }
                        Engine.logEngine.debug("Xvnc should listen on " + port + " port");
                    } catch (Exception e) {
                    }
                    try {
                        File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc");
                        File Xvnc = new File(vncDir, "/Xvnc");
                        File fonts = new File(vncDir, "/fonts");
                        File wm = new File(vncDir, "/matchbox-window-manager");
                        if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) {
                            for (File file : GenericUtils.<File>asList(Xvnc, wm)) {
                                new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start()
                                        .waitFor();
                            }
                            String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH);
                            String geometry = EnginePropertiesManager
                                    .getProperty(PropertyName.LINUX_XVNC_GEOMETRY);
                            Engine.logEngine
                                    .debug("Xvnc will use depth " + depth + " and geometry " + geometry);
                            Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp",
                                    fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start();
                            Thread.sleep(500);
                            try {
                                int exit = pr_xvnc.exitValue();
                                InputStream err = pr_xvnc.getErrorStream();
                                byte[] buf = new byte[err.available()];
                                err.read(buf);
                                Engine.logEngine.debug("Xvnc failed to run with exit code " + exit
                                        + " and this error : <<" + new String(buf, "UTF-8") + ">>");
                            } catch (Exception e) {
                                new ProcessBuilder(wm.getAbsolutePath()).start();
                                Engine.logEngine.debug("Xvnc successfully started !");
                            }
                        } else {
                            Engine.logEngine.info(
                                    vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc");
                        }
                    } catch (Exception e) {
                        Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e);
                    }
                } else
                    Engine.logEngine
                            .warn("Trying to start Xvnc on Linux without DISPLAY environment variable !");
            }

            // SAP provider registration
            try {
                SapJcoDestinationDataProvider.init();
                Engine.logEngine.debug("SAP destination provider successfully registered");
            } catch (Throwable e) {
                Engine.logEngine.error("Error while registering SAP destination provider", e);
            }

            isStarted = true;

            Engine.logEngine.info("Convertigo engine started");
        } catch (Throwable e) {
            isStartFailed = true;
            Engine.logEngine.error("Unable to successfully start the engine.", e);
        }
    } else {
        Engine.logEngine.info("Convertigo engine already started");
    }
}

From source file:net.pms.PMS.java

/**
 * Initialisation procedure for PMS.//from  w  w w .  ja va 2 s .c o  m
 * @return true if the server has been initialized correctly. false if the server could
 * not be set to listen on the UPnP port.
 * @throws Exception
 */
private boolean init() throws Exception {
    // The public VERSION field is deprecated.
    // This is a temporary fix for backwards compatibility
    VERSION = getVersion();

    // call this as early as possible
    displayBanner();

    AutoUpdater autoUpdater = null;
    if (Build.isUpdatable()) {
        String serverURL = Build.getUpdateServerURL();
        autoUpdater = new AutoUpdater(serverURL, getVersion());
    }

    registry = createSystemUtils();

    if (!isHeadless()) {
        frame = new LooksFrame(autoUpdater, configuration);
    } else {
        logger.info("GUI environment not available");
        logger.info("Switching to console mode");
        frame = new DummyFrame();
    }

    /*
     * we're here:
     *
     *     main() -> createInstance() -> init()
     *
     * which means we haven't created the instance returned by get()
     * yet, so the frame appender can't access the frame in the
     * standard way i.e. PMS.get().getFrame(). we solve it by
     * inverting control ("don't call us; we'll call you") i.e.
     * we notify the appender when the frame is ready rather than
     * e.g. making getFrame() static and requiring the frame
     * appender to poll it.
     *
     * XXX an event bus (e.g. MBassador or Guava EventBus
     * (if they fix the memory-leak issue)) notification
     * would be cleaner and could support other lifecycle
     * notifications (see above).
     */
    FrameAppender.setFrame(frame);

    configuration.addConfigurationListener(new ConfigurationListener() {
        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if ((!event.isBeforeUpdate())
                    && PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
                frame.setReloadable(true);
            }
        }
    });

    frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png");
    RendererConfiguration.loadRendererConfigurations(configuration);
    logger.info("Checking MPlayer font cache. It can take a minute or so.");
    checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");

    if (Platform.isWindows()) {
        checkProcessExistence("MPlayer", true, configuration.getTempFolder(), configuration.getMplayerPath(),
                "dummy");
    }

    logger.info("Done!");

    // check the existence of Vsfilter.dll
    if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
        logger.info("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath());
        File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
        if (!vsFilterdll.exists()) {
            logger.info(
                    "VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth");
        }
    }

    // Check if VLC is found
    String vlcVersion = registry.getVlcVersion();
    String vlcPath = registry.getVlcPath();

    if (vlcVersion != null && vlcPath != null) {
        logger.info("Found VLC version " + vlcVersion + " at: " + vlcPath);

        Version vlc = new Version(vlcVersion);
        Version requiredVersion = new Version("2.0.2");

        if (vlc.compareTo(requiredVersion) <= 0) {
            logger.error("Only VLC versions 2.0.2 and above are supported");
        }
    }

    // check if Kerio is installed
    if (registry.isKerioFirewall()) {
        logger.info("Detected Kerio firewall");
    }

    // force use of specific dvr ms muxer when it's installed in the right place
    File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
    if (dvrsMsffmpegmuxer.exists()) {
        configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
    }

    // disable jaudiotagger logging
    LogManager.getLogManager()
            .readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes()));

    // wrap System.err
    System.setErr(new PrintStream(new SystemErrWrapper(), true));

    server = new HTTPServer(configuration.getServerPort());

    /*
     * XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
     * can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
     *
     * XXX: if a plugin requires initialization/notification even earlier than
     * this, then a new external listener implementing a new callback should be added
     * e.g. StartupListener.registeredExtensions()
     */
    try {
        ExternalFactory.lookup();
    } catch (Exception e) {
        logger.error("Error loading plugins", e);
    }

    // a static block in Player doesn't work (i.e. is called too late).
    // this must always be called *after* the plugins have loaded.
    // here's as good a place as any
    Player.initializeFinalizeTranscoderArgsListeners();

    // Initialize a player factory to register all players
    PlayerFactory.initialize(configuration);

    // Instantiate listeners that require registered players.
    ExternalFactory.instantiateLateListeners();

    // Any plugin-defined players are now registered, create the GUI view.
    frame.addEngines();

    boolean binding = false;

    try {
        binding = server.start();
    } catch (BindException b) {
        logger.info("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: "
                + b.getMessage());
        logger.info("Maybe another process is running or the hostname is wrong.");
    }

    new Thread("Connection Checker") {
        @Override
        public void run() {
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
            }

            if (foundRenderers.isEmpty()) {
                frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png");
            } else {
                frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
            }
        }
    }.start();

    if (!binding) {
        return false;
    }

    // initialize the cache
    if (configuration.getUseCache()) {
        initializeDatabase(); // XXX: this must be done *before* new MediaLibrary -> new MediaLibraryFolder
        mediaLibrary = new MediaLibrary();
        logger.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":"
                + server.getPort() + "/console/home");
    }

    // XXX: this must be called:
    //     a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
    //     b) *after* mediaLibrary is initialized, if enabled (above)
    getRootFolder(RendererConfiguration.getDefaultConf());

    frame.serverReady();

    // UPNPHelper.sendByeBye();
    Runtime.getRuntime().addShutdownHook(new Thread("PMS Listeners Stopper") {
        @Override
        public void run() {
            try {
                for (ExternalListener l : ExternalFactory.getExternalListeners()) {
                    l.shutdown();
                }
                UPNPHelper.shutDownListener();
                UPNPHelper.sendByeBye();
                logger.debug("Forcing shutdown of all active processes");
                for (Process p : currentProcesses) {
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ise) {
                        logger.trace("Forcing shutdown of process: " + p);
                        ProcessUtil.destroy(p);
                    }
                }
                get().getServer().stop();
                Thread.sleep(500);
            } catch (InterruptedException e) {
                logger.debug("Caught exception", e);
            }
        }
    });

    UPNPHelper.sendAlive();
    logger.trace("Waiting 250 milliseconds...");
    Thread.sleep(250);
    UPNPHelper.listen();

    return true;
}

From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java

public void populateDataToDatabaseRefFromFile(File fakeData, DatabaseRef databaseServer)
        throws CannotFindDatabaseDumperException, IOException, InterruptedException {
    this.reportIntegration.setFakeDataFileSize(fakeData.length());
    long currentTime = System.currentTimeMillis();
    logger.info(/*from w  ww.ja va2 s  .c o  m*/
            "Populating fake data on server: {} - database {} will be created with data from file {} which has size of {}",
            databaseServer.getHost(), DATABASE_SOURCE_NAME, fakeData.getAbsolutePath(),
            humanize.Humanize.binaryPrefix(fakeData.length()));
    DatabaseDriver databaseDriver = dbDumpersFactory.getDatabaseDumper(databaseServer);
    String[] restoreCommandLine = databaseDriver.getRestoreCommandLine();
    int i = 1;
    while (true) {
        Process process = this.runCommandLine(restoreCommandLine);
        OutputStream outputStream = process.getOutputStream();
        InputStream dumpFileInputStream = Files.asByteSource(fakeData).openStream();
        try {
            ByteStreams.copy(dumpFileInputStream, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {

        } finally {
            dumpFileInputStream.close();
        }
        process.waitFor();
        if (process.exitValue() == 0) {
            break;
        }
        dumpFileInputStream.close();
        outputStream.close();
        if (i >= populateDataRetry) {
            throw this.generateInterruptedExceptionFromProcess(process);
        }
        logger.warn("Retry {}/{}: fail to populate data.", i, populateDataRetry);
        i++;
    }
    this.reportIntegration.setPopulateToDatabaseTime((System.currentTimeMillis() - currentTime) / 1000);
    logger.info("Finished to populate fake data on server: {} \n Duration: {}", databaseServer.getHost(),
            humanize.Humanize.duration(this.reportIntegration.getPopulateToDatabaseTime()));
}

From source file:com.symbian.driver.plugins.romflash.Activator.java

public boolean FlashRom(String romLocation) {

    try {/*from w w  w  .j av  a 2  s  .c om*/
        File rom = new File(romLocation);
        if (method.compareToIgnoreCase("serial") == 0) {
            if (!(switchOff() && switchOn())) {
                LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing.");
                return false;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe");
            if (trgtTestFile.isFile()) {
                ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber,
                        rom.getCanonicalPath());
                ld.directory(trgtTestFile.getParentFile());
                Process pp = ld.start();
                LOGGER.log(Level.INFO, "started trgtest process");
                BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                    LOGGER.log(Level.INFO, line);
                }
                //String answer = sb.toString();

                try {
                    LOGGER.log(Level.INFO, "going to wait now for trgtest to finish");
                    pp.waitFor();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish.");
                }
                LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue());
                pp.destroy();

            } else {
                LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file.");
            }
        } else // usb rom loading
        {
            // switch the device off...
            switchOff();
            List<File> lis1 = Arrays.asList(File.listRoots());
            // get reboot plugin, and reboot the device
            switchOn(); // or just switch on as things may be
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File[] listRoots2 = File.listRoots();
            // find the drive that made the difference!!
            File diff = null;
            for (File root : listRoots2) {
                if (!lis1.contains(root)) // found new drive
                {
                    diff = root;
                    break;
                }
            }
            File romfl = new File(diff, rom.getName());
            romfl.delete();
            File aCopyFrom = new File(rom.getCanonicalPath());
            FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel();
            FileChannel lDstChannel = new FileOutputStream(romfl).getChannel();
            lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size());
            lSrcChannel.close();
            lDstChannel.close();

            File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe");
            if (syncFile.isFile()) {

                ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString());

                ld.directory(syncFile.getParentFile());
                ld.start();
                // wait 10 seconds for the rom to load ...
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
                }
            } else {
                LOGGER.log(Level.SEVERE, "Could not find sync.exe file.");
            }
        }
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage());
        return false;
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
    }
    return true;
}

From source file:eu.cloud4soa.c4sgitservice.ws.GitServices.java

@WebMethod
public String[] generateKeyPairForUser(String username, String password) {
    String[] res = { "1", "Internal Server Error" };
    int retvalue = 0;
    if (userdao != null) {
        List userlist = userdao.findByUsernameAndPassword(username, password);
        if (userlist != null && !userlist.isEmpty()) {
            //Step 1 - Execute command
            try {
                Process child = Runtime.getRuntime().exec(new String[] { "ssh-keygen", //
                        "-q", // quiet
                        "-t", "rsa", //
                        "-P", "", // Zero password
                        "-C", username, //
                        "-f", username //
                });//from   w w w . j  av  a 2 s .co m
                child.waitFor();

                //Get the input stream and read from it
                InputStream in = child.getInputStream();
                int c;
                while ((c = in.read()) != -1) {
                    //System.out.print((char)c);
                }
                in.close();
                retvalue = child.exitValue();
                logger.info("ssh-keygen returned: " + retvalue);
                //Step 2 - read file
                if (retvalue == 0) { //Everything OK
                    try {
                        String pub, priv = "";
                        pub = Util.readfile(username + ".pub");
                        priv = Util.readfile(username);
                        //cleanup
                        try {
                            String command1 = "rm " + username + ".pub";
                            Process child1 = Runtime.getRuntime().exec(command1);
                            String command2 = "rm " + username;
                            Process child2 = Runtime.getRuntime().exec(command2);
                            child1.waitFor();
                            child2.waitFor();
                            logger.info("Success-Key-Pair created for User with username: ");
                            res = new String[] { "0", pub, priv };
                        } catch (Exception ex) {
                            logger.error("Error-Cleaning temporary files");
                            res = new String[] { "1", "Error-Cleaning temporary files" };
                        }
                    } catch (Exception ex) {
                        logger.error("Error-Reading temporary files");
                        res = new String[] { "1", "Error-Reading temporary files" };
                    }
                } else {
                    logger.error("Error-Internal ssh-keygen error");
                    res = new String[] { "1", "Internal ssh-keygen error" };
                }
            } catch (Exception ex) {
                logger.error("Error-Internal Server Error while executing ssh-keygen");
                res = new String[] { "1", "Error-Internal Server Error while executing ssh-keygen" };
            }

        } else {
            logger.error("User with username: " + username + " password: " + password + " does not exist");
            res = new String[] { "1",
                    "Error-User with username: " + username + " password: " + password + " does not exist" };
        }
    } else {
        logger.error("SpringBean userdao cannot be instantiated");
        res = new String[] { "1", "Error-Internal Server - Spring Bean cannot be initialized" };
    }

    return res;
}

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

/**
 * This method creates multi page pdf using ghost script command.
 * // w  ww  . j av a 2s  .  c o  m
 * @param batchInstanceThread {@link BatchInstanceThread}
 * @param pages11 {@link String []}
 * @param gsCmdParam {@link String}
 * @param ghostScriptCommand {@link String}
 * @param maxFilesProcessedPerLoop {@link Integer}
 * @param documentIdInt {@link String}
 */
public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final String[] pages11,
        final String gsCmdParam, final String ghostScriptCommand, final Integer maxFilesProcessedPerLoop,
        final String documentIdInt) {
    if (pages11 != null && pages11.length > 0) {
        this.pages = new String[pages11.length];
        this.pages = pages11.clone();
        this.documentId = documentIdInt;
        batchInstanceThread.add(new AbstractRunnable() {

            @Override
            public void run() {
                String ghostScriptPath = System.getenv(IImageMagickCommonConstants.GHOSTSCRIPT_ENV_VARIABLE);
                List<String> ghostScriptCommandList = new ArrayList<String>();
                File systemFileFolderPath = new File(pages[0]);
                String systemFolderPath = systemFileFolderPath.getParent();
                String outputFileName = "";
                String[] gsCmdParams = gsCmdParam.split(SPACE);
                int noOfPages = pages.length;
                int currPageNo = 0;
                int counter = 1;
                File fileToBeDeleted = null;
                String prevTempFilePath = null;
                String nextTempFilePath = null;
                String tempFilePath = pages[noOfPages - 1].substring(0,
                        pages[noOfPages - 1].lastIndexOf('.') == -1 ? pages[noOfPages].length()
                                : pages[noOfPages - 1].lastIndexOf('.'));
                boolean isLastPage = false;
                boolean isDBatchAddedToGSCmd = false;
                while (!isLastPage) {
                    ghostScriptCommandList.clear();
                    LOGGER.info("creating ghostscript command for multipage pdf creation.");
                    int maxNoOfPages = counter * maxFilesProcessedPerLoop;
                    for (String param : gsCmdParams) {
                        if (!isDBatchAddedToGSCmd
                                && param.trim().equalsIgnoreCase(GHOST_SCRIPT_COMMAND_OUTPUT_PARAMETERS)) {
                            isDBatchAddedToGSCmd = true;
                        }
                        ghostScriptCommandList.add(param);
                    }
                    if (!isDBatchAddedToGSCmd) {
                        ghostScriptCommandList.add(GHOST_SCRIPT_COMMAND_OUTPUT_PARAMETERS);
                    }
                    if (maxNoOfPages >= noOfPages - 1) {
                        if (OSUtil.isWindows()) {
                            outputFileName = pages[noOfPages - 1]
                                    .substring(pages[noOfPages - 1].lastIndexOf(File.separator) + 1);
                            ghostScriptCommandList.add(GHOST_SCRIPT_COMMAND_OUTPUT_FILE_PARAM + outputFileName);
                        } else if (OSUtil.isUnix()) {
                            ghostScriptCommandList
                                    .add(GHOST_SCRIPT_COMMAND_OUTPUT_FILE_PARAM + pages[noOfPages - 1]);
                        }

                        isLastPage = true;
                    } else {
                        nextTempFilePath = tempFilePath + '_' + '_' + counter + documentId
                                + FileType.PDF.getExtensionWithDot();
                        outputFileName = nextTempFilePath
                                .substring(nextTempFilePath.lastIndexOf(File.separator) + 1);
                        if (OSUtil.isWindows()) {
                            ghostScriptCommandList.add(DOUBLE_QUOTES + GHOST_SCRIPT_COMMAND_OUTPUT_FILE_PARAM
                                    + outputFileName + DOUBLE_QUOTES);
                        } else if (OSUtil.isUnix()) {
                            ghostScriptCommandList
                                    .add(GHOST_SCRIPT_COMMAND_OUTPUT_FILE_PARAM + nextTempFilePath);
                        }
                    }
                    if (prevTempFilePath != null) {
                        ghostScriptCommandList.add(prevTempFilePath);
                        fileToBeDeleted = new File(prevTempFilePath);
                    }
                    prevTempFilePath = nextTempFilePath;
                    counter++;
                    for (; currPageNo < noOfPages - 1 && currPageNo < maxNoOfPages; currPageNo++) {
                        if (OSUtil.isWindows()) {
                            ghostScriptCommandList
                                    .add(DOUBLE_QUOTES
                                            + pages[currPageNo].substring(
                                                    pages[currPageNo].lastIndexOf(File.separator) + 1)
                                            + DOUBLE_QUOTES);

                        } else if (OSUtil.isUnix()) {
                            ghostScriptCommandList.add(pages[currPageNo]);
                        }
                    }
                    List<String> commandList = new ArrayList<String>();
                    if (OSUtil.isWindows()) {
                        String absoluteFilePath = systemFolderPath + File.separator + outputFileName;
                        String absoluteGhostScriptParametersFilePath = absoluteFilePath.substring(0,
                                absoluteFilePath.lastIndexOf('.')) + FileType.SER.getExtensionWithDot();
                        File ghostScriptCommandParametersFile = new File(absoluteGhostScriptParametersFilePath);
                        writeGhosScriptParametersToFile(ghostScriptCommandParametersFile,
                                ghostScriptCommandList);
                        makeCommandForWindows(commandList, ghostScriptPath, systemFolderPath,
                                absoluteGhostScriptParametersFilePath);
                    } else if (OSUtil.isUnix()) {
                        commandList.add(ghostScriptPath + File.separator + ghostScriptCommand);
                        commandList.addAll(ghostScriptCommandList);
                    }

                    LOGGER.info("Command for multi page pdf creation : " + commandList);
                    String[] cmds = (String[]) commandList.toArray(new String[commandList.size()]);
                    executeCreatePdfCommand(fileToBeDeleted, cmds);
                }
                if (fileToBeDeleted != null && fileToBeDeleted.exists()) {
                    LOGGER.info("Deleting temporary file : " + fileToBeDeleted.getAbsolutePath());
                    fileToBeDeleted.delete();
                }
            }

            private void executeCreatePdfCommand(File fileToBeDeleted, String[] cmds) {
                try {
                    Process process = Runtime.getRuntime().exec(cmds);
                    InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
                    BufferedReader input = new BufferedReader(inputStreamReader);
                    String line = null;
                    do {
                        line = input.readLine();
                        LOGGER.info(line);
                    } while (line != null);
                    int exitValue = process.exitValue();
                    if (exitValue != 0) {
                        LOGGER.error("Process exited with an invalid exit value : " + exitValue);
                        setDcmaApplicationException(
                                new DCMAApplicationException(MULTIPAGE_PDF_CREATION_ERROR_MSG));
                    }
                    if (fileToBeDeleted != null && fileToBeDeleted.exists()) {
                        LOGGER.info("Deleting temporary file : " + fileToBeDeleted.getAbsolutePath());
                        fileToBeDeleted.delete();
                    }
                } catch (IOException e) {
                    LOGGER.error(MULTIPAGE_PDF_CREATION_ERROR_MSG + e.getMessage(), e);
                    setDcmaApplicationException(
                            new DCMAApplicationException(MULTIPAGE_PDF_CREATION_ERROR_MSG + e.getMessage(), e));
                } catch (SecurityException se) {
                    LOGGER.error("Cannot delete the temporary file : " + fileToBeDeleted.getAbsolutePath()
                            + se.getMessage(), se);
                }
            }

            private void writeGhosScriptParametersToFile(File file, List<String> ghostScriptCommandList) {
                LOGGER.info("Writing ghostscript parameters to :" + file.getAbsolutePath());
                StringBuffer ghostScriptParametersBuffer = new StringBuffer();
                for (String command : ghostScriptCommandList) {
                    ghostScriptParametersBuffer.append(command);
                    ghostScriptParametersBuffer.append(SPACE);
                }
                try {
                    FileUtils.writeStringToFile(file, ghostScriptParametersBuffer.toString());
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }

            private void makeCommandForWindows(List<String> commandList, String ghostScriptPath,
                    String systemFolderPath, String ghostScriptParametersFileAbsolutePath) {
                LOGGER.info("Forming Command for Ghostscript Executor(Windows).");
                commandList.add(System.getenv(GS_PDF_EXECUTOR_PATH));
                commandList.add(
                        DOUBLE_QUOTES + ghostScriptPath + File.separator + ghostScriptCommand + DOUBLE_QUOTES);
                commandList.add(DOUBLE_QUOTES + systemFolderPath + DOUBLE_QUOTES);
                commandList.add(DOUBLE_QUOTES + ghostScriptParametersFileAbsolutePath + DOUBLE_QUOTES);
            }
        });
    }
}