List of usage examples for java.lang System setErr
public static void setErr(PrintStream err)
From source file:org.apache.hadoop.hdfs.server.namenode.TestClusterId.java
/** * Test namenode format with -format -clusterid and empty clusterid. Format * should fail as no valid if was provided. * * @throws IOException//from w w w. j a v a 2s.c o m */ @Test(timeout = 300000) public void testFormatWithEmptyClusterIdOption() throws IOException { String[] argv = { "-format", "-clusterid", "" }; PrintStream origErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream stdErr = new PrintStream(baos); System.setErr(stdErr); NameNode.createNameNode(argv, config); // Check if usage is printed assertTrue(baos.toString("UTF-8").contains("Usage: java NameNode")); System.setErr(origErr); // check if the version file does not exists. File version = new File(hdfsDir, "current/VERSION"); assertFalse("Check version should not exist", version.exists()); }
From source file:org.sherlok.UimaPipeline.java
private void initEngines() throws UIMAException, SherlokException { // redirect stdout to catch Ruta script errors ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); PrintStream origOut = System.out; PrintStream origErr = System.err; System.setOut(new PrintStream(baosOut)); System.setErr(new PrintStream(baosErr)); try {// w w w. j a v a2s .c om // initialize Engines aes = createEngines(aeds.toArray(new AnalysisEngineDescription[aeds.size()])); } finally { // so that we restore Sysout in any case // catching Ruta script outputs (these contain errors) String maybeOut = baosOut.toString(); System.setOut(origOut); // restore String maybeErr = baosErr.toString(); System.setErr(origErr); // restore if (maybeErr.startsWith("Adding annotator")) { maybeErr = "";// fix for StanfordNLP output FIXME } else if (maybeErr.contains("Couldn't open cc.mallet.util.MalletLogger")) { maybeErr = "";// fix for Mallet FIXME } if (maybeOut.length() > 0) LOG.info(maybeOut); if (maybeErr.length() > 0) LOG.error(maybeErr); if (maybeErr.length() > 0) { LOG.info("Ruta script error" + maybeErr); throw new SherlokException("Ruta script error: " + maybeErr).setObject(this.pipelineDef.toString()); } for (String line : maybeOut.split("\n")) { if (line.startsWith("Error in line")) { // translate error messages for (Entry<String, String> e : CHAR_MAPPING.entrySet()) { line = line.replaceAll(e.getKey(), "'" + e.getValue() + "'"); } throw new SherlokException("Ruta script error on line " + line) .setObject(this.pipelineDef.toString()); } } } }
From source file:org.tinygroup.jspengine.compiler.JspRuntimeContext.java
/** * Process a "destory" event for this web application context. */// ww w .ja v a 2s .com public void destroy() { if (System.err instanceof SystemLogHandler) System.setErr(((SystemLogHandler) System.err).getWrapped()); threadStop(); for (JspServletWrapper jsw : jsps.values()) { jsw.destroy(); } parentClassLoader = null; }
From source file:VASSAL.launch.ModuleManager.java
public ModuleManager(ServerSocket serverSocket, long key, FileOutputStream lout, FileLock lock) throws IOException { if (instance != null) throw new IllegalStateException(); instance = this; this.serverSocket = serverSocket; this.key = key; // we hang on to these to prevent the lock from being lost this.lout = lout; this.lock = lock; // truncate the errorLog final File errorLog = new File(Info.getHomeDir(), "errorLog"); new FileOutputStream(errorLog).close(); final StartUp start = SystemUtils.IS_OS_MAC_OSX ? new ModuleManagerMacOSXStartUp() : new StartUp(); start.startErrorLog();/*ww w . ja va 2 s. co m*/ // log everything which comes across our stderr System.setErr(new PrintStream(new LoggedOutputStream(), true)); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); start.initSystemProperties(); // check whether we need to migrate pre-3.2 preferences final File oldprefs = new File(System.getProperty("user.home"), "VASSAL/Preferences"); if (oldprefs.exists()) { final File newprefs = new File(Info.getHomeDir(), "Preferences"); if (!newprefs.exists()) { FileUtils.copyFile(oldprefs, newprefs); } } if (SystemUtils.IS_OS_MAC_OSX) new MacOSXMenuManager(); else new ModuleManagerMenuManager(); SwingUtilities.invokeLater(new Runnable() { public void run() { launch(); } }); // ModuleManagerWindow.getInstance() != null now, so listen on the socket new Thread(new SocketListener(serverSocket), "socket listener").start(); final Prefs globalPrefs = Prefs.getGlobalPrefs(); // determine when we should next check on the current version of VASSAL final LongConfigurer nextVersionCheckConfig = new LongConfigurer(NEXT_VERSION_CHECK, null, -1L); globalPrefs.addOption(null, nextVersionCheckConfig); long nextVersionCheck = nextVersionCheckConfig.getLongValue(-1L); if (nextVersionCheck < System.currentTimeMillis()) { new UpdateCheckRequest().execute(); } // set the time for the next version check if (nextVersionCheck == -1L) { // this was our first check; randomly check after 0-10 days to // to spread version checks evenly over a 10-day period nextVersionCheck = System.currentTimeMillis() + (long) (Math.random() * 10 * 86400000); } else { // check again in 10 days nextVersionCheck += 10 * 86400000; } nextVersionCheckConfig.setValue(nextVersionCheck); // FIXME: the importer heap size configurers don't belong here // the initial heap size for the module importer final IntConfigurer initHeapConf = new IntConfigurer(INITIAL_HEAP, Resources.getString("GlobalOptions.initial_heap"), //$NON-NLS-1$ Integer.valueOf(256)); globalPrefs.addOption("Importer", initHeapConf); // the maximum heap size for the module importer final IntConfigurer maxHeapConf = new IntConfigurer(MAXIMUM_HEAP, Resources.getString("GlobalOptions.maximum_heap"), //$NON-NLS-1$ Integer.valueOf(512)); globalPrefs.addOption("Importer", maxHeapConf); /* final InetAddress lo = InetAddress.getByName(null); signalServerSocket = new ServerSocket(0, 0, lo); final MultiplexedSignalSource mss = new DefaultMultiplexedSignalSource(); final SignalDispatcher sd = new SignalDispatcher(mss); sd.addEventListener( AbstractLaunchAction.NotifyOpenModuleOk.class, new AbstractLaunchAction.NotifyOpenModuleOkListener() ); sd.addEventListener( AbstractLaunchAction.NotifyNewModuleOk.class, new AbstractLaunchAction.NotifyNewModuleOkListener() ); sd.addEventListener( AbstractLaunchAction.NotifyImportModuleOk.class, new AbstractLaunchAction.NotifyImportModuleOkListener() ); sd.addEventListener( AbstractLaunchAction.NotifyOpenModuleFailed.class, new AbstractLaunchAction.NotifyOpenModuleFailedListener() ); sd.addEventListener( AbstractLaunchAction.NotifySaveFileOk.class, new AbstractLaunchAction.NotifySaveFileOkListener() ); final SignalSender ss = new SignalSender(); signalServer = new SignalServer(signalServerSocket, mss, sd, ss); new Thread(signalServer, "comm server").start(); */ }
From source file:org.pantsbuild.tools.junit.impl.ConsoleRunnerImpl.java
void run(Iterable<String> tests) { System.setOut(new PrintStream(SWAPPABLE_OUT)); System.setErr(new PrintStream(SWAPPABLE_ERR)); List<Request> requests = parseRequests(SWAPPABLE_OUT.getOriginal(), SWAPPABLE_ERR.getOriginal(), tests); if (numTestShards > 0) { requests = setFilterForTestShard(requests); }/*ww w . ja v a 2 s .co m*/ JUnitCore core = new JUnitCore(); final AbortableListener abortableListener = new AbortableListener(failFast) { @Override protected void abort(Result failureResult) { exit(failureResult.getFailureCount()); } }; core.addListener(abortableListener); if (xmlReport) { if (!outdir.exists()) { if (!outdir.mkdirs()) { throw new IllegalStateException("Failed to create output directory: " + outdir); } } StreamCapturingListener streamCapturingListener = new StreamCapturingListener(outdir, !suppressOutput); abortableListener.addListener(streamCapturingListener); AntJunitXmlReportListener xmlReportListener = new AntJunitXmlReportListener(outdir, streamCapturingListener); abortableListener.addListener(xmlReportListener); } // TODO: Register all listeners to core instead of to abortableListener because // abortableListener gets removed when one of the listener throws exceptions in // RunNotifier.java. Other listeners should not get removed. if (perTestTimer) { abortableListener.addListener(new PerTestConsoleListener(SWAPPABLE_OUT.getOriginal())); } else { core.addListener(new ConsoleListener(SWAPPABLE_OUT.getOriginal())); } // Wrap test execution with registration of a shutdown hook that will ensure we // never exit silently if the VM does. final Thread abnormalExitHook = createAbnormalExitHook(abortableListener, SWAPPABLE_OUT.getOriginal()); Runtime.getRuntime().addShutdownHook(abnormalExitHook); int failures = 0; try { if (this.parallelThreads > 1) { ConcurrentCompositeRequest request = new ConcurrentCompositeRequest(requests, this.defaultParallel, this.parallelThreads); failures = core.run(request).getFailureCount(); } else { for (Request request : requests) { Result result = core.run(request); failures += result.getFailureCount(); } } } catch (InitializationError initializationError) { failures = 1; } finally { // If we're exiting via a thrown exception, we'll get a better message by letting it // propagate than by halt()ing. Runtime.getRuntime().removeShutdownHook(abnormalExitHook); } exit(failures); }
From source file:org.apache.jk.server.JkMain.java
public void init() throws IOException { long t1 = System.currentTimeMillis(); if (null != out) { PrintStream outS = new PrintStream(new FileOutputStream(out)); System.setOut(outS);//from ww w. j av a 2s.c om } if (null != err) { PrintStream errS = new PrintStream(new FileOutputStream(err)); System.setErr(errS); } String home = getWorkerEnv().getJkHome(); if (home == null) { // XXX use IntrospectionUtil to find myself this.guessHome(); } home = getWorkerEnv().getJkHome(); if (home == null) { log.info("Can't find home, jk2.properties not loaded"); } if (home != null) { File hF = new File(home); File conf = new File(home, "conf"); if (!conf.exists()) conf = new File(home, "etc"); propsF = new File(conf, "jk2.properties"); if (propsF.exists()) { log.debug("Starting Jk2, base dir= " + home + " conf=" + propsF); setPropertiesFile(propsF.getAbsolutePath()); } else { log.debug("Starting Jk2, base dir= " + home); if (log.isDebugEnabled()) log.debug("No properties file found " + propsF); } } String initHTTPS = (String) props.get("class.initHTTPS"); if ("true".equalsIgnoreCase(initHTTPS)) { initHTTPSUrls(); } long t2 = System.currentTimeMillis(); initTime = t2 - t1; }
From source file:org.apache.maven.cli.MavenCli.java
public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) { PrintStream oldout = System.out; PrintStream olderr = System.err; final Set<String> realms; if (classWorld != null) { realms = new HashSet<>(); for (ClassRealm realm : classWorld.getRealms()) { realms.add(realm.getId());//from w ww.j a v a 2s . c o m } } else { realms = Collections.emptySet(); } try { if (stdout != null) { System.setOut(stdout); } if (stderr != null) { System.setErr(stderr); } CliRequest cliRequest = new CliRequest(args, classWorld); cliRequest.workingDirectory = workingDirectory; return doMain(cliRequest); } finally { if (classWorld != null) { for (ClassRealm realm : new ArrayList<>(classWorld.getRealms())) { String realmId = realm.getId(); if (!realms.contains(realmId)) { try { classWorld.disposeRealm(realmId); } catch (NoSuchRealmException ignored) { // can't happen } } } } System.setOut(oldout); System.setErr(olderr); } }
From source file:org.apache.hadoop.mapreduce.TestMRJobClient.java
/** * test start form console command without options *//*ww w . j a v a 2s . c o m*/ private void startStop() { ByteArrayOutputStream data = new ByteArrayOutputStream(); PrintStream error = System.err; System.setErr(new PrintStream(data)); ExitUtil.disableSystemExit(); try { CLI.main(new String[0]); fail(" CLI.main should call System.exit"); } catch (ExitUtil.ExitException e) { ExitUtil.resetFirstExitException(); assertEquals(-1, e.status); } catch (Exception e) { } finally { System.setErr(error); } // in console should be written help text String s = new String(data.toByteArray()); assertTrue(s.contains("-submit")); assertTrue(s.contains("-status")); assertTrue(s.contains("-kill")); assertTrue(s.contains("-set-priority")); assertTrue(s.contains("-events")); assertTrue(s.contains("-history")); assertTrue(s.contains("-list")); assertTrue(s.contains("-list-active-trackers")); assertTrue(s.contains("-list-blacklisted-trackers")); assertTrue(s.contains("-list-attempt-ids")); assertTrue(s.contains("-kill-task")); assertTrue(s.contains("-fail-task")); assertTrue(s.contains("-logs")); }
From source file:com.sun.grizzly.http.jk.server.JkMain.java
public void init() throws IOException { long t1 = System.currentTimeMillis(); if (null != out) { PrintStream outS = new PrintStream(new FileOutputStream(out)); System.setOut(outS);/*w w w .j a v a2 s .com*/ } if (null != err) { PrintStream errS = new PrintStream(new FileOutputStream(err)); System.setErr(errS); } String home = getWorkerEnv().getJkHome(); if (home == null) { // XXX use IntrospectionUtil to find myself this.guessHome(); } home = getWorkerEnv().getJkHome(); if (home == null) { LoggerUtils.getLogger().info("Can't find home, jk2.properties not loaded"); } if (LoggerUtils.getLogger().isLoggable(Level.FINEST)) { LoggerUtils.getLogger().log(Level.FINEST, "Starting Jk2, base dir= " + home); } loadPropertiesFile(); String initHTTPS = (String) props.get("class.initHTTPS"); if ("true".equalsIgnoreCase(initHTTPS)) { initHTTPSUrls(); } long t2 = System.currentTimeMillis(); initTime = t2 - t1; }
From source file:com.diversityarrays.dal.server.ServerGui.java
public ServerGui(Image serverIconImage, IDalServer svr, DalServerFactory factory, File wwwRoot, DalServerPreferences prefs) {/*from ww w . j a v a 2s.c o m*/ this.serverIconImage = serverIconImage; this.dalServerFactory = factory; this.wwwRoot = wwwRoot; this.preferences = prefs; JMenuBar menuBar = new JMenuBar(); JMenu serverMenu = new JMenu("Server"); menuBar.add(serverMenu); serverMenu.add(serverStartAction); serverMenu.add(serverStopAction); serverMenu.add(exitAction); JMenu commandMenu = new JMenu("Command"); menuBar.add(commandMenu); commandMenu.add(doSql); JMenu urlMenu = new JMenu("URL"); menuBar.add(urlMenu); urlMenu.add(new JMenuItem(copyDalUrlAction)); urlMenu.add(new JMenuItem(showDalUrlQRcodeAction)); setJMenuBar(menuBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); messages.setFont(GuiUtil.createMonospacedFont(12)); messages.setEditable(false); setServer(svr); quietOption.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean q = quietOption.isSelected(); if (server != null) { server.setQuiet(q); } } }); JScrollPane scrollPane = new JScrollPane(messages, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); final JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar(); JButton clear = new JButton(new AbstractAction("Clear") { @Override public void actionPerformed(ActionEvent e) { messages.setText(""); } }); final boolean[] follow = new boolean[] { true }; final JCheckBox followTail = new JCheckBox("Follow", follow[0]); followTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { follow[0] = followTail.isSelected(); } }); final OutputStream os = new OutputStream() { @Override public void write(int b) throws IOException { char ch = (char) b; messages.append(new Character(ch).toString()); if (ch == '\n' && follow[0]) { verticalScrollBar.setValue(verticalScrollBar.getMaximum()); } } }; TeePrintStream pso = new TeePrintStream(System.out, os); TeePrintStream pse = new TeePrintStream(System.err, os); System.setErr(pse); System.setOut(pso); Box box = Box.createHorizontalBox(); box.add(clear); box.add(followTail); box.add(quietOption); box.add(Box.createHorizontalGlue()); JPanel bottom = new JPanel(new BorderLayout()); bottom.add(BorderLayout.NORTH, box); bottom.add(BorderLayout.SOUTH, statusInfoLine); Container cp = getContentPane(); cp.add(BorderLayout.CENTER, scrollPane); cp.add(BorderLayout.SOUTH, bottom); pack(); setSize(640, 480); final MemoryUsageMonitor mum = new MemoryUsageMonitor(); mum.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { statusInfoLine.setMessage(mum.getMemoryUsage()); } }); if (server == null) { // If initial server is null, allow user to specify addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { removeWindowListener(this); serverStartAction.actionPerformed(null); } }); } else { addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { removeWindowListener(this); ensureDatabaseInitialisedThenStartServer(); } }); } }