List of usage examples for java.lang System setOut
public static void setOut(PrintStream out)
From source file:TweetAttributes.java
private static void writeOutputToFile(List<TweetAttributes> tweets, String outputFile) throws IOException { try {//from w w w . ja v a 2 s .co m File file = new File(outputFile); //Your file FileOutputStream fos = new FileOutputStream(file); PrintStream ps = new PrintStream(fos); System.setOut(ps); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); // List<Long> output=new ArrayList<>(); // int count=1; Map<Integer, ArrayList> opmap = new HashMap<Integer, ArrayList>(); for (TweetAttributes user : tweets) { if (opmap.containsKey(user.getClusterId())) { opmap.get(user.getClusterId()).add(user.getId()); } else { ArrayList<Long> ids = new ArrayList<Long>(); ids.add(user.getId()); opmap.put(user.getClusterId(), ids); } // count++; } /* for(TweetAttributes model : tweets) { System.out.println(model.getClusterId()+" "+model.getId()); }*/ // System.out.println(outputFile+" "+out); for (Entry<Integer, ArrayList> entry : opmap.entrySet()) { System.out.print(entry.getKey() + " "); for (Object fruitNo : entry.getValue()) { System.out.print(fruitNo); System.out.print(", "); } System.out.println(); } }
From source file:org.moeaframework.TestUtils.java
/** * Invokes the main method of the specified command line utility, * redirecting the output to the specified file. As this method redirects * the {@code System.out} stream, this must be the only process writing to * {@code System.out}./*from www . j ava 2s . c o m*/ * * @param output the file for output redirection * @param tool the command line utility class * @param args the command line arguments * @throws Exception if any of the many exceptions for reflection or * file writing occurred */ public static void pipeCommandLine(File output, Class<?> tool, String... args) throws Exception { PrintStream oldOut = System.out; PrintStream newOut = null; try { newOut = new PrintStream(new FileOutputStream(output)); System.setOut(newOut); Method mainMethod = tool.getMethod("main", String[].class); mainMethod.invoke(null, (Object) args); } finally { if (newOut != null) { newOut.close(); } System.setOut(oldOut); } }
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); }//w w w. j a v a2 s. c o m 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.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); }//from www .j a va2s. 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:functionaltests.NodeSourceCommandsFunctTest.java
private void updateDynamicParametersAndCheckOutput(String nodeSourceName) { System.out.println(LOG_HEADER + " Test updatensparam command"); this.clearAndTypeLine("updatensparam( '" + nodeSourceName + "', " + modifiedInfrastructureParametersString + ", " + restartDownNodesPolicyParametersString + ")"); this.runCli(); String out = this.capturedOutput.toString(); System.setOut(this.stdOut); System.out.println(out);/*from w w w . j a va 2 s .c o m*/ assertThat(out).contains("Node source dynamic parameters successfully updated."); }
From source file:lcmc.ArgumentParser.java
public void parseOptionsAndReturnAutoArguments(String[] args) { final Options options = new Options(); options.addOption("h", HELP_OP, false, "print this help"); options.addOption(null, KEEP_HELPER_OP, false, "do not overwrite the lcmc-gui-helper program"); options.addOption(null, RO_OP, false, "read only mode"); options.addOption(null, OP_OP, false, "operator mode"); options.addOption(null, ADMIN_OP, false, "administrator mode"); options.addOption(null, OP_MODE_OP, true, "operating mode. <arg> can be:\n" + "ro - read only\n" + "op - operator\n" + "admin - administrator"); options.addOption(null, NOLRM_OP, false, "do not show removed resources from LRM."); options.addOption("v", VERSION_OP, false, "print version"); options.addOption(null, AUTO_OP, true, "ADVANCED USE: for testing"); options.addOption(null, PCMKTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, DRBDTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, VMTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, GUITEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, NO_UPGRADE_CHECK_OP, false, "disable upgrade check"); options.addOption(null, NO_PLUGIN_CHECK_OP, false, "disable plugin check, DEPRECATED: there are no plugins"); options.addOption(null, TIGHTVNC_OP, false, "enable tight vnc viewer"); options.addOption(null, ULTRAVNC_OP, false, "enable ultra vnc viewer"); options.addOption(null, REALVNC_OP, false, "enable real vnc viewer"); options.addOption(null, BIGDRBDCONF_OP, false, "create one big drbd.conf, instead of many" + " files in drbd.d/ directory"); options.addOption(null, STAGING_DRBD_OP, false, "enable more DRBD installation options"); options.addOption(null, STAGING_PACEMAKER_OP, false, "enable more Pacemaker installation options"); options.addOption(null, VNC_PORT_OFFSET_OP, true, "offset for port forwarding"); options.addOption(null, SLOW_OP, false, "specify this if you have slow computer"); options.addOption(null, RESTORE_MOUSE_OP, false, "ADVANCED USE: for testing"); options.addOption(null, SCALE_OP, true, "scale fonts and sizes of elements in percent (100)"); options.addOption(null, ID_DSA_OP, true, "location of id_dsa file ($HOME/.ssh/id_dsa)"); options.addOption(null, ID_RSA_OP, true, "location of id_rsa file ($HOME/.ssh/id_rsa)"); options.addOption(null, KNOWN_HOSTS_OP, true, "location of known_hosts file ($HOME/.ssh/known_hosts)"); options.addOption(null, OUT_OP, true, "where to redirect the standard out"); options.addOption(null, DEBUG_OP, true, "debug level, 0 - none, 3 - all"); options.addOption("c", CLUSTER_OP, true, "define a cluster"); final Option hostOp = new Option("h", HOST_OP, true, "define a cluster, used with --cluster option"); hostOp.setArgs(10000);//w w w .j a v a 2s.c om options.addOption(hostOp); options.addOption(null, SUDO_OP, false, "whether to use sudo, used with --cluster option"); options.addOption(null, USER_OP, true, "user to use with sudo, used with --cluster option"); options.addOption(null, PORT_OP, true, "ssh port, used with --cluster option"); options.addOption(null, ADVANCED_OP, false, "start in an advanced mode"); options.addOption(null, ONE_HOST_CLUSTER_OP, false, "allow one host cluster"); options.addOption(null, NO_PASSPHRASE_OP, false, "try no passphrase first"); options.addOption(null, EMBED_OP, false, "embed applet in the browser"); options.addOption(null, NO_EMBED_OP, false, "don't embed applet in the browser"); options.addOption(null, CMD_LOG_OP, false, "Log executed commands to the lcmc.log on the servers"); options.addOption(null, CHECK_SWING_OP, false, "ADVANCED USE: for testing"); final CommandLineParser parser = new PosixParser(); String autoArgs = null; try { final CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(OUT_OP)) { final String out = cmd.getOptionValue(OUT_OP); if (out != null) { try { System.setOut(new PrintStream(new FileOutputStream(out))); } catch (final FileNotFoundException e) { System.exit(2); } } } if (cmd.hasOption(DEBUG_OP)) { final String level = cmd.getOptionValue(DEBUG_OP); if (level != null && lcmc.common.domain.util.Tools.isNumber(level)) { LoggerFactory.setDebugLevel(Integer.parseInt(level)); } else { throw new ParseException("cannot parse debug level: " + level); } } boolean tightvnc = cmd.hasOption(TIGHTVNC_OP); boolean ultravnc = cmd.hasOption(ULTRAVNC_OP); final boolean realvnc = cmd.hasOption(REALVNC_OP); if (!tightvnc && !ultravnc && !realvnc) { if (lcmc.common.domain.util.Tools.isLinux()) { tightvnc = true; } else { tightvnc = true; ultravnc = true; } } final boolean advanced = cmd.hasOption(ADVANCED_OP); access.setAdvancedMode(advanced); application.setUseTightvnc(tightvnc); application.setUseUltravnc(ultravnc); application.setUseRealvnc(realvnc); application.setUpgradeCheckEnabled(!cmd.hasOption(NO_UPGRADE_CHECK_OP)); application.setBigDRBDConf(cmd.hasOption(BIGDRBDCONF_OP)); application.setStagingDrbd(cmd.hasOption(STAGING_DRBD_OP)); application.setStagingPacemaker(cmd.hasOption(STAGING_PACEMAKER_OP)); application.setHideLRM(cmd.hasOption(NOLRM_OP)); application.setKeepHelper(cmd.hasOption(KEEP_HELPER_OP)); application.setOneHostCluster(cmd.hasOption(ONE_HOST_CLUSTER_OP)); application.setNoPassphrase(cmd.hasOption(NO_PASSPHRASE_OP)); if (cmd.hasOption(EMBED_OP)) { application.setEmbedApplet(true); } if (cmd.hasOption(NO_EMBED_OP)) { application.setEmbedApplet(false); } if (cmd.hasOption(CMD_LOG_OP)) { application.setCmdLog(true); } if (cmd.hasOption(CHECK_SWING_OP)) { swingUtils.setCheckSwing(true); } final String pwd = System.getProperty("user.home"); final String scaleOp = cmd.getOptionValue(SCALE_OP, "100"); try { final int scale = Integer.parseInt(scaleOp); application.setScale(scale); application.resizeFonts(scale); } catch (final NumberFormatException e) { LOG.appWarning("initApp: cannot parse scale: " + scaleOp); } final String idDsaPath = cmd.getOptionValue(ID_DSA_OP, pwd + "/.ssh/id_dsa"); final String idRsaPath = cmd.getOptionValue(ID_RSA_OP, pwd + "/.ssh/id_rsa"); final String knownHostsPath = cmd.getOptionValue(KNOWN_HOSTS_OP, pwd + "/.ssh/known_hosts"); application.setIdDSAPath(idDsaPath); application.setIdRSAPath(idRsaPath); application.setKnownHostPath(knownHostsPath); final String opMode = cmd.getOptionValue(OP_MODE_OP); autoArgs = cmd.getOptionValue(AUTO_OP); if (cmd.hasOption(HELP_OP)) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar LCMC.jar [OPTIONS]", options); System.exit(0); } if (cmd.hasOption(VERSION_OP)) { System.out.println("LINUX CLUSTER MANAGEMENT CONSOLE " + lcmc.common.domain.util.Tools.getRelease() + " by Rasto Levrinc"); System.exit(0); } if (cmd.hasOption("ro") || "ro".equals(opMode)) { access.setAccessType(AccessMode.RO); access.setMaxAccessType(AccessMode.RO); } else if (cmd.hasOption("op") || "op".equals(opMode)) { access.setAccessType(AccessMode.OP); access.setMaxAccessType(AccessMode.OP); } else if (cmd.hasOption("admin") || "admin".equals(opMode)) { access.setAccessType(AccessMode.ADMIN); access.setMaxAccessType(AccessMode.ADMIN); } else if (opMode != null) { LOG.appWarning("initApp: unknown operating mode: " + opMode); } float fps = MainData.DEFAULT_ANIM_FPS; if (cmd.hasOption(SLOW_OP)) { fps /= 2; } if (cmd.hasOption(RESTORE_MOUSE_OP)) { /* restore mouse if it is stuck in pressed state, during * robot tests. */ roboTest.restoreMouse(); } final String vncPortOffsetString = cmd.getOptionValue(VNC_PORT_OFFSET_OP); if (vncPortOffsetString != null && lcmc.common.domain.util.Tools.isNumber(vncPortOffsetString)) { application.setVncPortOffset(Integer.parseInt(vncPortOffsetString)); } mainData.setAnimFPS(fps); if (cmd.hasOption(CLUSTER_OP) || cmd.hasOption(HOST_OP)) { parseClusterOptionsAndCreateClusterButton(cmd); } } catch (final ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.exit(1); } LOG.debug1("initApp: max mem: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + 'm'); if (autoArgs != null) { parseAutoArgs(autoArgs); } }
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 w w .ja v a 2s. co 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: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); }/*from w w w. j a va 2 s . c o m*/ 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:it.crs4.seal.read_sort.MergeAlignments.java
/** * Scan command line and set configuration values appropriately. * Calls System.exit in case of a command line error. *//*w w w . ja va 2s . c o m*/ @SuppressWarnings("static") // for OptionBuilder private void scanOptions(String[] args) { Options options = new Options(); Option ref = OptionBuilder.withDescription("root path to the reference used to create the SAM data") .hasArg().withArgName("REF_PATH").withLongOpt("reference").create("ref"); options.addOption(ref); Option ann = OptionBuilder.withDescription( "annotation file (.ann) of the BWA reference used to create the SAM data (not required if you specify " + ref.getOpt() + ")") .hasArg().withArgName("ref.ann").withLongOpt("annotations").create("ann"); options.addOption(ann); Option md5 = OptionBuilder.withDescription("generated MD5 checksums for reference contigs") .withLongOpt("md5").create("md5"); options.addOption(md5); Option optSortOrder = OptionBuilder.withDescription( "Sort order. Can be one of: unknown, unsorted, queryname, coordinate. Default: coordinate") .hasArg().withArgName("sort order").withLongOpt("sort-order").create("so"); options.addOption(optSortOrder); Option as = OptionBuilder.withDescription("Genome assembly identifier (@SQ AS:xxxx tag)").hasArg() .withArgName("ASSEMBLY_ID").withLongOpt("sq-assembly").create("sqas"); options.addOption(as); Option optHeaderOnly = OptionBuilder.withDescription("Only output the SAM header, then exit.") .withLongOpt("header-only").create("ho"); options.addOption(optHeaderOnly); // read group options Map<String, Option> readGroupOptions = defineRGOptions(); for (Option opt : readGroupOptions.values()) options.addOption(opt); CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(ref.getOpt())) userReferenceRoot = line.getOptionValue(ref.getOpt()); if (line.hasOption(md5.getOpt())) generatedMd5 = true; if (line.hasOption(ann.getOpt())) userAnnotation = line.getOptionValue(ann.getOpt()); if (line.hasOption(as.getOpt())) // TODO: validate this input genomeAssemblyId = line.getOptionValue(as.getOpt()); if (line.hasOption(optSortOrder.getOpt())) { String value = line.getOptionValue(optSortOrder.getOpt()); if ("unknown".equals(value) || "unsorted".equals(value) || "queryname".equals(value) || "coordinate".equals(value)) sortOrder = value; else throw new ParseException( "Invalid sort order. Sort order must be one of: unknown, unsorted, queryname, coordinate."); } if (line.hasOption(optHeaderOnly.getOpt())) headerOnly = true; // remaining args String[] otherArgs = line.getArgs(); if (headerOnly) { // We're only generating the header, so we don't expect any input reads. if (otherArgs.length > 1) throw new ParseException( "You can't provide an input path with --header-only. Provide an output path or let the output go to stdout."); if (otherArgs.length == 0) userOutput = null; else userOutput = otherArgs[0]; } else // not headerOnly { if (otherArgs.length <= 0 || otherArgs.length > 2) throw new ParseException( "You must provide an HDFS input path and, optionally, an output path."); userOutput = null; userInput = otherArgs[0]; if (otherArgs.length >= 2) userOutput = otherArgs[1]; } readGroupFields = parseReadGroupOptions(readGroupOptions, line); // option validation if (generatedMd5 && userReferenceRoot == null) throw new ParseException( "You must specify the path the reference if you want to generate MD5 checksums"); if (userReferenceRoot == null && userAnnotation == null) throw new ParseException( "You must provide the path to the reference or at least its annotation file (<ref>.ann)"); } catch (ParseException e) { System.err.println("Usage error: " + e.getMessage()); // XXX: redirect System.out to System.err since the simple version of // HelpFormatter.printHelp prints to System.out, and we're on a way to // a fatal exit. System.setOut(System.err); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("MergeAlignments [options] -ann <ref>.ann [<in>] [<out>]", options); System.exit(1); } }
From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java
private static String tryCreateMozilla() { if (EnvironmentUtils.IS_LINUX) { boolean oldDebug = Device.DEBUG; Device.DEBUG = true;//from w w w . j a v a 2 s . c o m PrintStream oldOut = System.out; Shell shell = null; PrintStream newOut = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); newOut = new PrintStream(baos); // replace the out since the Mozilla output debug results into // stdout. System.setOut(newOut); shell = new Shell(); try { new Browser(shell, SWT.NONE); } catch (Throwable e) { UIUtils.showError(e); } return baos.toString(); } catch (Throwable e1) { // ignore } finally { if (shell != null) { shell.dispose(); } System.setOut(oldOut); IOUtils.closeQuietly(newOut); Device.DEBUG = oldDebug; } } return ""; //$NON-NLS-1$ }