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:com.datatorrent.stram.cli.ApexCli.java

protected void restoreOutput(PrintStream originalStream) {
    if (raw) {
        System.setOut(originalStream);
    }
}

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

public static void main(String args[]) throws Exception {
    Splash splash = null;//  w  w  w  .j av a2s.  c  om

    boolean headless = (System.getProperty("muse.mode.server") != null);
    if (!headless)
        splash = new Splash();
    else {
        System.out.println("Muse running in headless mode!");
        browserOpen = false;
    }

    tellUser(splash, "Setting up logging...");
    setupLogging();
    basicSetup(args);
    BASE_URL = "http://localhost:" + PORT + "/" + WEBAPP_NAME;
    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.

    tellUser(splash, "Log file: " + debugFile + "***\n");

    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);
    tellUser(splash, "Memory: " + getMemoryStats());

    // 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 already running at: " + BASE_URL + ", will shut it down!");
        tellUser(splash, "ePADD already running at: " + BASE_URL + ", will shut it down!");
        killRunningServer(BASE_URL);

        boolean killed = false;
        int N_KILL_TRIES = 20, N_KILL_PERIOD_MILLIS = 3000;
        // check every 3 secs 20 times (total 1 minute) for the previous epadd to die
        // if it doesn't die after a minute, fail
        for (int i = 0; i < N_KILL_TRIES; i++) {
            try {
                Thread.sleep(N_KILL_PERIOD_MILLIS);
            } catch (InterruptedException ie) {
            }
            out.println("Checking " + MUSE_CHECK_URL);
            tellUser(splash, "Checking " + MUSE_CHECK_URL);
            try {
                urlAlive = isURLAlive(MUSE_CHECK_URL);
            } catch (Exception e) {
                out.println("Exception: " + e);
                e.printStackTrace(out);
            }
            if (!urlAlive)
                break;
        }

        if (!urlAlive) {
            out.println("Good. Shutdown succeeded, will restart");
            tellUser(splash, "Good. Shutdown succeeded, we'll restart ePADD.");
        } else {
            String message = "Previously running ePADD still alive despite attempt to shut it down, 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);
            tellUser(splash, "Sorry, unable to kill previous ePADD. Quitting!");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ie) {
            }
            if (splash != null)
                splash.close();
            return;
        }
    }

    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        setupResources();
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        tellUser(splash, "Starting ePADD at " + BASE_URL);

        server.start();

        PrintStream debugOut1 = 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) {
            out.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
        }

        final PrintStream debugOut = debugOut1;

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    shutdownSessions();
                    server.stop();
                    server.destroy();
                    debugOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }));

        boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);

        if (success) {
            try {
                int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 
                tellUser(splash, "Setting up shutdown port...");

                new ShutdownThread(server, shutdownPort).start(); // this will start a non-daemon thread that keeps the process alive
                out.println("Listening for ePADD shutdown message on port " + shutdownPort);
                tellUser(splash, "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) {
                out.println("Unable to setup system tray icon: " + e);
                e.printStackTrace(err);
            }

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

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

                    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

                    launchBrowser(link, splash);

                } 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);
                }
            }

        } else {
            out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
            tellUser(splash, "SORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING");
        }

        savedSystemOut = out;
        savedSystemErr = err;
        System.setOut(debugOut);
        System.setErr(debugOut);
        if (splash != null)
            splash.close();
    }
    // program should not halt here, as ShutdownThread is running as a non-daemon thread.
    // splashDemo.closeWindow();
}

From source file:edu.isi.wings.catalog.component.api.impl.kb.ComponentReasoningKB.java

/**
 * Helper function which does the actual data requirement checking
 * //ww  w .j  a  v  a2  s .  c o  m
 * @param details
 * @param specialize
 * @param useRules
 * @return
 */
public ArrayList<ComponentPacket> findDataDetails(ComponentPacket details, boolean specialize,
        boolean useRules) {
    ArrayList<ComponentPacket> list = new ArrayList<ComponentPacket>();

    HashMap<String, KBObject> omap = this.objPropMap;
    HashMap<String, KBObject> dmap = this.dataPropMap;

    // Extract info from details object
    ComponentVariable c = details.getComponent();
    HashMap<String, Variable> roleMaps = details.getStringRoleMaps();
    HashMap<String, Role> varMaps = details.getStringVariableMap();
    ArrayList<KBTriple> redbox = details.getRequirements();

    // Get All component bindings
    String incompid = c.getID();
    Binding cb = c.getBinding();
    ArrayList<String> cbindings = new ArrayList<String>();
    if (!cb.isSet())
        cbindings.add(cb.getID());
    else {
        for (WingsSet s : cb) {
            cbindings.add(((Binding) s).getID());
        }
    }

    // Get List of all concrete components
    ArrayList<Component> ccomps = new ArrayList<Component>();
    for (String cbid : cbindings) {
        Component comp = this.getCachedComponent(cbid);
        if (comp == null) {
            logger.debug(cbid + " is not a valid component");
            details.addExplanations(cbid + " is not a valid component");
            details.setInvalidFlag(true);
            list.add(details);
            return list;
        }
        boolean isConcrete = (comp.getType() == Component.CONCRETE);
        if (!specialize) {
            // If no specialization required, add component as is
            ccomps.add(comp);
        } else if (isConcrete) {
            // If specialization required, but component is already concrete,
            // add as is
            ccomps.add(comp);
        } else {
            /* If the component is abstract, then get all it's concrete
             * components. Example of how components are structured in ontology:
             * absClass 
             * - [abs (isConcrete: false)] 
             * - conc1Class 
             *    - [conc1 (isConcrete: true)] 
             * - conc2Class 
             *    - [conc2 (isConcrete: true)] 
             * Note: Only 1 Component Instance per Class
             */
            ArrayList<String> concreteids = this.getConcreteComponentsForAbstract(comp.getID());
            for (String concreteid : concreteids) {
                Component instcomp = this.getCachedComponent(concreteid);
                if (instcomp != null && instcomp.getType() == Component.CONCRETE) {
                    ccomps.add(instcomp);
                }
            }
        }
    }

    logger.debug("Available components to check validity: " + ccomps);

    // For All concrete components :
    // - Get mapping of specialized arguments to variables
    // - Transfer "relevant" output variable properties to input variables
    // - Pass back the specialized component + specialized mappings +
    // modified red-box
    // - Handle *NEW* Arguments as well -> Create *NEW* DataVariables

    // Get Metrics property hierarchy triples for adding into the temporary
    // kb

    for (Component ccomp : ccomps) {
        HashMap<Role, Variable> sRoleMap = new HashMap<Role, Variable>();
        ArrayList<String> varids = new ArrayList<String>();

        // Create a new temporary kb
        KBAPI tkb = this.ontologyFactory.getKB(OntSpec.PLAIN);

        // Add the redbox (i.e. datavariable constraints) to the temporary
        // kb, along with domain knowledge about the data catalog
        tkb.addTriples(redbox);
        tkb.addTriples(domainKnowledge);

        KBObject ccompobj = this.kb.getIndividual(ccomp.getID());
        // Create a copy of the specialized component in the temporary kb
        KBObject tcomp = this.copyObjectIntoKB(incompid, ccompobj, tkb, this.pcdomns, null, false);

        boolean typesOk = true;

        // For all argument roles of the specialized component :
        ArrayList<ComponentRole> allArgs = new ArrayList<ComponentRole>(ccomp.getInputs());
        allArgs.addAll(ccomp.getOutputs());

        HashSet<String> explanations = new HashSet<String>();
        ComponentPacket cmr;
        ComponentVariable concreteComponent = new ComponentVariable(incompid);
        concreteComponent.setBinding(new Binding(ccomp.getID()));
        if (specialize)
            concreteComponent.setConcrete(true);
        else
            concreteComponent.setConcrete(c.isConcrete());

        ArrayList<String> inputRoles = new ArrayList<String>();

        for (ComponentRole arg : allArgs) {
            // Get the argument ID for the specialized argument
            String argid = arg.getRoleName();

            Variable var = roleMaps.get(argid);
            String varid = null;
            String roleid = null;
            if (var == null) {
                // Create a new Variable for role if none exists currently
                // varid = arg.getID()+"_"+ccomp.getName()+"_Variable";
                varid = ccomp.getNamespace() + argid;
                roleid = ccomp.getID() + "_" + argid + "_role";

                short type = 0;
                if (arg.isParam())
                    type = VariableType.PARAM;
                else
                    type = VariableType.DATA;
                var = new Variable(varid, type);
            } else {
                varid = var.getID();
                roleid = varMaps.get(var.getID()).getID();
                // Make sure that the variable has a type that is either
                // subsumed by the argument type, or that the argument type
                // is subsumed by the variable type
                if (!checkTypeCompatibility(tkb, varid, arg.getID())) {
                    logger.debug(arg.getID() + " is not type compatible with variable: " + varid);
                    explanations.add("INFO " + ccomp + " is not selectable because " + arg.getID()
                            + " is not type compatible with variable: " + varid);
                    typesOk = false;
                    break;
                }
            }

            // Copy over the argument's classes to the variable
            KBObject argobj = this.kb.getIndividual(arg.getID());
            KBObject varobj = this.copyObjectClassesIntoKB(varid, argobj, tkb, this.dcdomns, null, false);

            // create hasArgumentID property for the variable
            tkb.addTriple(varobj, dmap.get("hasArgumentID"), tkb.createLiteral(argid));

            Role r = new Role(roleid);
            r.setRoleId(argid);
            r.setDimensionality(arg.getDimensionality());

            // Set variable data binding
            if (var.isDataVariable() && var.getBinding() != null && var.getBinding().getName() != null) {
                tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral(var.getBinding().getName()));
            } else {
                tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral(""));
            }

            // Set variable parameter binding (default if none set)
            if (var.isParameterVariable()) {
                KBObject arg_value = null;
                ValueBinding parambinding = (ValueBinding) var.getBinding();
                if (parambinding != null && parambinding.getValue() != null) {
                    arg_value = tkb.createXSDLiteral(parambinding.getValueAsString(),
                            parambinding.getDatatype());
                } else if (arg.getParamDefaultalue() != null) {
                    arg_value = tkb.createLiteral(arg.getParamDefaultalue());
                }
                if (arg_value != null) {
                    tkb.setPropertyValue(varobj, dmap.get("hasValue"), arg_value);
                }
            }

            // assign this variable as an input or output to the component
            if (ccomp.getInputs().contains(arg)) {
                inputRoles.add(r.getRoleId());
                tkb.addTriple(tcomp, omap.get("hasInput"), varobj);
            } else {
                tkb.addTriple(tcomp, omap.get("hasOutput"), varobj);
            }
            sRoleMap.put(r, var);
            varids.add(var.getID());
        }

        // Empty triple list returned if errors encountered below
        ArrayList<KBTriple> empty = new ArrayList<KBTriple>();

        // Return if there was some problem with types
        if (!typesOk) {
            logger.debug(ccomp + " is not selectable ");
            explanations.add("INFO " + ccomp + " is not selectable ");
            cmr = new ComponentPacket(concreteComponent, sRoleMap, empty);
            cmr.setInputRoles(inputRoles);
            cmr.addExplanations(explanations);
            cmr.setInvalidFlag(true);
            list.add(cmr);
            continue;
        }

        // ** Run Rules **
        if (useRules && ccomp.hasRules()) {
            // Redirect output to a byte stream
            ByteArrayOutputStream bost = new ByteArrayOutputStream();
            PrintStream oldout = System.out;
            System.setOut(new PrintStream(bost, true));

            // Run propagation rules on the temporary kb
            tkb.setRulePrefixes(this.rulePrefixes);
            tkb.applyRules(this.getCachedComponentRules(ccomp));
            //tkb.applyRulesFromString(allrules);

            // Get printouts from Rules and store as Explanations
            if (!bost.toString().equals("")) {
                for (String exp : bost.toString().split("\\n")) {
                    explanations.add(exp);
                }
            }
            // Set output back to original System.out
            System.setOut(oldout);
        }

        // Checking for invalidity
        KBObject invalidProp = tkb.getProperty(this.pcns + "isInvalid");
        KBObject isInvalid = tkb.getPropertyValue(tcomp, invalidProp);
        if (isInvalid != null && (Boolean) isInvalid.getValue()) {
            logger.debug(ccomp + " is not selectable ");
            explanations.add("INFO " + ccomp + " is not selectable ");
            cmr = new ComponentPacket(concreteComponent, sRoleMap, empty);
            cmr.setInputRoles(inputRoles);
            cmr.addExplanations(explanations);
            cmr.setInvalidFlag(true);
            list.add(cmr);
            continue;
        }

        // Set parameter values (if any)
        for (Variable var : roleMaps.values()) {
            if (var.isParameterVariable() && var.getBinding() == null) {
                KBObject varobj = tkb.getResource(var.getID());
                KBObject val = tkb.getPropertyValue(varobj, dmap.get("hasValue"));
                if (val != null && val.getValue() != null) {
                    tkb.addTriple(varobj, tkb.getResource(this.wflowns + "hasParameterValue"), val);
                    var.setBinding(new ValueBinding(val.getValue(), val.getDataType()));
                }
            }
        }

        // Create a constraint engine and get Relevant Constraints here
        ConstraintEngine cons = new ConstraintEngineKB(tkb, "");
        cons.addWhitelistedNamespace(this.dcdomns);
        cons.addWhitelistedNamespace(this.dcns);
        cons.addWhitelistedNamespace(this.wflowns);
        ArrayList<String> blacklistedIds = new ArrayList<String>();
        blacklistedIds.add(dmap.get("hasArgumentID").getID());
        blacklistedIds.add(dmap.get("hasBindingID").getID());
        blacklistedIds.add(this.dcns + "hasMetrics");
        blacklistedIds.add(this.dcns + "hasDataMetrics");
        blacklistedIds.add(this.pcns + "hasValue");

        for (String id : blacklistedIds)
            cons.addBlacklistedId(id);
        ArrayList<KBTriple> constraints = cons.getConstraints(varids);
        for (String id : blacklistedIds)
            cons.removeBlacklistedId(id);

        cmr = new ComponentPacket(concreteComponent, sRoleMap, constraints);
        cmr.setInputRoles(inputRoles);
        cmr.addExplanations(explanations);
        list.add(cmr);
    }
    return list;
}

From source file:edu.umd.cs.buildServer.BuildServerDaemon.java

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

    CommandLineParser parser = new PosixParser();
    Options options = getOptions();//w ww  .  jav  a2 s .co m
    CommandLine line;
    try {
        line = parser.parse(options, args);

    } catch (Exception e) {
        printHelp(options);
        return;
    }
    if (line.hasOption("help")) {
        printHelp(options);
        return;
    }

    String[] remainingArgs = line.getArgs();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("easyhttps", easyhttps);

    BuildServerDaemon buildServer = new BuildServerDaemon();
    if (line.hasOption("config")) {
        String c = line.getOptionValue("config");
        buildServer.setConfigFile(c);
    } else if (remainingArgs.length == 1)
        buildServer.setConfigFile(remainingArgs[0]);

    boolean once = line.hasOption("once");

    if (line.hasOption("submission")) {
        once = true;
        buildServer.getConfig().setProperty(DEBUG_SPECIFIC_SUBMISSION, line.getOptionValue("submission"));
        if (line.hasOption("testSetup"))
            buildServer.getConfig().setProperty(DEBUG_SPECIFIC_TESTSETUP, line.getOptionValue("testSetup"));
        if (line.hasOption("skipDownload"))
            buildServer.getConfig().setProperty(DEBUG_SKIP_DOWNLOAD, "true");

    } else if (line.hasOption("testSetup")) {
        throw new IllegalArgumentException(
                "You can only specify a specific test setup if you also specify a specific submission");
    }

    if (line.hasOption("projectNum")) {
        buildServer.getConfig().setProperty(DEBUG_SPECIFIC_PROJECT, line.getOptionValue("projectNum"));
    }

    if (line.hasOption("quiet"))
        buildServer.setQuiet(true);
    if (line.hasOption("verify"))
        buildServer.setVerifyOnly();

    if (line.hasOption("course")) {
        buildServer.getConfig().setProperty(DEBUG_SPECIFIC_COURSE, line.getOptionValue("course"));
    }

    if (line.hasOption("logLevel"))
        buildServer.getConfig().setProperty(LOG4J_THRESHOLD, line.getOptionValue("logLevel"));

    if (line.hasOption("downloadOnly")) {
        System.out.println("Setting download only");
        buildServer.setDownloadOnly(true);
        once = true;
    }
    if (once) {
        buildServer.getConfig().setProperty(LOG_DIRECTORY, "console");
        buildServer.setDoNotLoop(true);
        buildServer.getConfig().setProperty(DEBUG_PRESERVE_SUBMISSION_ZIPFILES, "true");
    }

    buildServer.initConfig();
    Logger log = buildServer.getLog();

    /** Redirect standard out and err to dev null, since clover
     * writes to standard out and error */

    PrintStream systemOut = System.out;
    PrintStream systemErr = System.err;
    if (buildServer.isQuiet()) {
        System.setOut(new PrintStream(new DevNullOutputStream()));
        System.setErr(new PrintStream(new DevNullOutputStream()));
    }

    try {
        buildServer.executeServerLoop();
        if (log != null)
            log.info("Shutting down");
        System.out.println("Shutting down");
        timedSystemExit0();
    } catch (Throwable e) {
        buildServer.clearMyPidFile();
        if (log != null)
            log.fatal("BuildServerDaemon got fatal exception; waiting for cron to restart me: ", e);
        e.printStackTrace(systemErr);
        System.exit(1);
    }
    if (buildServer.isQuiet()) {
        System.setOut(systemOut);
        System.setErr(systemErr);
    }
}

From source file:ai.grakn.test.graql.shell.GraqlShellIT.java

private String testShell(String input, ByteArrayOutputStream berr, String... args) throws Exception {
    args = specifyUniqueKeyspace(args);/*from   w  w  w .ja  v a 2 s .  c  o m*/

    InputStream in = new ByteArrayInputStream(input.getBytes());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    PrintStream out = new PrintStream(new TeeOutputStream(bout, trueOut));

    // Intercept stderr, but make sure it is still printed using the TeeOutputStream
    PrintStream err = new PrintStream(new TeeOutputStream(berr, trueErr));

    try {
        System.out.flush();
        System.err.flush();
        System.setIn(in);
        System.setOut(out);
        System.setErr(err);

        GraqlShell.runShell(args, expectedVersion, historyFile);
    } catch (Exception e) {
        System.setErr(trueErr);
        e.printStackTrace();
        err.flush();
        fail(berr.toString());
    } finally {
        resetIO();
    }

    out.flush();
    err.flush();

    return bout.toString();
}

From source file:geva.Main.AbstractRun.java

protected void setOutput() {
    String stdOut = "";
    String stdErr = "";
    try {/* w w  w. j av a  2s.  c om*/
        String key = Constants.STDOUT;
        String value = this.properties.getProperty(key);
        if (value != null) {
            if (!value.equals("")) {
                stdOut = System.getProperty("user.dir") + System.getProperty("file.separator") + value + ".out";
            }
        }
        key = Constants.STDERR;
        value = this.properties.getProperty(key);
        if (value != null) {
            if (!value.equals("")) {
                stdErr = System.getProperty("user.dir") + System.getProperty("file.separator") + value + ".err";
            }
        }
        if (!stdOut.equals("")) {
            logger.info("Redirecting stdOut to " + stdOut);
            FileOutputStream fos = new FileOutputStream(stdOut, true);
            PrintStream ps = new PrintStream(fos);
            System.setOut(ps);
        }
        if (!stdErr.equals("")) {
            logger.info("Redirecting stdErr to " + stdErr);
            FileOutputStream fos = new FileOutputStream(stdErr, true);
            PrintStream ps = new PrintStream(fos);
            System.setErr(ps);
        }
    } catch (Exception e) {
        logger.error(" std output exception", e);
    }
}

From source file:com.clematis.jsmodify.JSExecutionTracer.java

/**
 * Dirty way to save program points from the proxy request threads. TODO: Frank, find cleaner
 * way./*  w w w . ja  va  2  s . com*/
 * 
 * @param string
 *            The JSON-text to save.
 */
public static void addPoint(String string) {
    JSONArray buffer = null;
    JSONObject targetAttributes = null;
    JSONObject targetElement = null;
    String JSONLabel = new String();
    int i;

    try {
        /* save the current System.out for later usage */
        PrintStream oldOut = System.out;
        /* redirect it to the file */
        System.setOut(output);

        buffer = new JSONArray(string);
        for (i = 0; i < buffer.length(); i++) {

            if (points.length() > 0) {
                // Add comma after previous trace object
                System.out.println(",");
            }

            points.put(buffer.getJSONObject(i));

            if (buffer.getJSONObject(i).has("args")
                    && ((String) buffer.getJSONObject(i).get("messageType")).contains("FUNCTION_ENTER")) {
                try {
                    JSONArray args = (JSONArray) buffer.getJSONObject(i).get("args");
                    String newValue = args.toString();
                    buffer.getJSONObject(i).remove("args");
                    buffer.getJSONObject(i).put("args", newValue);
                } catch (JSONException jse) {
                    // argument is not a JSON object
                    continue;
                }
            }
            if (buffer.getJSONObject(i).has("returnValue")
                    && !buffer.getJSONObject(i).get("returnValue").getClass().toString().contains("Null")) {
                try {
                    JSONObject rv = (JSONObject) buffer.getJSONObject(i).get("returnValue");
                    String newValue = rv.toString();
                    buffer.getJSONObject(i).remove("returnValue");
                    buffer.getJSONObject(i).put("returnValue", newValue);
                } catch (JSONException jse) {
                    // argument is not a JSON object
                    continue;
                }
            }
            if (buffer.getJSONObject(i).has("targetElement")) {
                JSONArray extractedArray = new JSONArray(
                        buffer.getJSONObject(i).get("targetElement").toString());
                try {
                    targetAttributes = extractedArray.getJSONObject(1);
                    String targetType = extractedArray.get(0).toString();

                    targetElement = new JSONObject("{\"elementType\":\"" + targetType + "\",\"attributes\":"
                            + targetAttributes.toString() + "}");

                } catch (Exception e) {
                    // targetElement is not usual DOM element
                    // E.g. DOMContentLoaded
                    if (buffer.getJSONObject(i).has("eventType")
                            && buffer.getJSONObject(i).get("eventType").toString().contains("ContentLoaded")) {
                        targetElement = new JSONObject("{\"elementType\":\"DOCUMENT\",\"attributes\":\"-\"}");
                    } else {
                        targetElement = new JSONObject("{\"elementType\":\"UNKNOWN\",\"attributes\":\"-\"}");
                    }
                }
                buffer.getJSONObject(i).remove("targetElement");
                buffer.getJSONObject(i).put("targetElement", targetElement.toString());
            }

            // Insert @class key for Jackson mapping
            if (buffer.getJSONObject(i).has("messageType")) {
                String mType = buffer.getJSONObject(i).get("messageType").toString();

                // Maybe better to change mType to ENUM and use switch
                // instead of 'if's
                if (mType.contains("FUNCTION_CALL")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.FunctionCall");
                    JSONLabel = "\"FunctionTrace\":";
                } else if (mType.contains("FUNCTION_ENTER")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.FunctionEnter");
                    JSONLabel = "\"FunctionTrace\":";
                } else if (mType.contains("FUNCTION_EXIT")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.FunctionExit");
                    JSONLabel = "\"FunctionTrace\":";
                } else if (mType.contains("RETURN_STATEMENT")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.FunctionReturnStatement");
                    JSONLabel = "\"FunctionTrace\":";
                } else if (mType.contains("DOM_EVENT")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.DOMEventTrace");
                    JSONLabel = "\"DOMEventTrace\":";
                } else if (mType.contains("DOM_MUTATION")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.DOMMutationTrace");
                    JSONLabel = "\"DOMEventTrace\":";
                } else if (mType.contains("DOM_ELEMENT_VALUE")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.DOMElementValueTrace");
                    JSONLabel = "\"DOMEventTrace\":";
                } else if (mType.contains("TIMEOUT_SET")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.TimeoutSet");
                    JSONLabel = "\"TimingTrace\":";
                } else if (mType.contains("TIMEOUT_CALLBACK")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.TimeoutCallback");
                    JSONLabel = "\"TimingTrace\":";
                } else if (mType.contains("XHR_OPEN")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.XMLHttpRequestOpen");
                    JSONLabel = "\"XHRTrace\":";
                } else if (mType.contains("XHR_SEND")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.XMLHttpRequestSend");
                    JSONLabel = "\"XHRTrace\":";
                } else if (mType.contains("XHR_RESPONSE")) {
                    buffer.getJSONObject(i).put("@class", "com.clematis.core.trace.XMLHttpRequestResponse");
                    JSONLabel = "\"XHRTrace\":";
                }
                // messageType obsolete
                buffer.getJSONObject(i).remove("messageType");
            }

            System.out.print(JSONLabel + "[" + buffer.getJSONObject(i).toString(2) + "]");
        }

        /* Restore the old system.out */
        System.setOut(oldOut);

        if (i > 0) {
            counter = buffer.getJSONObject(buffer.length() - 1).getInt("counter") + 1;
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

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

/**
 * The test has been passed once the "terminateAfterString" has been seen.
 * @param args Command line arguments for the runner
 * @param terminateAfterString the runner is searching the stdout and stderr for this string. as soon as it appears, the test has passed
 * @param failOnPatterns The runner is searching stdout and stderr for the pattern (regexp) specified here. If one appears, the test has failed
 * @param type Set the type of the runner
 * @param expectedReturnValue Expected return code from the runner.
 * @param checkLogForTerminateString  If true, the runner checks also the log4j logger for the terminate string
 *//*from w w w .  j av  a 2 s  . co  m*/
protected void runWithArgs(String[] args, String terminateAfterString, String[] failOnPatterns, RunTypes type,
        int expectedReturnValue, boolean checkLogForTerminateString) {
    LOG.info("Running with args {}", Arrays.toString(args));

    outContent = new ByteArrayOutputStream();
    errContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));

    // we wait for at most three minutes
    final int START_TIMEOUT_SECONDS = 180;
    final long deadline = System.currentTimeMillis() + (START_TIMEOUT_SECONDS * 1000);

    Runner runner = new Runner(args, type, expectedReturnValue);
    runner.start();

    boolean expectedStringSeen = false;
    boolean testPassedFromLog4j = false;
    do {
        sleep(1000);
        String outContentString = outContent.toString();
        String errContentString = errContent.toString();
        if (failOnPatterns != null) {
            for (String failOnString : failOnPatterns) {
                Pattern pattern = Pattern.compile(failOnString);
                if (pattern.matcher(outContentString).find() || pattern.matcher(errContentString).find()) {
                    LOG.warn("Failing test. Output contained illegal string '" + failOnString + "'");
                    sendOutput();
                    // stopping runner.
                    runner.sendStop();
                    Assert.fail("Output contained illegal string '" + failOnString + "'");
                }
            }
        }
        // check output for the expected terminateAfterString.
        if (checkLogForTerminateString) {
            LoggingEvent matchedEvent = UtilsTest.getEventContainingString(terminateAfterString);
            if (matchedEvent != null) {
                testPassedFromLog4j = true;
                LOG.info("Found expected output in logging event {}", matchedEvent);
            }

        }

        if (outContentString.contains(terminateAfterString) || errContentString.contains(terminateAfterString)
                || testPassedFromLog4j) {
            expectedStringSeen = true;
            LOG.info("Found expected output in redirected streams");
            // send "stop" command to command line interface
            LOG.info("RunWithArgs: request runner to stop");
            runner.sendStop();
            // wait for the thread to stop
            try {
                runner.join(30000);
            } catch (InterruptedException e) {
                LOG.warn("Interrupted while stopping runner", e);
            }
            LOG.warn("RunWithArgs runner stopped.");
        } else {
            // check if thread died
            if (!runner.isAlive()) {
                // leave loop: the runner died, so we can not expect new strings to show up.
                break;
            }
        }
    } while (runner.getRunnerError() == null && !expectedStringSeen && System.currentTimeMillis() < deadline);

    sendOutput();

    if (runner.getRunnerError() != null) {
        // this lets the test fail.
        throw new RuntimeException("Runner failed", runner.getRunnerError());
    }
    Assert.assertTrue("During the timeout period of " + START_TIMEOUT_SECONDS + " seconds the "
            + "expected string did not show up", expectedStringSeen);

    LOG.info("Test was successful");
}

From source file:org.apache.sentry.provider.db.generic.tools.TestSentryShellSolr.java

private Set<String> getShellResultWithOSRedirect(SentryShellSolr sentryShell, String[] args,
        boolean expectedExecuteResult) throws Exception {
    PrintStream oldOut = System.out;
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    assertEquals(expectedExecuteResult, sentryShell.executeShell(args));
    Set<String> resultSet = Sets.newHashSet(outContent.toString().split("\n"));
    System.setOut(oldOut);/* ww w  .jav  a2s  .  c om*/
    return resultSet;
}

From source file:org.apache.sentry.cli.tools.TestSentryShellIndexer.java

private Set<String> getShellResultWithOSRedirect(SentryShellIndexer sentryShell, String[] args,
        boolean expectedExecuteResult) throws Exception {
    PrintStream oldOut = System.out;
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    assertEquals(expectedExecuteResult, sentryShell.executeShell(args));
    String outContentStr = outContent.toString();
    Set<String> resultSet = outContentStr.length() > 0 ? Sets.<String>newHashSet(outContentStr.split("\n"))
            : Sets.<String>newHashSet();
    System.setOut(oldOut);//w w w  .j a va 2s .  com
    return resultSet;
}