Example usage for java.lang Thread setDaemon

List of usage examples for java.lang Thread setDaemon

Introduction

In this page you can find the example usage for java.lang Thread setDaemon.

Prototype

public final void setDaemon(boolean on) 

Source Link

Document

Marks this thread as either a #isDaemon daemon thread or a user thread.

Usage

From source file:ch.entwine.weblounge.kernel.site.SiteDispatcherServiceImpl.java

/**
 * Callback for OSGi's declarative services component activation.
 * /*from ww w  . ja v  a2 s .c o  m*/
 * @param context
 *          the component context
 * @throws IOException
 *           if reading from the configuration admin service fails
 * @throws ConfigurationException
 *           if service configuration fails
 */
void activate(ComponentContext context) throws IOException, ConfigurationException {

    BundleContext bundleContext = context.getBundleContext();
    logger.info("Starting site dispatcher");

    // Configure the jasper work directory where compiled java classes go
    String tmpDir = System.getProperty("java.io.tmpdir");
    jasperScratchDir = PathUtils.concat(tmpDir, DEFAULT_JASPER_SCRATCH_DIR);
    jasperConfig.put(OPT_JASPER_SCRATCHDIR, jasperScratchDir);

    // Try to get hold of the service configuration
    ServiceReference configAdminRef = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
    if (configAdminRef != null) {
        ConfigurationAdmin configAdmin = (ConfigurationAdmin) bundleContext.getService(configAdminRef);
        Dictionary<?, ?> config = configAdmin.getConfiguration(SERVICE_PID).getProperties();
        if (config != null) {
            configure(config);
        } else {
            logger.debug("No customized configuration for site dispatcher found");
        }
    } else {
        logger.debug("No configuration admin service found while looking for site dispatcher configuration");
    }

    servletRegistrations = new HashMap<Site, ServiceRegistration>();

    logger.debug("Site dispatcher activated");

    // Register for changing sites
    siteManager.addSiteListener(this);

    // Process sites that have already been registered
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (Iterator<Site> si = siteManager.sites(); si.hasNext();) {
                addSite(si.next());
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}./*from   w ww .ja v a 2s  .co m*/
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Duration sessionTimeout, Credentials credentials, Optional<String> chrootPath,
        Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = (int) Preconditions.checkNotNull(sessionTimeout).inMillis();
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            new Function<InetSocketAddress, String>() {
                @Override
                public String apply(InetSocketAddress addr) {
                    return addr.getHostName() + ":" + addr.getPort();
                }
            });
    this.zooKeeperServers = Joiner.on(',').join(servers);
    this.connectString = this.zooKeeperServers.concat(chrootPath.or(""));
}

From source file:com.intuit.tank.harness.APITestHarness.java

private void startHttp(String baseUrl) {
    isLocal = false;//from   w  w w.  jav  a 2  s.co m
    CommandListener.startHttpServer(tankConfig.getAgentConfig().getAgentPort());
    if (baseUrl == null) {
        baseUrl = AmazonUtil.getControllerBaseUrl();
    }
    AgentServiceClient client = new AgentServiceClient(baseUrl);
    String instanceUrl = null;
    int tries = 0;
    while (instanceUrl == null) {
        try {
            instanceUrl = "http://" + AmazonUtil.getPublicHostName() + ":"
                    + tankConfig.getAgentConfig().getAgentPort();
            LOG.info("MyInstanceURL  = " + instanceUrl);
        } catch (IOException e1) {
            tries++;
            if (tries < 10) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // ignore
                }
            } else {
                LOG.error("Error getting amazon host. maybe local.");
                String publicIp = new HostInfo().getPublicIp();

                if (!publicIp.equals(HostInfo.UNKNOWN)) {
                    instanceUrl = "http://" + publicIp + ":" + tankConfig.getAgentConfig().getAgentPort();
                    LOG.info("MyInstanceURL from hostinfo  = " + instanceUrl);
                } else {
                    instanceUrl = "http://localhost:" + tankConfig.getAgentConfig().getAgentPort();
                }
            }
        }
    }
    LOG.info("MyInstanceURL  = " + instanceUrl);
    if (capacity < 0) {
        capacity = AmazonUtil.getCapacity();
    }
    VMRegion region = VMRegion.STANDALONE;
    if (AmazonUtil.isInAmazon()) {
        try {
            region = AmazonUtil.getVMRegion();
        } catch (IOException e) {
            LOG.warn(LogUtil.getLogMessage("Error getting region. using CUSTOM...", LogEventType.System));
        }
    }
    if (agentRunData.getJobId() == null) {
        agentRunData.setJobId(AmazonUtil.getJobId());
        agentRunData.setStopBehavior(AmazonUtil.getStopBehavior());
    }

    LogUtil.getLogEvent().setJobId(agentRunData.getJobId());
    LOG.info(LogUtil.getLogMessage("Active Profile" + agentRunData.getActiveProfile().getDisplayName()));
    AgentData data = new AgentData(agentRunData.getJobId(), instanceId, instanceUrl, capacity, region,
            AmazonUtil.getZone());
    try {
        AgentTestStartData startData = null;
        int count = 0;
        LOG.info(LogUtil.getLogMessage("Sending AgentData to controller: " + data.toString(),
                LogEventType.System));
        while (count < 10) {
            try {
                startData = client.agentReady(data);
                break;
            } catch (Exception e) {
                LOG.error("Error sending ready: " + e, e);
                count++;
            }
        }
        writeXmlToFile(startData.getScriptUrl());

        agentRunData.setNumUsers(startData.getConcurrentUsers());
        agentRunData.setNumStartUsers(startData.getStartUsers());
        agentRunData.setRampTime(startData.getRampTime());
        agentRunData.setJobId(startData.getJobId());
        agentRunData.setUserInterval(startData.getUserIntervalIncrement());
        agentRunData.setSimulationTime(startData.getSimulationTime());
        agentRunData.setAgentInstanceNum(startData.getAgentInstanceNum());
        agentRunData.setTotalAgents(startData.getTotalAgents());

        if (startData.getDataFiles() != null) {
            for (DataFileRequest dfRequest : startData.getDataFiles()) {
                saveDataFile(dfRequest);
            }
        }
        Thread t = new Thread(new StartedChecker());
        t.setName("StartedChecker");
        t.setDaemon(false);
        t.start();
    } catch (Exception e) {
        LOG.error("Error communicating with controller: " + e, e);
        System.exit(0);
    }
}

From source file:io.snappydata.test.dunit.standalone.ProcessManager.java

private void linkStreams(final int vmNum, final ProcessHolder holder, final InputStream in,
        final PrintStream out) {
    Thread ioTransport = new Thread() {
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String vmName = (vmNum == -2) ? "[locator]" : "[vm_" + vmNum + "]";
            try {
                String line = reader.readLine();
                while (line != null) {
                    out.print(vmName);//  w  ww.  j  a v a  2s  .  com
                    out.println(line);
                    line = reader.readLine();
                }
            } catch (Exception e) {
                if (!holder.isKilled()) {
                    out.println("Error transporting IO from child process");
                    e.printStackTrace(out);
                }
            }
        }
    };

    ioTransport.setDaemon(true);
    ioTransport.start();
}

From source file:zipkin.execjar.ExecJarRule.java

@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        public void evaluate() throws Throwable {
            try {
                ProcessBuilder bootBuilder = new ProcessBuilder("java", "-jar", execJar);
                bootBuilder.environment().put("SERVER_PORT", String.valueOf(port()));
                bootBuilder.environment().putAll(environment);
                bootBuilder.redirectErrorStream(true);
                bootApp = bootBuilder.start();

                CountDownLatch startedOrCrashed = new CountDownLatch(1);
                Thread consoleReader = new Thread(() -> {
                    boolean foundStartMessage = false;
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(bootApp.getInputStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.indexOf("JVM running for") != -1) {
                                foundStartMessage = true;
                                startedOrCrashed.countDown();
                            }//w  w  w.  j  a  v a  2  s.c o m
                            console.add(line);
                        }
                    } catch (Exception e) {
                    } finally {
                        if (!foundStartMessage)
                            startedOrCrashed.countDown();
                    }
                });
                consoleReader.setDaemon(true);
                consoleReader.start();

                if (!startedOrCrashed.await(10, TimeUnit.SECONDS)) {
                    throw new AssumptionViolatedException("Took too long to start or crash");
                }

                base.evaluate();
            } finally {
                bootApp.destroy();
            }
        }
    };
}

From source file:com.amazon.mws.shared.MwsConnection.java

/**
 * Get the shared executor service that is used by async calls if no
 * executor is supplied./*from  w  w  w  . j a v  a 2 s  .c om*/
 * 
 * @return The shared executor service.
 */
private ExecutorService getSharedES() {
    synchronized (this.getClass()) {
        if (sharedES != null) {
            return sharedES;
        }
        sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    public Thread newThread(Runnable task) {
                        Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement());
                        thread.setDaemon(true);
                        thread.setPriority(Thread.NORM_PRIORITY);
                        return thread;
                    }
                }, new RejectedExecutionHandler() {
                    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                        if (!executor.isShutdown()) {
                            log.warn("MWSClient async queue full, running on calling thread.");
                            task.run();
                        } else {
                            throw new RejectedExecutionException();
                        }
                    }
                });
        return sharedES;
    }
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

public void appendEntries(RaftLog logMgr, long lastApplied) {
    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;//from   w w  w  .  j  a va 2 s.co m
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection conn = connections.get(server);
        long startIndex = logMgr.getFollowerMatchIndex(server) + 1;

        LOG.info(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
        Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), conn,
                getRaftNode().getRaftLog(), getRaftNode().getServerInfo(), getRaftNode().getCurrentTerm(),
                logMgr.getCommitIndex(), startIndex - 1, logMgr.getLogTerm(startIndex - 1),
                logMgr.getLogEntries(startIndex, lastApplied), lastApplied));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:fish.payara.maven.plugins.micro.StartMojo.java

private void redirectStream(final InputStream inputStream, final PrintStream printStream) {
    final Thread thread = new Thread(threadGroup, () -> {
        BufferedReader br;/*from  w  w w  . j av  a 2s  . co m*/
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
                printStream.println(line);
                if (!immediateExit && sb.toString().contains(MICRO_READY_MESSAGE)) {
                    microProcessorThread.interrupt();
                    br.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    thread.setDaemon(false);
    thread.start();
}

From source file:com.amazonservices.mws.client.MwsConnection.java

/**
 * Get the shared executor service that is used by async calls if no
 * executor is supplied.//w w w  .j  a v  a  2 s .  co  m
 * 
 * @return The shared executor service.
 */
private ExecutorService getSharedES() {
    synchronized (this.getClass()) {
        if (sharedES != null) {
            return sharedES;
        }
        sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    //@Override
                    public Thread newThread(Runnable task) {
                        Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement());
                        thread.setDaemon(true);
                        thread.setPriority(Thread.NORM_PRIORITY);
                        return thread;
                    }
                }, new RejectedExecutionHandler() {
                    //@Override
                    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                        if (!executor.isShutdown()) {
                            log.warn("MWSClient async queue full, running on calling thread.");
                            task.run();
                        } else {
                            throw new RejectedExecutionException();
                        }
                    }
                });
        return sharedES;
    }
}

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();//from  w ww  .ja  va2s. c  o  m
            } 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");
    }
}