⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 wrapperstartstopapp.java

📁 java程序写系统的服务
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: start(args) Will wait up to " + maxLoops
                    + " seconds for the main method to complete." );
            }
        }
        
        Thread mainThread = new Thread( this, "WrapperStartStopAppMain" );
        synchronized(this)
        {
            m_startMainArgs = args;
            mainThread.start();
            
            // To avoid problems with the main thread starting slowly on heavily loaded systems,
            //  do not continue until the thread has actually started.
            while ( !m_mainStarted )
            {
                try
                {
                    this.wait( 1000 );
                }
                catch ( InterruptedException e )
                {
                    // Continue.
                }
            }
            
            // Wait for startup main method to complete.
            int loops = 0;
            while ( ( loops < maxLoops ) && ( !m_mainComplete ) )
            {
                try
                {
                    this.wait( 1000 );
                }
                catch ( InterruptedException e )
                {
                    // Continue.
                }
                
                if ( !m_mainComplete )
                {
                    // If maxLoops is large then this could take a while.  Notify the
                    //  WrapperManager that we are still starting so it doesn't give up.
                    WrapperManager.signalStarting( 5000 );
                }
                
                loops++;
            }
            
            // Always set the flag stating that the start method completed.  This is needed
            //  so the run method can decide whether or not it needs to be responsible for
            //  shutting down the JVM in the event of an exception thrown by the start main
            //  method.
            m_startComplete = true;
            
            // The main exit code will be null unless an error was thrown by the start
            //  main method.
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: start(args) end.  Main Completed="
                    + m_mainComplete + ", exitCode=" + m_mainExitCode );
            }
            return m_mainExitCode;
        }
    }
    
    /**
     * Called when the application is shutting down.
     */
    public int stop( int exitCode )
    {
        if ( WrapperManager.isDebugEnabled() )
        {
            System.out.println( "WrapperStartStopApp: stop(" + exitCode + ")" );
        }
        
        // Execute the main method in the stop class
        Throwable t = null;
        try
        {
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: invoking stop main method" );
            }
            m_stopMainMethod.invoke( null, new Object[] { m_stopMainArgs } );
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: stop main method completed" );
            }
            
            if ( m_stopWait )
            {
                // This feature exists to make sure the stop process waits for the main
                //  application to fully shutdown.  This can only be done by looking for
                //  and counting the number of non-daemon threads still running in the
                //  system.
                
                int systemThreadCount = WrapperSystemPropertyUtil.getIntProperty(
                    WrapperStartStopApp.class.getName() + ".systemThreadCount", 1 );
                systemThreadCount = Math.max( 0, systemThreadCount ); 
                
                int threadCnt;
                while( ( threadCnt = getNonDaemonThreadCount() ) > systemThreadCount )
                {
                    if ( WrapperManager.isDebugEnabled() )
                    {
                        System.out.println( "WrapperStartStopApp: stopping.  Waiting for "
                            + ( threadCnt - systemThreadCount ) + " threads to complete." );
                    }
                    try
                    {
                        Thread.sleep( 1000 );
                    }
                    catch ( InterruptedException e )
                    {
                    }
                }
            }
            
            // Success
            return exitCode;
        }
        catch ( IllegalAccessException e )
        {
            t = e;
        }
        catch ( IllegalArgumentException e )
        {
            t = e;
        }
        catch ( InvocationTargetException e )
        {
            t = e;
        }
        
        // If we get here, then an error was thrown.
        System.out.println( "Encountered an error running stop main: " + t );

        // We should print a stack trace here, because in the case of an 
        // InvocationTargetException, the user needs to know what exception
        // their app threw.
        t.printStackTrace();
        
        // Return a failure exit code
        return 1;
    }
    
    /**
     * Called whenever the native wrapper code traps a system control signal
     *  against the Java process.  It is up to the callback to take any actions
     *  necessary.  Possible values are: WrapperManager.WRAPPER_CTRL_C_EVENT, 
     *    WRAPPER_CTRL_CLOSE_EVENT, WRAPPER_CTRL_LOGOFF_EVENT, or 
     *    WRAPPER_CTRL_SHUTDOWN_EVENT
     */
    public void controlEvent( int event )
    {
        if ( ( event == WrapperManager.WRAPPER_CTRL_LOGOFF_EVENT )
            && WrapperManager.isLaunchedAsService() )
        {
            // Ignore
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: controlEvent(" + event + ") Ignored" );
            }
        }
        else
        {
            if ( WrapperManager.isDebugEnabled() )
            {
                System.out.println( "WrapperStartStopApp: controlEvent(" + event + ") Stopping" );
            }
            WrapperManager.stop( 0 );
            // Will not get here.
        }
    }
    
    /*---------------------------------------------------------------
     * Methods
     *-------------------------------------------------------------*/
    /**
     * Returns a count of all non-daemon threads in the JVM, starting with the top
     *  thread group.
     *
     * @return Number of non-daemon threads.
     */
    private int getNonDaemonThreadCount()
    {
        // Locate the top thread group.
        ThreadGroup topGroup = Thread.currentThread().getThreadGroup();
        while ( topGroup.getParent() != null )
        {
            topGroup = topGroup.getParent();
        }
        
        // Get a list of all threads.  Use an array that is twice the total number of
        //  threads as the number of running threads may be increasing as this runs.
        Thread[] threads = new Thread[topGroup.activeCount() * 2];
        topGroup.enumerate( threads, true );
        
        // Only count any non daemon threads which are 
        //  still alive other than this thread.
        int liveCount = 0;
        for ( int i = 0; i < threads.length; i++ )
        {
            /*
            if ( threads[i] != null )
            {
                System.out.println( "Check " + threads[i].getName() + " daemon="
                    + threads[i].isDaemon() + " alive=" + threads[i].isAlive() );
            }
            */
            if ( ( threads[i] != null ) && threads[i].isAlive() )
            {
                // Do not count this thread.
                if ( ( Thread.currentThread() != threads[i] ) && ( !threads[i].isDaemon() ) )
                {
                    // Non-Daemon living thread
                    liveCount++;
                    //System.out.println( "  -> Non-Daemon" );
                }
            }
        }
        //System.out.println( "  => liveCount = " + liveCount );
        
        return liveCount;
    }
    
    /**
     * Returns the main method of the specified class.  If there are any problems,
     *  an error message will be displayed and the Wrapper will be stopped.  This
     *  method will only return if it has a valid method.
     */
    private Method getMainMethod( String className )
    {
        // Look for the start class by name
        Class mainClass;
        try
        {
            mainClass = Class.forName( className );
        }
        catch ( ClassNotFoundException e )
        {
            System.out.println( "WrapperStartStopApp: Unable to locate the class " + className
                + ": " + e );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        catch ( LinkageError e )
        {
            System.out.println( "WrapperStartStopApp: Unable to locate the class " + className
                + ": " + e );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        
        // Look for the start method
        Method mainMethod;
        try
        {
            // getDeclaredMethod will return any method named main in the specified class,
            //  while getMethod will only return public methods, but it will search up the
            //  inheritance path.
            mainMethod = mainClass.getMethod( "main", new Class[] { String[].class } );
        }
        catch ( NoSuchMethodException e )
        {
            System.out.println(
                "WrapperStartStopApp: Unable to locate a public static main method in "
                + "class " + className + ": " + e );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        catch ( SecurityException e )
        {
            System.out.println(
                "WrapperStartStopApp: Unable to locate a public static main method in "
                + "class " + className + ": " + e );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        
        // Make sure that the method is public and static
        int modifiers = mainMethod.getModifiers();
        if ( !( Modifier.isPublic( modifiers ) && Modifier.isStatic( modifiers ) ) )
        {
            System.out.println( "WrapperStartStopApp: The main method in class " + className
                + " must be declared public and static." );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        
        return mainMethod;
    }
    
    private String[] getArgs( String[] args, int argBase )
    {
        // The arg at the arg base should be a count of the number of available arguments.
        int argCount;
        try
        {
            argCount = Integer.parseInt( args[argBase] );
        }
        catch ( NumberFormatException e )
        {
            System.out.println( "WrapperStartStopApp: Illegal argument count: " + args[argBase] );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        if ( argCount < 0 )
        {
            System.out.println( "WrapperStartStopApp: Illegal argument count: " + args[argBase] );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        
        // Make sure that there are enough arguments in the array.
        if ( args.length < argBase + 1 + argCount )
        {
            System.out.println( "WrapperStartStopApp: Not enough argments.  Argument count of "
                + argCount + " was specified." );
            showUsage();
            WrapperManager.stop( 1 );
            return null;  // Will not get here
        }
        
        // Create the argument array
        String[] mainArgs = new String[argCount];
        System.arraycopy( args, argBase + 1, mainArgs, 0, argCount );
        
        return mainArgs;
    }
    
    /**
     * Displays application usage
     */
    protected void showUsage()
    {
        System.out.println();
        System.out.println(
            "WrapperStartStopApp Usage:" );
        System.out.println(
            "  java org.tanukisoftware.wrapper.WrapperStartStopApp {start_class} {start_arg_count} "
            + "[start_arguments] {stop_class} {stop_wait} {stop_arg_count} [stop_arguments]" );
        System.out.println();
        System.out.println(
            "Where:" );
        System.out.println(
            "  start_class:     The fully qualified class name to run to start the " );
        System.out.println(
            "                   application." );
        System.out.println(
            "  start_arg_count: The number of arguments to be passed to the start class's " );
        System.out.println(
            "                   main method." );
        System.out.println(
            "  stop_class:      The fully qualified class name to run to stop the " );
        System.out.println(
            "                   application." );
        System.out.println(
            "  stop_wait:       When stopping, should the Wrapper wait for all threads to " );
        System.out.println(
            "                   complete before exiting (true/false)." );
        System.out.println(
            "  stop_arg_count:  The number of arguments to be passed to the stop class's " );
        System.out.println(
            "                   main method." );
        
        System.out.println(
            "  app_parameters:  The parameters that would normally be passed to the" );
        System.out.println(
            "                   application." );
    }
    
    /*---------------------------------------------------------------
     * Main Method
     *-------------------------------------------------------------*/
    /**
     * Used to Wrapper enable a standard Java application.  This main
     *  expects the first argument to be the class name of the application
     *  to launch.  All remaining arguments will be wrapped into a new
     *  argument list and passed to the main method of the specified
     *  application.
     */
    public static void main( String args[] )
    {
        new WrapperStartStopApp( args );
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -