List of usage examples for java.lang System setErr
public static void setErr(PrintStream err)
From source file:runtime.starter.MPJAppMaster.java
public void run() throws Exception { try {//from w w w .j av a 2 s .co m appMasterSock = new Socket(serverName, ioServerPort); //redirecting stdout and stderr System.setOut(new PrintStream(appMasterSock.getOutputStream(), true)); System.setErr(new PrintStream(appMasterSock.getOutputStream(), true)); } catch (Exception exp) { exp.printStackTrace(); } FileSystem fs = FileSystem.get(conf); Path wrapperDest = new Path(wrapperPath); FileStatus destStatus = fs.getFileStatus(wrapperDest); Path userFileDest = new Path(userJarPath); FileStatus destStatusClass = fs.getFileStatus(userFileDest); // Initialize AM <--> RM communication protocol AMRMClient<ContainerRequest> rmClient = AMRMClient.createAMRMClient(); rmClient.init(conf); rmClient.start(); // Initialize AM <--> NM communication protocol NMClient nmClient = NMClient.createNMClient(); nmClient.init(conf); nmClient.start(); // Register with ResourceManager RegisterApplicationMasterResponse registerResponse = rmClient.registerApplicationMaster("", 0, ""); // Priority for containers - priorities are intra-application Priority priority = Records.newRecord(Priority.class); priority.setPriority(mpjContainerPriority); maxMem = registerResponse.getMaximumResourceCapability().getMemory(); if (debugYarn) { System.out.println("[MPJAppMaster]: Max memory capability resources " + "in cluster: " + maxMem); } if (containerMem > maxMem) { System.out.println("[MPJAppMaster]: container memory specified above " + "threshold of cluster! Using maximum memory for " + "containers: " + containerMem); containerMem = maxMem; } maxCores = registerResponse.getMaximumResourceCapability().getVirtualCores(); if (debugYarn) { System.out.println("[MPJAppMaster]: Max v-cores capability resources " + "in cluster: " + maxCores); } if (containerCores > maxCores) { System.out.println("[MPJAppMaster]: virtual cores specified above " + "threshold of cluster! Using maximum v-cores for " + "containers: " + containerCores); containerCores = maxCores; } // Resource requirements for containers Resource capability = Records.newRecord(Resource.class); capability.setMemory(containerMem); capability.setVirtualCores(containerCores); // Make container requests to ResourceManager for (int i = 0; i < np; ++i) { ContainerRequest containerReq = new ContainerRequest(capability, null, null, priority); rmClient.addContainerRequest(containerReq); } Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); // Creating Local Resource for Wrapper LocalResource wrapperJar = Records.newRecord(LocalResource.class); wrapperJar.setResource(ConverterUtils.getYarnUrlFromPath(wrapperDest)); wrapperJar.setSize(destStatus.getLen()); wrapperJar.setTimestamp(destStatus.getModificationTime()); wrapperJar.setType(LocalResourceType.ARCHIVE); wrapperJar.setVisibility(LocalResourceVisibility.APPLICATION); // Creating Local Resource for UserClass LocalResource userClass = Records.newRecord(LocalResource.class); userClass.setResource(ConverterUtils.getYarnUrlFromPath(userFileDest)); userClass.setSize(destStatusClass.getLen()); userClass.setTimestamp(destStatusClass.getModificationTime()); userClass.setType(LocalResourceType.ARCHIVE); userClass.setVisibility(LocalResourceVisibility.APPLICATION); localResources.put("mpj-yarn-wrapper.jar", wrapperJar); localResources.put("user-code.jar", userClass); while (allocatedContainers < np) { AllocateResponse response = rmClient.allocate(0); mpiContainers.addAll(response.getAllocatedContainers()); allocatedContainers = mpiContainers.size(); if (allocatedContainers != np) { Thread.sleep(100); } } if (debugYarn) { System.out.println("[MPJAppMaster]: launching " + allocatedContainers + " containers"); } for (Container container : mpiContainers) { ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class); List<String> commands = new ArrayList<String>(); commands.add(" $JAVA_HOME/bin/java"); commands.add(" -Xmx" + containerMem + "m"); commands.add(" runtime.starter.MPJYarnWrapper"); commands.add("--serverName"); commands.add(serverName); // server name commands.add("--ioServerPort"); commands.add(Integer.toString(ioServerPort)); // IO server port commands.add("--deviceName"); commands.add(deviceName); // device name commands.add("--className"); commands.add(className); // class name commands.add("--psl"); commands.add(psl); // protocol switch limit commands.add("--np"); commands.add(Integer.toString(np)); // no. of containers commands.add("--rank"); commands.add(" " + Integer.toString(rank++)); // rank //temp sock port to share rank and ports commands.add("--wireUpPort"); commands.add(wireUpPort); if (appArgs != null) { commands.add("--appArgs"); for (int i = 0; i < appArgs.length; i++) { commands.add(appArgs[i]); } } ctx.setCommands(commands); // Set local resource for containers ctx.setLocalResources(localResources); // Set environment for container Map<String, String> containerEnv = new HashMap<String, String>(); setupEnv(containerEnv); ctx.setEnvironment(containerEnv); // Time to start the container nmClient.startContainer(container, ctx); } while (completedContainers < np) { // argument to allocate() is the progress indicator AllocateResponse response = rmClient.allocate(completedContainers / np); for (ContainerStatus status : response.getCompletedContainersStatuses()) { if (debugYarn) { System.out.println("\n[MPJAppMaster]: Container Id - " + status.getContainerId()); System.out.println("[MPJAppMaster]: Container State - " + status.getState().toString()); System.out.println("[MPJAppMaster]: Container Diagnostics - " + status.getDiagnostics()); } ++completedContainers; } if (completedContainers != np) { Thread.sleep(100); } ; } // Un-register with ResourceManager rmClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "", ""); //shutDown AppMaster IO System.out.println("EXIT"); }
From source file:org.apache.maven.cli.CopyOfMavenCli.java
public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) { PrintStream oldout = System.out; PrintStream olderr = System.err; try {//from ww w . j a v a 2s. c om 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 { System.setOut(oldout); System.setErr(olderr); } }
From source file:com.eviware.loadui.launcher.LoadUILauncher.java
/** * Initiates and starts the OSGi runtime. */// w ww.j a v a2s . co m public LoadUILauncher(String[] args) { argv = args; //Fix for Protection! String username = System.getProperty("user.name"); System.setProperty("user.name.original", username); System.setProperty("user.name", username.toLowerCase()); File externalFile = new File(WORKING_DIR, "res/buildinfo.txt"); //Workaround for some versions of Java 6 which have a known SSL issue String versionString = System.getProperty("java.version", "0.0.0_00"); try { if (versionString.startsWith("1.6") && versionString.contains("_")) { int updateVersion = Integer.parseInt(versionString.split("_", 2)[1]); if (updateVersion > 27) { log.info("Detected Java version " + versionString + ", disabling CBC Protection."); System.setProperty("jsse.enableCBCProtection", "false"); } } } catch (Exception e) { e.printStackTrace(); } if (externalFile.exists()) { try (InputStream is = new FileInputStream(externalFile)) { Properties buildinfo = new Properties(); buildinfo.load(is); System.setProperty(LOADUI_BUILD_NUMBER, buildinfo.getProperty("build.number")); System.setProperty(LOADUI_BUILD_DATE, buildinfo.getProperty("build.date")); System.setProperty(LOADUI_NAME, buildinfo.getProperty(LOADUI_NAME, "loadUI")); } catch (IOException e) { e.printStackTrace(); } } else { System.setProperty(LOADUI_BUILD_NUMBER, "unknown"); System.setProperty(LOADUI_BUILD_DATE, "unknown"); System.setProperty(LOADUI_NAME, "loadUI"); } options = createOptions(); CommandLineParser parser = new PosixParser(); try { cmd = parser.parse(options, argv); } catch (ParseException e) { System.err.print("Error parsing commandline args: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("", options); exitInError(); throw new RuntimeException(); } if (cmd.hasOption(SYSTEM_PROPERTY_OPTION)) { parseSystemProperties(); } initSystemProperties(); String sysOutFilePath = System.getProperty("system.out.file"); if (sysOutFilePath != null) { File sysOutFile = new File(sysOutFilePath); if (!sysOutFile.exists()) { try { sysOutFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { System.err.println("Writing stdout and stderr to file:" + sysOutFile.getAbsolutePath()); final PrintStream outStream = new PrintStream(sysOutFile); System.setOut(outStream); System.setErr(outStream); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { outStream.close(); } })); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } System.out.println("Launching " + System.getProperty(LOADUI_NAME) + " Build: " + System.getProperty(LOADUI_BUILD_NUMBER, "[internal]") + " " + System.getProperty(LOADUI_BUILD_DATE, "")); Main.loadSystemProperties(); configProps = Main.loadConfigProperties(); if (configProps == null) { System.err.println("There was an error loading the OSGi configuration!"); exitInError(); } Main.copySystemProperties(configProps); }
From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java
public void vcsImportCommand(String prefix, String arguments, String vcsIgnoreMessages, String propertyFile) throws CompositeException { String identifier = "VCSWSDAOImpl.vcsImportCommand"; // some unique identifier that characterizes this invocation. String actionName = "IMPORT"; try {/*from w w w . j a va 2 s . c om*/ boolean preserveQuotes = false; boolean initArgsList = true; List<String> argsList = new ArrayList<String>(); // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. // If so then force a no operation to happen by performing a -printcontents for pkg_import // mtinius-2016-04-14: commented out until a full analysis can be done. //if (CommonUtils.isExecOperation() && !arguments.toLowerCase().contains("-printcontents")) // arguments = arguments + " -printcontents"; // Parse the arguments argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile); String[] args = argsList.toArray(new String[0]); /* * 2014-02-14 (mtinius): Removed the PDTool Archive capability */ // ImportCommand.startCommand(null, null, args); /* * 2014-02-14 (mtinius): Added security manager around the Composite native Archive code because * it has System.out.println and System.exit commands. Need to trap both. */ String maskedargsList = CommonUtils.getArgumentListMasked(argsList); if (logger.isDebugEnabled()) { logger.debug(identifier + "(prefix, arguments, vcsIngoreMessages, propertyFile). prefix=" + prefix + " arguments=[" + maskedargsList + "]" + " vcsIgnoreMessages=" + vcsIgnoreMessages + " propertyFile=" + propertyFile); } // Get the existing security manager SecurityManager sm = System.getSecurityManager(); PrintStream originalOut = System.out; PrintStream originalErr = System.err; String command = "ImportCommand.startCommand"; try { // Get the offset location of the java.policy file [offset from PDTool home]. String javaPolicyOffset = CommonConstants.javaPolicy; String javaPolicyLocation = CommonUtils.extractVariable(prefix, CommonUtils.getFileOrSystemPropertyValue(propertyFile, "PROJECT_HOME_PHYSICAL"), propertyFile, true) + javaPolicyOffset; // Set the java security policy System.getProperties().setProperty("java.security.policy", javaPolicyLocation); // Create a new System.out Logger Logger exportLogger = Logger.getLogger(ImportCommand.class); System.setOut(new PrintStream(new LogOutputStream(exportLogger, Level.INFO))); System.setErr(new PrintStream(new LogOutputStream(exportLogger, Level.ERROR))); // Create a new security manager System.setSecurityManager(new NoExitSecurityManager()); // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { // Invoke the Composite native import command. ImportCommand.startCommand(null, null, args); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } } catch (NoExitSecurityExceptionStatusNonZero nesesnz) { String error = identifier + ":: Exited with exception from System.exit(): " + command + "(null, null, " + maskedargsList + ")"; logger.error(error); throw new CompositeException(error); } catch (NoExitSecurityExceptionStatusZero nesezero) { if (logger.isDebugEnabled()) { logger.debug(identifier + ":: Exited successfully from System.exit(): " + command + "(null, null, " + maskedargsList + ")"); } } finally { System.setSecurityManager(sm); System.setOut(originalOut); System.setErr(originalErr); } } catch (Exception e) { if (resolveExecCommandLineError(prefix, e.getMessage().toString(), vcsIgnoreMessages)) { ApplicationException applicationException = new ApplicationException( "ImportCommand execution returned an error=" + e.getMessage().toString()); if (logger.isErrorEnabled()) { logger.error(applicationException); } throw applicationException; } } }
From source file:science.atlarge.graphalytics.reference.ReferencePlatform.java
private static void startBenchmarkLogging(Path fileName) { sysOut = System.out;/* w w w . j a v a2s . co m*/ sysErr = System.err; try { File file = null; file = fileName.toFile(); file.getParentFile().mkdirs(); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); TeeOutputStream bothStream = new TeeOutputStream(System.out, fos); PrintStream ps = new PrintStream(bothStream); System.setOut(ps); System.setErr(ps); } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("cannot redirect to output file"); } }
From source file:com.net2plan.gui.GUINet2Plan.java
/** * <p>Main method</p>/*from w ww .j av a 2 s . c o m*/ * * @param args Command-line parameters (unused) * @since 0.2.0 */ public static void main(String[] args) { SystemUtils.configureEnvironment(GUINet2Plan.class, UserInterface.GUI); /* Add default canvas systems */ PluginSystem.addPlugin(ITopologyCanvas.class, JUNGCanvas.class); PrintStream stdout = System.out; PrintStream stderr = System.err; try { PrintStream out = new PrintStream(ErrorHandling.STREAM, true, StandardCharsets.UTF_8.name()); System.setOut(out); System.setErr(out); getInstance().start(); } catch (Throwable ex) { System.setOut(stdout); System.setErr(stderr); System.out.println("Error loading the graphic environment. Please, try the command line interface."); if (!(ex instanceof Net2PlanException) || ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(ex); if (ex instanceof Net2PlanException) System.out.println(ex.getMessage()); } }
From source file:de.thischwa.pmcms.tool.InternalAntTool.java
/** * Initializes an ant project. The base directory is the current working directory. * /*from w w w.j a v a2s. co m*/ * @return Ant project. */ private static Project buildProject() { Project project = new Project(); project.setBasedir(System.getProperty("user.dir")); project.init(); DefaultLogger logger = new DefaultLogger(); project.addBuildListener(logger); logger.setOutputPrintStream(System.out); logger.setErrorPrintStream(System.err); logger.setMessageOutputLevel(Project.MSG_VERBOSE); System.setOut(new PrintStream(new DemuxOutputStream(project, false))); System.setErr(new PrintStream(new DemuxOutputStream(project, true))); project.fireBuildStarted(); return project; }
From source file:org.apache.hadoop.hdfs.server.namenode.TestClusterId.java
/** * Test namenode format with -format -clusterid options. Format should fail * was no clusterid was sent.//from w w w.ja v a 2 s . c om * * @throws IOException */ @Test(timeout = 300000) public void testFormatWithNoClusterIdOption() 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:flow.visibility.pcap.FlowProcess.java
/** function to create internal frame contain flow sequence */ public static JInternalFrame FlowSequence() { final StringBuilder errbuf = new StringBuilder(); // For any error msgs final String file = "tmp-capture-file.pcap"; //System.out.printf("Opening file for reading: %s%n", file); /*************************************************************************** * Second we open up the selected file using openOffline call **************************************************************************/ Pcap pcap = Pcap.openOffline(file, errbuf); if (pcap == null) { System.err.printf("Error while opening device for capture: " + errbuf.toString()); }/*from w w w .j a v a2s .c o m*/ /** create blank internal frame */ JInternalFrame FlowSequence = new JInternalFrame("Flow Sequence", true, true, true, true); FlowSequence.setBounds(601, 0, 600, 660); JTextArea textArea3 = new JTextArea(50, 10); PrintStream printStream3 = new PrintStream(new CustomOutputStream(textArea3)); System.setOut(printStream3); System.setErr(printStream3); JScrollPane scrollPane3 = new JScrollPane(textArea3); FlowSequence.add(scrollPane3); /** Process to print the packet one by one */ JPacketHandler<String> jpacketHandler = new JPacketHandler<String>() { public void nextPacket(JPacket packet, String user) { final JCaptureHeader header = packet.getCaptureHeader(); Timestamp timestamp = new Timestamp(header.timestampInMillis()); Tcp tcp = new Tcp(); Udp udp = new Udp(); Icmp icmp = new Icmp(); Ip4 ip4 = new Ip4(); Ethernet ethernet = new Ethernet(); /** For IP Packet */ if (packet.hasHeader(ip4)) { if (packet.hasHeader(tcp)) { System.out.println(timestamp.toString() + " : [TCP] : " + FormatUtils.ip(ip4.source()) + ":" + tcp.source() + "->" + FormatUtils.ip(ip4.destination()) + ":" + tcp.destination()); } if (packet.hasHeader(udp)) { System.out.println(timestamp.toString() + " : [UDP] : " + FormatUtils.ip(ip4.source()) + ":" + udp.source() + "->" + FormatUtils.ip(ip4.destination()) + ":" + udp.destination()); } if (packet.hasHeader(icmp)) { System.out.println(timestamp.toString() + " : [ICMP] : " + FormatUtils.ip(ip4.source()) + "->" + FormatUtils.ip(ip4.destination()) + ":" + icmp.type()); } } /** For Ethernet Packet */ else if (packet.hasHeader(ethernet)) { System.out.println(timestamp.toString() + " : [ETH] : " + FormatUtils.mac(ethernet.source()) + "->" + FormatUtils.mac(ethernet.destination()) + ":" + ethernet.type()); } } }; Pcap pcap4 = Pcap.openOffline(file, errbuf); /** Redirect the Output into Frame Text Area */ FlowSequence.setVisible(true); pcap4.loop(Pcap.LOOP_INFINITE, jpacketHandler, null); FlowSequence.revalidate(); pcap4.close(); return FlowSequence; }
From source file:SystemUtils.java
public static void RedirectStdErr(OutputStream outs) throws IOException { System.setErr(new PrintStream(outs, true)); }