List of usage examples for java.lang System setOut
public static void setOut(PrintStream out)
From source file:org.codice.ddf.catalog.pubsub.command.ListCommandTest.java
/** * Test subscriptions:list command with one subscription ID argument. Should return the one * matching registered subscriptions.//www . j a v a 2s.c o m * * @throws Exception */ @Test public void testListOneMatchingSubscriptionIdArg() 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); ServiceReference yourSubscription = mock(ServiceReference.class); when(yourSubscription.getPropertyKeys()).thenReturn(new String[] { SUBSCRIPTION_ID_PROPERTY_KEY }); when(yourSubscription.getProperty(SUBSCRIPTION_ID_PROPERTY_KEY)).thenReturn(YOUR_SUBSCRIPTION_ID); when(bundleContext.getServiceReferences(eq(SubscriptionsCommand.SERVICE_PID), anyString())) .thenReturn(new ServiceReference[] { mySubscription }); PrintStream realSystemOut = System.out; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer)); // when listCommand.id = MY_SUBSCRIPTION_ID; 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()); String expectedLdapFilter = "(" + SUBSCRIPTION_ID_PROPERTY_KEY + "=" + MY_SUBSCRIPTION_ID + ")"; assertThat(argument.getValue(), containsString(expectedLdapFilter)); }
From source file:functionaltests.TagCommandsFunctTest.java
@Test public void testJobResult() throws Exception { typeLine("jobresult(" + jobId.longValue() + ")"); runCli();//from ww w . j a v a 2 s . c o m String out = this.capturedOutput.toString(); System.setOut(stdOut); System.out.println("------------- testJobResult:"); System.out.println(out); assertTrue(out.contains("T1#1")); assertTrue(out.contains("Print1#1")); assertTrue(out.contains("Print2#1")); assertTrue(out.contains("T2#1")); assertTrue(out.contains("T1#2")); assertTrue(out.contains("Print1#2")); assertTrue(out.contains("Print2#2")); assertTrue(out.contains("T2#2")); }
From source file:caarray.client.test.gui.GuiMain.java
public GuiMain() throws Exception { JFrame frame = new JFrame("API Test Suite"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout(6, 6)); JPanel topPanel = new JPanel(); /* ###### Text fields for modifiable parameters ##### */ final JTextField javaHostText = new JTextField(TestProperties.getJavaServerHostname(), 20); JLabel javaHostLabel = new JLabel("Java Service Host"); JButton save = new JButton("Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { TestProperties.setJavaServerHostname(javaHostText.getText()); }// w w w . j a va2s. c om }); JLabel javaPortLabel = new JLabel("Java Port"); final JTextField javaPortText = new JTextField(Integer.toString(TestProperties.getJavaServerJndiPort()), 5); JButton save2 = new JButton("Save"); save2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int port = Integer.parseInt(javaPortText.getText()); TestProperties.setJavaServerJndiPort(port); } catch (NumberFormatException e) { System.out.println(javaPortText.getText() + " is not a valid port number."); } } }); JLabel gridHostLabel = new JLabel("Grid Service Host"); final JTextField gridHostText = new JTextField(TestProperties.getGridServerHostname(), 20); JButton save3 = new JButton("Save"); save3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { TestProperties.setGridServerHostname(gridHostText.getText()); } }); JLabel gridPortLabel = new JLabel("Grid Service Port"); final JTextField gridPortText = new JTextField(Integer.toString(TestProperties.getGridServerPort()), 5); JButton save4 = new JButton("Save"); save4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int port = Integer.parseInt(gridPortText.getText()); TestProperties.setGridServerPort(port); } catch (NumberFormatException e) { System.out.println(gridPortText.getText() + " is not a valid port number."); } } }); JLabel excludeLabel = new JLabel("Exclude test cases (comma-separated list):"); final JTextField excludeText = new JTextField("", 30); JButton save5 = new JButton("Save"); save5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String testString = excludeText.getText(); if (testString != null) { String[] testCases = testString.split(","); if (testCases != null && testCases.length > 0) { List<Float> tests = new ArrayList<Float>(); for (String test : testCases) { try { tests.add(Float.parseFloat(test)); } catch (NumberFormatException e) { System.out.println(test + " is not a valid test case."); } } TestProperties.setExcludedTests(tests); } } } }); JLabel includeLabel = new JLabel("Include only (comma-separated list):"); final JTextField includeText = new JTextField("", 30); JButton save6 = new JButton("Save"); save6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String testString = includeText.getText(); if (testString != null) { String[] testCases = testString.split(","); if (testCases != null && testCases.length > 0) { List<Float> tests = new ArrayList<Float>(); for (String test : testCases) { try { tests.add(Float.parseFloat(test)); } catch (NumberFormatException e) { System.out.println(test + " is not a valid test case."); } } TestProperties.setIncludeOnlyTests(tests); } } } }); JLabel threadLabel = new JLabel("Number of threads:"); final JTextField threadText = new JTextField(Integer.toString(TestProperties.getNumThreads()), 5); JButton save7 = new JButton("Save"); save7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int threads = Integer.parseInt(threadText.getText()); TestProperties.setNumThreads(threads); } catch (NumberFormatException e) { System.out.println(threadText.getText() + " is not a valid thread number."); } } }); GridBagLayout topLayout = new GridBagLayout(); topPanel.setLayout(topLayout); JLabel[] labels = new JLabel[] { javaHostLabel, javaPortLabel, gridHostLabel, gridPortLabel, excludeLabel, includeLabel, threadLabel }; JTextField[] textFields = new JTextField[] { javaHostText, javaPortText, gridHostText, gridPortText, excludeText, includeText, threadText }; JButton[] buttons = new JButton[] { save, save2, save3, save4, save5, save6, save7 }; for (int i = 0; i < labels.length; i++) { GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = i; topPanel.add(labels[i], c); c.gridx = 1; topPanel.add(textFields[i], c); c.gridx = 2; topPanel.add(buttons[i], c); } frame.getContentPane().add(topPanel, BorderLayout.PAGE_START); GridLayout bottomLayout = new GridLayout(0, 4); selectionPanel.setLayout(bottomLayout); JCheckBox selectAll = new JCheckBox("Select/Deselect All"); selectAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JCheckBox box = (JCheckBox) e.getSource(); selectAll(box.isSelected()); } }); selectionPanel.add(selectAll); JCheckBox excludeLongTests = new JCheckBox("Exclude Long Tests"); excludeLongTests.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JCheckBox box = (JCheckBox) e.getSource(); if (box.isSelected()) { TestProperties.excludeLongTests(); } else { TestProperties.removeExcludedLongTests(); } } }); TestProperties.excludeLongTests(); excludeLongTests.setSelected(true); selectionPanel.add(excludeLongTests); //Initialize check boxes corresponding to test categories initializeTests(); centerPanel.setLayout(new GridLayout(0, 1)); centerPanel.add(selectionPanel); //Redirect System messages to gui JScrollPane textScroll = new JScrollPane(); textScroll.setViewportView(textDisplay); System.setOut(new PrintStream(new JTextAreaOutputStream(textDisplay))); System.setErr(new PrintStream(new JTextAreaOutputStream(textDisplay))); centerPanel.add(textScroll); JScrollPane scroll = new JScrollPane(centerPanel); frame.getContentPane().add(scroll, BorderLayout.CENTER); JButton runButton = new JButton("Run Tests"); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { runTests(); } catch (Exception e) { System.out.println("An error occured executing the tests: " + e.getClass() + ". Check error log for details."); log.error("Exception encountered:", e); } } }); JPanel bottomPanel = new JPanel(); bottomPanel.add(runButton); frame.getContentPane().add(bottomPanel, BorderLayout.PAGE_END); frame.pack(); frame.setVisible(true); }
From source file:ca.craigthomas.visualclassifier.nn.trainer.TestTrainer.java
@Test public void testHeartbeatOutputToConsole() { Random random = new Random(); mLayerSizes = Arrays.asList(2, 1); DoubleMatrix inputs = DoubleMatrix.ones(500, 2); DoubleMatrix outputs = DoubleMatrix.ones(500, 1); for (int index = 0; index < 500; index++) { double value1 = (double) random.nextInt(100) + 1; double value2 = (double) random.nextInt(100) + 1; if (value1 > 50.0) { inputs.put(index, 0, 1.0);/* w ww . ja va2 s .c o m*/ } else { inputs.put(index, 0, 0.0); } if (value2 > 50.0) { inputs.put(index, 1, 1.0); } else { inputs.put(index, 1, 0.0); } if (value1 > 50.0 || value2 > 50.0) { outputs.put(index, 0, 1.0); } else { outputs.put(index, 0, 0.0); } } ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); mTrainer = new Trainer.Builder(mLayerSizes, inputs, outputs).learningRate(0.001).maxIterations(200) .heartBeat(1).recordCosts().build(); mTrainer.train(); String standardOut = stdOut.toString(); String[] strings = standardOut.split("\\n"); assertEquals(200, strings.length); for (int i = 0; i < strings.length; i++) { assertTrue(strings[i].contains("Iteration: " + (i + 1))); } }
From source file:org.apache.hive.beeline.TestSchemaTool.java
/** * Test schema upgrade//from www.jav a2 s .co m * @throws Exception */ public void testSchemaUpgrade() throws Exception { boolean foundException = false; // Initialize 0.7.0 schema schemaTool.doInit("0.7.0"); // verify that driver fails due to older version schema try { schemaTool.verifySchemaVersion(); } catch (HiveMetaException e) { // Expected to fail due to old schema foundException = true; } if (!foundException) { throw new Exception("Hive operations shouldn't pass with older version schema"); } // Generate dummy pre-upgrade script with errors String invalidPreUpgradeScript = writeDummyPreUpgradeScript(0, "upgrade-0.11.0-to-0.12.0.derby.sql", "foo bar;"); // Generate dummy pre-upgrade scripts with valid SQL String validPreUpgradeScript0 = writeDummyPreUpgradeScript(0, "upgrade-0.12.0-to-0.13.0.derby.sql", "CREATE TABLE schema_test0 (id integer);"); String validPreUpgradeScript1 = writeDummyPreUpgradeScript(1, "upgrade-0.12.0-to-0.13.0.derby.sql", "CREATE TABLE schema_test1 (id integer);"); // Capture system out and err schemaTool.setVerbose(true); OutputStream stderr = new ByteArrayOutputStream(); PrintStream errPrintStream = new PrintStream(stderr); System.setErr(errPrintStream); OutputStream stdout = new ByteArrayOutputStream(); PrintStream outPrintStream = new PrintStream(stdout); System.setOut(outPrintStream); // Upgrade schema from 0.7.0 to latest schemaTool.doUpgrade("0.7.0"); // Verify that the schemaTool ran pre-upgrade scripts and ignored errors assertTrue(stderr.toString().contains(invalidPreUpgradeScript)); assertTrue(stderr.toString().contains("foo")); assertFalse(stderr.toString().contains(validPreUpgradeScript0)); assertFalse(stderr.toString().contains(validPreUpgradeScript1)); assertTrue(stdout.toString().contains(validPreUpgradeScript0)); assertTrue(stdout.toString().contains(validPreUpgradeScript1)); // Verify that driver works fine with latest schema schemaTool.verifySchemaVersion(); }
From source file:nl.vu.psy.rite.Rite.java
public void run() { if (run) {/*from www. j a va 2 s . com*/ Recipe r = null; try { System.out.println("Starting work cycle.."); long sleepTime = Long.parseLong(getProperty(PropertyKeys.INTERVAL)); long scrubDelay = Long.parseLong(getProperty(PropertyKeys.SCRUBDELAY)); long idleDelay = Long.parseLong(getProperty(PropertyKeys.IDLEDELAY)); int maxFailures = Integer.parseInt(getProperty(PropertyKeys.MAXFAILURES)); int maxScrubs = Integer.parseInt(getProperty(PropertyKeys.MAXSCRUBS)); int maxRecipes = Integer.parseInt(getProperty(PropertyKeys.MAXRECIPES)); while (!lifeTimeExceeded() && !halt) { // Check commands ClientCommand co = rh.getClientCommand(identifier); if (co == null) { if (idle) { System.out.println( "-------------------------------------------------------------------------------"); System.out.println("Idle."); System.out.println("Time: " + TimeStamp.dateToString(new Date())); System.out.println( "-------------------------------------------------------------------------------"); try { Thread.sleep(idleDelay); } catch (InterruptedException e) { System.out.println("The work cycle was interrupted: " + e.getMessage()); System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); return; } System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); } else { r = rh.lockRecipe(); // Lock and retrieve recipe if (r == null) { System.out.println( "-------------------------------------------------------------------------------"); System.out.println("No recipe. Scrubbing host."); System.out.println("Time: " + TimeStamp.dateToString(new Date())); System.out.println( "-------------------------------------------------------------------------------"); rh.scrubHost(); scrubs++; if (scrubs > maxScrubs) { System.out.println( "The maximum number of scrubs has been reached. This client will shutdown..."); halt = true; } System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); try { Thread.sleep(scrubDelay); } catch (InterruptedException e) { System.out.println("The work cycle was interrupted: " + e.getMessage()); System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); return; } } else { // Reset scrub counter scrubs = 0; // Set up streams for recipe output PrintStream out = null; PrintStream err = null; try { out = new PrintStream( new FileOutputStream("recipe." + r.getIdentifier() + ".stdout")); PrintStream teeOut = new PrintStream(new TeeOutputStream(System.out, out)); System.setOut(teeOut); err = new PrintStream( new FileOutputStream("recipe." + r.getIdentifier() + ".stderr")); PrintStream teeErr = new PrintStream(new TeeOutputStream(System.err, err)); System.setErr(teeErr); } catch (FileNotFoundException e) { // Absorb System.out.println( "Could not tee output streams to file. Outputting to main application streams only."); } System.out.println( "-------------------------------------------------------------------------------"); System.out.println("Starting recipe: " + r.getIdentifier() + "."); System.out.println("Time: " + TimeStamp.dateToString(new Date())); System.out.println( "-------------------------------------------------------------------------------"); recipeCooker.setRecipe(r); // Run recipe // Wait for completion while (!r.hasCompleted()) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { System.out.println("The work cycle was interrupted: " + e.getMessage()); System.out.println("Attempting release of: " + r.getIdentifier()); r = recipeCooker.getRecipe(); recipeCooker.removeRecipe(); rh.releaseRecipe(r); System.out.println( "=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); return; } } r = recipeCooker.getRecipe(); recipeCooker.removeRecipe(); rh.releaseRecipe(r); recipes++; if (r.hasFailed()) { failures++; } if (failures >= maxFailures) { System.out.println( "The maximum number of recipe failures has been reached. This client will shutdown..."); halt = true; } if (maxRecipes > -1 && recipes >= maxRecipes) { System.out.println( "The maximum number of completed recipes has been reached. This client will shutdown..."); halt = true; } System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); System.setOut(System.out); System.setErr(System.err); if (out != null) { out.close(); out = null; } if (err != null) { err.close(); err = null; } } } } else { // Handle command // FIXME not too fond of all these flags System.out.println( "-------------------------------------------------------------------------------"); System.out.println("Got command: " + co.getCommand()); System.out.println("Time: " + TimeStamp.dateToString(new Date())); System.out.println( "-------------------------------------------------------------------------------"); switch (co.getCommand()) { case HALT: System.out.println("Halting client..."); halt = true; break; case IDLE: System.out.println("Setting client to idle..."); idle = true; break; case RUN: System.out.println("Setting client to run..."); idle = false; break; default: break; } System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); } } //System.out.println("Shutting down..."); if (rh.hasLock()) { System.out.println("Attempting release of: " + r.getIdentifier()); r = recipeCooker.getRecipe(); recipeCooker.removeRecipe(); rh.releaseRecipe(r); System.out.println("=== MARK: " + TimeStamp.dateToString(new Date()) + " ==="); return; } } catch (Exception e) { System.out.println("An exception was encountered while running: " + e.getMessage()); System.out.println("Exiting!"); return; } } }
From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.AFMavenCli.java
public int doMain(AFCliRequest cliRequest, ClassWorld classWorld) { PlexusContainer localContainer = null; PrintStream originalOut = System.out; PrintStream originalErr = System.err; try {//from w w w . j a v a 2s . co m initialize(cliRequest); cli(cliRequest); logging(cliRequest); version(cliRequest); properties(cliRequest); localContainer = container(cliRequest, classWorld); commands(cliRequest); configure(cliRequest); toolchains(cliRequest); populateRequest(cliRequest); repository(cliRequest); return execute(cliRequest); } catch (ExitException e) { e.getStackTrace(); return e.exitCode; } catch (UnrecognizedOptionException e) { e.getStackTrace(); return 1; } catch (BuildAbort e) { e.getStackTrace(); AFCLIReportingUtils.showError(slf4jLogger, "ABORTED", e, cliRequest.isShowErrors()); return 2; } catch (Exception e) { e.getStackTrace(); AFCLIReportingUtils.showError(slf4jLogger, "Error executing Maven.", e, cliRequest.isShowErrors()); return 1; } finally { System.setOut(originalOut); System.setErr(originalErr); if (localContainer != null) { localContainer.dispose(); localContainer = null; } } }
From source file:functionaltests.NodeSourceCommandsFunctTest.java
private String waitForFreeNodesAndList(String nodeSourceName) { try {/*from w ww . j a v a2 s . c om*/ TimeUnit.SECONDS.sleep(WAIT_FOR_FREE_NODES_DURATION); } catch (InterruptedException e) { e.printStackTrace(); } this.clearAndTypeLine("listnodes(\"" + nodeSourceName + "\")"); this.runCli(); String output = this.capturedOutput.toString(); System.setOut(this.stdOut); System.out.println(output); return output; }
From source file:org.apache.maven.cli.DefaultMavenExecutionRequestBuilder.java
/** * configure logging// w ww.jav a2s. co m */ private void logging(CliRequest cliRequest) { cliRequest.debug = cliRequest.commandLine.hasOption(CLIManager.DEBUG); cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption(CLIManager.QUIET); cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.ERRORS); slf4jLoggerFactory = LoggerFactory.getILoggerFactory(); Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory); if (cliRequest.debug) { cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG); slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG); } else if (cliRequest.quiet) { cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR); slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR); } else { cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_INFO); slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.INFO); } if (cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) { File logFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE)); logFile = resolveFile(logFile, cliRequest.workingDirectory); // redirect stdout and stderr to file try { PrintStream ps = new PrintStream(new FileOutputStream(logFile)); System.setOut(ps); System.setErr(ps); } catch (FileNotFoundException e) { // // Ignore // } } slf4jConfiguration.activate(); plexusLoggerManager = new Slf4jLoggerManager(); slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName()); }
From source file:functionaltests.TagCommandsFunctTest.java
@Test public void testJobResultWithTag() throws Exception { typeLine("jobresult(" + jobId.longValue() + ", 'LOOP-T2-1')"); runCli();/*from ww w . j ava 2s . c om*/ String out = this.capturedOutput.toString(); System.setOut(stdOut); System.out.println("------------- testJobResultWithTag:"); System.out.println(out); assertTrue(out.contains("T1#1")); assertTrue(out.contains("Print1#1")); assertTrue(out.contains("Print2#1")); assertTrue(out.contains("T2#1")); assertTrue(!out.contains("T1#2")); assertTrue(!out.contains("Print1#2")); assertTrue(!out.contains("Print2#2")); assertTrue(!out.contains("T2#2")); }