Example usage for java.lang System setOut

List of usage examples for java.lang System setOut

Introduction

In this page you can find the example usage for java.lang System setOut.

Prototype

public static void setOut(PrintStream out) 

Source Link

Document

Reassigns the "standard" output stream.

Usage

From source file:org.jkiss.dbeaver.core.application.DBeaverApplication.java

private void stopDebugWriter() {
    if (oldSystemOut != null)
        System.setOut(oldSystemOut);
    if (oldSystemErr != null)
        System.setErr(oldSystemErr);

    if (debugWriter != null) {
        IOUtils.close(debugWriter);/*from w  ww . j a va2  s  .c om*/
        debugWriter = null;
    }
}

From source file:com.vuze.android.remote.service.VuzeService.java

@Override
public void onCreate() {
    super.onCreate();
    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "VuzeService: onCreate");
    }//from w  w  w.ja v  a2 s  . c o m

    instance = this;
    if (BuildConfig.DEBUG) {
        //android.os.Debug.waitForDebugger();
    }

    if (!AndroidUtils.hasPermisssion(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // TODO: implement check
        Log.d(TAG, "onCreate: No WRITE_EXTERNAL_STORAGE permission");
    }

    // requires WRITE_EXTERNAL_STORAGE
    File storageRoot = Environment.getExternalStorageDirectory();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        File dirDoc = Environment.getExternalStoragePublicDirectory("Documents");
        File dirDl = Environment.getExternalStoragePublicDirectory("Download");
        File dirVideo = Environment.getExternalStoragePublicDirectory("Movies");
        File dirAudio = Environment.getExternalStoragePublicDirectory("Music");
        if (CorePrefs.DEBUG_CORE) {
            Log.d("VuzeService", "Doc=" + dirDoc + "\nDL=" + dirDl + "\nVideo=" + dirVideo + "\nAudio="
                    + dirAudio + "\nStorage=" + storageRoot);
        }

    }

    File vuzeDownloadDir = new File(new File(storageRoot, "Vuze"), "Downloads");
    File internalRoot = this.getApplicationContext().getFilesDir();
    vuzeCoreConfigRoot = new File(internalRoot, ".vuze");

    if (!vuzeCoreConfigRoot.exists() || !vuzeDownloadDir.exists()) {
        File vuzeCustomDir = new File(vuzeCoreConfigRoot, "custom");
        vuzeCustomDir.mkdirs();
        try {
            File configFile = new File(vuzeCustomDir, "VuzeRemote.config");
            FileWriter fileWriter = new FileWriter(configFile, false);
            fileWriter.write(
                    "Default\\ save\\ path=string:" + vuzeDownloadDir.getAbsolutePath().replace("\\", "\\\\"));
            fileWriter.close();
        } catch (IOException e) {
        }
        vuzeDownloadDir.mkdirs();
    }

    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "onCreate: config root=" + vuzeCoreConfigRoot + ";manager=" + vuzeManager);
    }

    if (vuzeManager == null) {

        // TODO: If non-cellular only:
        // - Check ConnectivityManager.getActiveNetworkInfo().getType
        // - if TYPE_MOBILE, bind to "lo" or "127.0.0.1" before core start
        // - if non TYPE_MOBILE, check what's in UP state (ex. eth0, wlan0).
        // Should not be rmnet
        // - if not rmnet, bind before core start
        // ALSO
        // on network change, do the above, restarting core (shut down and start
        // again) if bind needs to change
        // If any network (cellular or otherwise)
        // - Ensure binding is blank, restart core if needed

        NetworkState networkState = VuzeRemoteApp.getNetworkState();
        networkState.addListener(this); // triggers

        buildCustomFile();
        vuzeManager = new VuzeManager(vuzeCoreConfigRoot);
        staticCore = vuzeManager.getCore();

        if (!AndroidUtils.DEBUG) {
            System.setOut(new PrintStream(new OutputStream() {
                public void write(int b) {
                    //DO NOTHING
                }
            }));
        }

        SimpleTimer.addPeriodicEvent("Update Notification", 30000, new TimerEventPerformer() {
            @Override
            public void perform(TimerEvent event) {
                updateNotification();
            }
        });

        PairingManager pairingManager = PairingManagerFactory.getSingleton();
        if (pairingManager != null) {
            try {
                Field ui = pairingManager.getClass().getDeclaredField("ui");
                ui.setAccessible(true);
                ui.set(pairingManager, this);
            } catch (Throwable t) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.e(TAG, "onCreate: ", t);
                }
            }
        }
        if (CorePrefs.getPrefOnlyPluggedIn()) {
            boolean wasConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());
            boolean isConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());

            if (wasConnected != isConnected) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "state changed while starting up.. stop core and try again");
                }

                restartService();
                return;
            }
        }
        staticCore.addLifecycleListener(new AzureusCoreLifecycleAdapter() {

            @Override
            public void started(AzureusCore core) {
                // not called if listener is added after core is started!
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "started: core");
                }

                coreStarted = true;
                sendStuff(MSG_OUT_CORE_STARTED, null);

                updateNotification();

                core.getGlobalManager().addListener(new GlobalManagerListener() {

                    @Override
                    public void downloadManagerAdded(DownloadManager dm) {

                    }

                    @Override
                    public void downloadManagerRemoved(DownloadManager dm) {

                    }

                    @Override
                    public void destroyInitiated() {

                    }

                    @Override
                    public void destroyed() {

                    }

                    @Override
                    public void seedingStatusChanged(boolean seeding_only_mode,
                            boolean potentially_seeding_only_mode) {
                        VuzeService.this.seeding_only_mode = seeding_only_mode;
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "seedingStatusChanged: " + seeding_only_mode);
                        }

                        if (seeding_only_mode) {
                            CorePrefs.releasePowerLock();
                        } else {
                            CorePrefs.adjustPowerLock();
                        }
                    }
                });
            }

            @Override
            public void componentCreated(AzureusCore core, AzureusCoreComponent component) {
                // GlobalManager is always called, even if already created
                if (component instanceof GlobalManager) {

                    String s = NetworkAdmin.getSingleton().getNetworkInterfacesAsString();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "started: " + s);
                    }

                }
                if (component instanceof PluginInterface) {
                    String pluginID = ((PluginInterface) component).getPluginID();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "plugin " + pluginID + " started");
                    }

                    if (pluginID.equals("xmwebui")) {
                        webUIStarted = true;
                        sendStuff(MSG_OUT_WEBUI_STARTED, null);
                        updateNotification();
                    }
                } else {
                    Log.d(TAG, "component " + component.getClass().getSimpleName() + " started");
                }
            }

            @Override
            public void stopped(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core");
                }

                core.removeLifecycleListener(this);

                sendStuff(MSG_OUT_CORE_STOPPED, null);

                // This will never get called if there's a non-deamon thread
                // (measurement-1 from GA, also Binder_2, Binder_1).  Instead,
                // System.exit(0) is called, which kills the service.
                // The service is restarted (STICKY) by android & everything starts
                // up nicely.

                // in case we do get here, keep exit path consistent
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!");
                }

                NetworkState networkState = VuzeRemoteApp.getNetworkState();
                networkState.removeListener(VuzeService.this);

                // Delay exitVM otherwise Vuze core will error with:
                //Listener dispatch timeout: failed = com.vuze.android.remote
                // .service.VuzeService
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "stopped: delayed exit vm");
                        }

                        SESecurityManager.exitVM(0);
                    }
                });
                thread.setDaemon(false);
                thread.start();
                //System.exit(0);
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!!");
                }

            }

            @Override
            public void stopping(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopping: core");
                }

                isCoreStopping = true;

                VuzeEasyTracker.getInstance().stop();
                sendStuff(MSG_OUT_CORE_STOPPING, null);
                CorePrefs.releasePowerLock();

                updateNotification();
            }
        });
    } else {
        if (CorePrefs.DEBUG_CORE) {
            Log.d(TAG, "onCreate: vuzeManager already created");
        }
    }
}

From source file:eu.cassandra.platform.gui.GUI.java

/**
 * Redirects output streams to the GUI./*from  w  ww . j a  v a  2 s  .c  o m*/
 */
@SuppressWarnings("unused")
private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };
    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
}

From source file:edu.stanford.muse.launcher.Main.java

public static void main(String args[]) throws Exception {

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();//from w w  w  .  jav a2s.com
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            out.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/muse/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:edu.stanford.epadd.launcher.Main.java

public static void main(String args[]) throws Exception {
    setupLogging();// ww  w.  ja v a2s .  c o  m
    basicSetup(args);
    setupResources();

    out.println("Starting up ePADD on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g",
                2000);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! ePADD is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running ePADD still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL;
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill ePADD if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for ePADD shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            System.err.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(System.err);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                link = "http://localhost:" + PORT + "/epadd/index.jsp";

                if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/epadd/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!noShutdown) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("ePADD will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:org.codice.ddf.catalog.pubsub.command.ListCommandTest.java

/**
 * Test subscriptions:list command with the LDAP filter arg specified, e.g., subscriptions:list -f
 * "(subscription-id=my*)" Should return matching subscriptions.
 *
 * @throws Exception//w w w .j ava  2s.  c om
 */
@Test
public void testListWithLdapFilterArg() throws Exception {
    // Setup argument captor for LDAP filter that will be passed in to getServiceReferences()
    // call
    ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);

    ListCommand listCommand = new ListCommand();

    BundleContext bundleContext = mock(BundleContext.class);
    listCommand.setBundleContext(bundleContext);

    ServiceReference mySubscription = mock(ServiceReference.class);
    when(mySubscription.getPropertyKeys()).thenReturn(new String[] { SUBSCRIPTION_ID_PROPERTY_KEY });
    when(mySubscription.getProperty(SUBSCRIPTION_ID_PROPERTY_KEY)).thenReturn(MY_SUBSCRIPTION_ID);
    when(bundleContext.getServiceReferences(eq(SubscriptionsCommand.SERVICE_PID), anyString()))
            .thenReturn(new ServiceReference[] { mySubscription });

    String ldapFilter = "(" + SUBSCRIPTION_ID_PROPERTY_KEY + "=my*)";

    PrintStream realSystemOut = System.out;

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    System.setOut(new PrintStream(buffer));

    // when
    listCommand.id = ldapFilter;
    listCommand.ldapFilter = true;
    listCommand.execute();

    /* cleanup */
    System.setOut(realSystemOut);

    // then
    List<String> linesWithText = getConsoleOutputText(buffer);
    assertThat(linesWithText.size(), is(3));
    assertThat(linesWithText,
            hasItems(containsString("Total subscriptions found: 1"), containsString(MY_SUBSCRIPTION_ID)));

    buffer.close();

    // Verify the LDAP filter passed in when mock BundleContext.getServiceReferences() was
    // called.
    verify(bundleContext).getServiceReferences(anyString(), argument.capture());
    assertThat(argument.getValue(), containsString(ldapFilter));
}

From source file:functionaltests.TagCommandsFunctTest.java

@Test
public void testListJobResultUnknownJob() throws Exception {
    typeLine("jobresult(" + NOT_EXISTENT_JOBID + ", 'unknownTag')");

    runCli();//w w  w. j  a va 2s.  c  o m

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testListJobResultUnknownJob:");
    System.out.println(out);
    assertTrue(out.contains("error"));
}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

@Override
public void runBare() throws Throwable
{
    String qname = getClass().getName() + "." + getName();

    // Initialize this for each test run
    _env = new HashMap<String, String>();

    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    PrintStream out = null;//from  w  w w .  j a  va 2  s .c  o  m
    PrintStream err = null;

    boolean redirected = _output != null && _output.length() > 0;
    if (redirected)
    {
        _outputFile = new File(String.format("%s/TEST-%s.out", _output, qname));
        out = new PrintStream(new FileOutputStream(_outputFile), true);
        err = new PrintStream(String.format("%s/TEST-%s.err", _output, qname));

        System.setOut(out);
        System.setErr(err);

        if (_interleaveBrokerLog)
        {
            _testcaseOutputStream = out;
        }
        else
        {
            _testcaseOutputStream = new PrintStream(new FileOutputStream(String
                    .format("%s/TEST-%s.broker.out", _output, qname)), true);
        }
    }

    try
    {
        super.runBare();
    }
    catch (Exception e)
    {
        _logger.error("exception", e);
        throw e;
    }
    finally
    {
        stopAllBrokers();

        // reset properties used in the test
        revertSystemProperties();
        revertLoggingLevels();

        if(_brokerCleanBetweenTests)
        {
            final String qpidWork = System.getProperty("QPID_WORK");
            cleanBrokerWork(qpidWork);
            createBrokerWork(qpidWork);
        }

        _logger.info("==========  stop " + getTestName() + " ==========");

        if (redirected)
        {
            System.setErr(oldErr);
            System.setOut(oldOut);
            err.close();
            out.close();
            if (!_interleaveBrokerLog)
            {
                _testcaseOutputStream.close();
            }
        }
    }
}

From source file:org.apache.flink.yarn.YARNSessionCapacitySchedulerITCase.java

/**
 * Test TaskManager failure and also if the vcores are set correctly (see issue FLINK-2213).
 */// w ww . ja v a  2 s .  c o m
@Test(timeout = 100000) // timeout after 100 seconds
public void testTaskManagerFailure() {
    LOG.info("Starting testTaskManagerFailure()");
    Runner runner = startWithArgs(
            new String[] { "-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n",
                    "1", "-jm", "768", "-tm", "1024", "-s", "3", // set the slots 3 to check if the vCores are set properly!
                    "-nm", "customName", "-Dfancy-configuration-value=veryFancy",
                    "-Dyarn.maximum-failed-containers=3", "-D" + ConfigConstants.YARN_VCORES + "=2" },
            "Number of connected TaskManagers changed to 1. Slots available: 3", RunTypes.YARN_SESSION);

    Assert.assertEquals(2, getRunningContainers());

    // ------------------------ Test if JobManager web interface is accessible -------

    YarnClient yc = null;
    try {
        yc = YarnClient.createYarnClient();
        yc.init(yarnConfiguration);
        yc.start();

        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        Assert.assertEquals(1, apps.size()); // Only one running
        ApplicationReport app = apps.get(0);
        Assert.assertEquals("customName", app.getName());
        String url = app.getTrackingUrl();
        if (!url.endsWith("/")) {
            url += "/";
        }
        if (!url.startsWith("http://")) {
            url = "http://" + url;
        }
        LOG.info("Got application URL from YARN {}", url);

        String response = TestBaseUtils.getFromHTTP(url + "taskmanagers/");

        JsonNode parsedTMs = new ObjectMapper().readTree(response);
        ArrayNode taskManagers = (ArrayNode) parsedTMs.get("taskmanagers");
        Assert.assertNotNull(taskManagers);
        Assert.assertEquals(1, taskManagers.size());
        Assert.assertEquals(3, taskManagers.get(0).get("slotsNumber").asInt());

        // get the configuration from webinterface & check if the dynamic properties from YARN show up there.
        String jsonConfig = TestBaseUtils.getFromHTTP(url + "jobmanager/config");
        Map<String, String> parsedConfig = WebMonitorUtils.fromKeyValueJsonArray(jsonConfig);

        Assert.assertEquals("veryFancy", parsedConfig.get("fancy-configuration-value"));
        Assert.assertEquals("3", parsedConfig.get("yarn.maximum-failed-containers"));
        Assert.assertEquals("2", parsedConfig.get(ConfigConstants.YARN_VCORES));

        // -------------- FLINK-1902: check if jobmanager hostname/port are shown in web interface
        // first, get the hostname/port
        String oC = outContent.toString();
        Pattern p = Pattern.compile("Flink JobManager is now running on ([a-zA-Z0-9.-]+):([0-9]+)");
        Matcher matches = p.matcher(oC);
        String hostname = null;
        String port = null;
        while (matches.find()) {
            hostname = matches.group(1).toLowerCase();
            port = matches.group(2);
        }
        LOG.info("Extracted hostname:port: {} {}", hostname, port);

        Assert.assertEquals("unable to find hostname in " + jsonConfig, hostname,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY));
        Assert.assertEquals("unable to find port in " + jsonConfig, port,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY));

        // test logfile access
        String logs = TestBaseUtils.getFromHTTP(url + "jobmanager/log");
        Assert.assertTrue(logs.contains("Starting YARN ApplicationMaster"));
        Assert.assertTrue(logs.contains("Starting JobManager"));
        Assert.assertTrue(logs.contains("Starting JobManager Web Frontend"));
    } catch (Throwable e) {
        LOG.warn("Error while running test", e);
        Assert.fail(e.getMessage());
    }

    // ------------------------ Kill container with TaskManager and check if vcores are set correctly -------

    // find container id of taskManager:
    ContainerId taskManagerContainer = null;
    NodeManager nodeManager = null;
    UserGroupInformation remoteUgi = null;
    NMTokenIdentifier nmIdent = null;
    try {
        remoteUgi = UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        LOG.warn("Unable to get curr user", e);
        Assert.fail();
    }
    for (int nmId = 0; nmId < NUM_NODEMANAGERS; nmId++) {
        NodeManager nm = yarnCluster.getNodeManager(nmId);
        ConcurrentMap<ContainerId, Container> containers = nm.getNMContext().getContainers();
        for (Map.Entry<ContainerId, Container> entry : containers.entrySet()) {
            String command = Joiner.on(" ").join(entry.getValue().getLaunchContext().getCommands());
            if (command.contains(YarnTaskManager.class.getSimpleName())) {
                taskManagerContainer = entry.getKey();
                nodeManager = nm;
                nmIdent = new NMTokenIdentifier(taskManagerContainer.getApplicationAttemptId(), null, "", 0);
                // allow myself to do stuff with the container
                // remoteUgi.addCredentials(entry.getValue().getCredentials());
                remoteUgi.addTokenIdentifier(nmIdent);
            }
        }
        sleep(500);
    }

    Assert.assertNotNull("Unable to find container with TaskManager", taskManagerContainer);
    Assert.assertNotNull("Illegal state", nodeManager);

    yc.stop();

    List<ContainerId> toStop = new LinkedList<ContainerId>();
    toStop.add(taskManagerContainer);
    StopContainersRequest scr = StopContainersRequest.newInstance(toStop);

    try {
        nodeManager.getNMContext().getContainerManager().stopContainers(scr);
    } catch (Throwable e) {
        LOG.warn("Error stopping container", e);
        Assert.fail("Error stopping container: " + e.getMessage());
    }

    // stateful termination check:
    // wait until we saw a container being killed and AFTERWARDS a new one launched
    boolean ok = false;
    do {
        LOG.debug("Waiting for correct order of events. Output: {}", errContent.toString());

        String o = errContent.toString();
        int killedOff = o.indexOf("Container killed by the ApplicationMaster");
        if (killedOff != -1) {
            o = o.substring(killedOff);
            ok = o.indexOf("Launching TaskManager") > 0;
        }
        sleep(1000);
    } while (!ok);

    // send "stop" command to command line interface
    runner.sendStop();
    // wait for the thread to stop
    try {
        runner.join(1000);
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while stopping runner", e);
    }
    LOG.warn("stopped");

    // ----------- Send output to logger
    System.setOut(originalStdout);
    System.setErr(originalStderr);
    String oC = outContent.toString();
    String eC = errContent.toString();
    LOG.info("Sending stdout content through logger: \n\n{}\n\n", oC);
    LOG.info("Sending stderr content through logger: \n\n{}\n\n", eC);

    // ------ Check if everything happened correctly
    Assert.assertTrue("Expect to see failed container", eC.contains("New messages from the YARN cluster"));

    Assert.assertTrue("Expect to see failed container",
            eC.contains("Container killed by the ApplicationMaster"));

    Assert.assertTrue("Expect to see new container started",
            eC.contains("Launching TaskManager") && eC.contains("on host"));

    // cleanup auth for the subsequent tests.
    remoteUgi.getTokenIdentifiers().remove(nmIdent);

    LOG.info("Finished testTaskManagerFailure()");
}

From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java

protected void executAntBuild(ServletConfig servletConfig, File buildFile, String target)
        throws ServletException {
    log.debug("Executing Ant build " + buildFile + " target " + target);

    org.apache.tools.ant.Project antProject = AntProject.getConfiguredProject(buildFile);
    antProject.setProperty("app.home", servletConfig.getServletContext().getRealPath("/"));
    antProject.setProperty("app.init-count", Long.toString(getInitializationCount()));

    Properties servletOptionsProps = servletOptions.setProperties(new Properties(), "app.servlet-options",
            false);//from   w  w w . ja  v  a  2  s  . c o  m
    for (Iterator i = servletOptionsProps.keySet().iterator(); i.hasNext();) {
        String propName = (String) i.next();
        antProject.setProperty(propName, servletOptionsProps.getProperty(propName));
    }

    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
    PrintStream pstream = new PrintStream(ostream);

    BuildLogger logger = new NoBannerLogger();
    logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO);
    logger.setOutputPrintStream(pstream);
    logger.setErrorPrintStream(pstream);

    PrintStream saveOut = System.out;
    PrintStream saveErr = System.err;
    System.setOut(pstream);
    System.setErr(pstream);

    antProject.addBuildListener(logger);
    Exception exceptionThrown = null;
    try {
        Vector targets = new Vector();
        if (target != null) {
            String[] targetNames = TextUtils.getInstance().split(target, ",", true);
            for (int i = 0; i < targetNames.length; i++)
                targets.add(targetNames[i]);
        } else
            targets.add(antProject.getDefaultTarget());
        antProject.executeTargets(targets);
    } catch (Exception e) {
        exceptionThrown = e;
    }

    if (exceptionThrown != null) {
        log.error(ostream.toString());
        log.error("Error running ant build file " + buildFile + " target " + target, exceptionThrown);
    } else
        log.debug(ostream.toString());

    int extnPos = buildFile.getName().lastIndexOf('.');
    String nameNoExtn = extnPos != -1 ? buildFile.getName().substring(0, extnPos) : buildFile.getName();
    File logFile = servletOptions.getInitUsingAntLogFile() != null
            ? new File(servletOptions.getInitUsingAntLogFile())
            : new File(buildFile.getParentFile(), nameNoExtn + ".log");

    FileOutputStream fos = null;
    PrintWriter logWriter = null;
    try {
        fos = new FileOutputStream(logFile.getAbsolutePath(), logFile.exists());
        logWriter = new PrintWriter(fos);
        logWriter.println("-----------------------------------------------------------------------------");
        logWriter.println("Started build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
        logWriter.write(ostream.toString());
        if (exceptionThrown != null)
            logWriter.write(TextUtils.getInstance().getStackTrace(exceptionThrown));
        logWriter.println("Ended build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
    } catch (IOException e) {
        throw new ServletException(e);
    } finally {
        logWriter.close();
        try {
            fos.close();
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    System.setOut(saveOut);
    System.setErr(saveErr);
}