List of usage examples for java.lang System setOut
public static void setOut(PrintStream out)
From source file:org.nuxeo.build.ant.AntClient.java
public void run(File buildFile, List<String> targets) throws BuildException { PrintStream previousErr = System.err; PrintStream previousOut = System.out; InputStream in = System.in; InputStream newIn = null;//from ww w . ja va2 s . c om PrintStream newOut = null; PrintStream newErr = null; try { // Configure IO InputHandler handler = new DefaultInputHandler(); project.setInputHandler(handler); if (allowInput) { project.setDefaultInputStream(System.in); } newIn = new DemuxInputStream(project); System.setIn(newIn); newOut = new PrintStream(new DemuxOutputStream(project, false)); System.setOut(newOut); newErr = new PrintStream(new DemuxOutputStream(project, true)); System.setErr(newErr); if (!buildFile.isAbsolute()) { buildFile = new File(project.getBaseDir(), buildFile.getPath()); } project.setUserProperty("ant.file", buildFile.getPath()); ProjectHelper.configureProject(project, buildFile); project.fireBuildStarted(); if (targets != null) { project.getExecutor().executeTargets(project, targets.toArray(new String[targets.size()])); } else { project.getExecutor().executeTargets(project, new String[] { project.getDefaultTarget() }); } project.fireBuildFinished(null); } catch (BuildException e) { project.fireBuildFinished(e); throw e; } finally { System.setOut(previousOut); System.setErr(previousErr); System.setIn(in); IOUtil.close(newIn); IOUtil.close(newOut); IOUtil.close(newErr); } }
From source file:com.proteus.jsmodify.JSExecutionTracer.java
/** * Initialize the plugin and create folders if needed. * /*from w ww .java2 s . c o m*/ * @param browser * The browser. */ public static void preCrawling(ArrayList<String> htmlPaths, ArrayList<String> jsPaths, ArrayList<String> jsFileNames) { // TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO /* if (jsPaths.size() != jsFileNames.size()) { System.err.println("ERROR: JSEXECUTIONTRACER::PRECRAWLER -> not equal number of js paths and js file names"); // return; } else { StaticAnalyzer staticAnalyzer = new StaticAnalyzer(); for (String htmlPath : htmlPaths) { staticAnalyzer.getCallGraph(htmlPath, ""); } for (int i = 0; i < jsFileNames.size(); i ++) { staticAnalyzer.getCallGraph(jsFileNames.get(i), jsPaths.get(i)); } } */ // TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO try { points = new JSONArray(); Helper.directoryCheck(getOutputFolder()); output = new PrintStream(getOutputFolder() + getFilename()); // Add opening bracket around whole trace PrintStream oldOut = System.out; System.setOut(output); System.out.println("{"); System.setOut(oldOut); } catch (IOException e) { e.printStackTrace(); } }
From source file:flow.visibility.pcap.FlowProcess.java
/** function to create internal frame contain flow summary in text */ public static JInternalFrame FlowSummary() { 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 ww .ja va 2s . c om*/ /** create blank internal frame */ JInternalFrame FlowSummary = new JInternalFrame("Flow Summary", true, true, true, true); FlowSummary.setBounds(0, 331, 600, 329); JTextArea textArea = new JTextArea(50, 10); PrintStream printStream = new PrintStream(new CustomOutputStream(textArea)); System.setOut(printStream); System.setErr(printStream); JScrollPane scrollPane = new JScrollPane(textArea); FlowSummary.add(scrollPane); /** Process the FlowMap */ Pcap pcap2 = Pcap.openOffline(file, errbuf); JFlowMap superFlowMap = new JFlowMap(); pcap2.loop(Pcap.LOOP_INFINITE, superFlowMap, null); /** Redirect the FlowMap Output into the Frame Text Area */ FlowSummary.setVisible(true); System.out.printf("%s%n", superFlowMap); FlowSummary.revalidate(); pcap2.close(); return FlowSummary; }
From source file:org.apache.taverna.scufl2.wfdesc.TestConvertToWfdesc.java
@Test public void stdin() throws Exception { byte[] input = IOUtils.toByteArray(getClass().getResourceAsStream("/" + HELLOWORLD_T2FLOW)); assertTrue(input.length > 0);/*from w ww.j a v a2 s . c o m*/ InputStream in = new ByteArrayInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream outBuf = new PrintStream(out); try { System.setIn(in); System.setOut(outBuf); ConvertToWfdesc.main(new String[] {}); } finally { restoreStd(); } out.flush(); out.close(); String turtle = out.toString("utf-8"); //System.out.println(turtle); assertTrue(turtle.contains("Hello_World")); assertTrue(turtle.contains("processor/hello/out/value")); }
From source file:com.savoirfairelinux.jmeter.openstack.test.AbstractOpenstackSamplerTest.java
@BeforeClass public static void prepare() throws Exception { // load configuration configuration = new Properties(); InputStream inputStream = AbstractOpenstackSamplerTest.class.getClassLoader() .getResourceAsStream("configuration.properties"); if (inputStream != null) configuration.load(inputStream); // load arguments arguments = new Arguments(); Properties argumentsProps = new Properties(); inputStream = AbstractOpenstackSamplerTest.class.getClassLoader() .getResourceAsStream("arguments.properties"); if (inputStream != null) argumentsProps.load(inputStream); for (Object key : argumentsProps.keySet()) arguments.addArgument((String) key, argumentsProps.getProperty((String) key)); // setup JMeter JMeterUtils.loadJMeterProperties(""); // handle user defined global configuration for (Object key : configuration.keySet()) { String keyStr = (String) key; // set JVM properties if (keyStr.startsWith("jvm.")) System.setProperty(keyStr.replaceFirst("^jvm\\.", ""), configuration.getProperty(keyStr)); // set JMeter properties else if (keyStr.startsWith("jmeter.")) JMeterUtils.setProperty(keyStr.replaceFirst("^jmeter\\.", ""), configuration.getProperty(keyStr)); }//from w w w.j av a2 s. co m // disable stdout before the logging is correctly setup CustomStdOut customStdOut = new CustomStdOut(System.out); customStdOut.setEnabled(false); System.setOut(customStdOut); // initialize logging and locale JMeterUtils.initLogging(); JMeterUtils.initLocale(); // workaround to disable Jersey warning java.util.logging.Logger.getLogger("").setLevel(Level.SEVERE); // re-enable stdout customStdOut.setEnabled(true); }
From source file:functionaltests.NodeSourceCommandsFunctTest.java
private void createNodeSourceAndListNodeSources(String nodeSourceName, boolean nodesRecoverableParameter) throws Exception { System.out.println(LOG_HEADER + " Test createns command"); if (nodesRecoverableParameter) { this.typeLine("createns( '" + nodeSourceName + "', " + initialInfrastructureParametersString + ", " + staticPolicyParametersString + ", 'tRuE')"); } else {//from w w w . ja v a2 s . c om this.typeLine("createns( '" + nodeSourceName + "', " + initialInfrastructureParametersString + ", " + staticPolicyParametersString + ")"); } this.runCli(); String out = this.capturedOutput.toString(); System.setOut(this.stdOut); System.out.println(out); assertThat(out).contains("Node source successfully created."); this.checkOccurrencesOfNodeSourceInNodeSourceList(nodeSourceName); this.checkOccurrencesOfNodeSourceInNodesList(nodeSourceName, NUMBER_OF_NODES); }
From source file:edu.vt.middleware.crypt.KeyStoreCliTest.java
/** * @param keyStore Keystore file./*from w w w. j av a2 s. c om*/ * @param storeType Keystore type. Uses default type if null. * @param cert Certificate file. * @param privKey Private key file. * @param keyAlg Key algorithm name. Uses default key type if null. * @param alias Alias of keypair inside keystore. * * @throws Exception On test failure. */ @Test(groups = { "cli", "keystore" }, dataProvider = "keypairdata") public void testImportExportKeyPair(final String keyStore, final String storeType, final String cert, final String privKey, final String keyAlg, final String alias) throws Exception { new File(TEST_OUTPUT_DIR).mkdir(); final PrintStream oldStdOut = System.out; final String keyStorePath = TEST_OUTPUT_DIR + keyStore; final String exportCertPath = TEST_OUTPUT_DIR + keyStore + "." + cert; final String exportKeyPath = TEST_OUTPUT_DIR + keyStore + "." + privKey; final OptionData keyStoreOption = new OptionData("keystore", keyStorePath); final OptionData storeTypeOption = storeType == null ? null : new OptionData("storetype", storeType); final OptionData storePassOption = new OptionData("storepass", "changeit"); final OptionData keyAlgOption = keyAlg == null ? null : new OptionData("keyalg", keyAlg); final OptionData aliasOption = new OptionData("alias", alias); final OptionData[] listOptions = new OptionData[] { new OptionData("list"), keyStoreOption, storeTypeOption, storePassOption, }; final OptionData[] importOptions = new OptionData[] { new OptionData("import"), keyStoreOption, storeTypeOption, storePassOption, new OptionData("cert", KEY_DIR_PATH + cert), new OptionData("key", KEY_DIR_PATH + privKey), keyAlgOption, aliasOption, }; final OptionData[] exportOptions = new OptionData[] { new OptionData("export"), keyStoreOption, storeTypeOption, storePassOption, new OptionData("cert", exportCertPath), new OptionData("key", exportKeyPath), keyAlgOption, aliasOption, }; try { final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStream)); logger.info( "Importing keypair into keystore with command line " + CliHelper.toCommandLine(importOptions)); KeyStoreCli.main(CliHelper.toArgs(importOptions)); AssertJUnit.assertTrue(new File(keyStorePath).exists()); // Verify imported entry is present when we list contents outStream.reset(); KeyStoreCli.main(CliHelper.toArgs(listOptions)); final String output = outStream.toString(); logger.info("Keystore listing output:\n" + output); AssertJUnit.assertTrue(output.indexOf(alias) != -1); outStream.reset(); logger.info( "Exporting keypair from keystore with command line " + CliHelper.toCommandLine(exportOptions)); KeyStoreCli.main(CliHelper.toArgs(exportOptions)); AssertJUnit.assertTrue(new File(exportCertPath).exists()); AssertJUnit.assertTrue(new File(exportKeyPath).exists()); } finally { // Restore STDOUT System.setOut(oldStdOut); } }
From source file:com.jkoolcloud.tnt4j.streams.StreamsAgentTest.java
private void interceptConsole() throws InterruptedException { console = new StringWriter(); final WriterOutputStream writerOutputStream = new WriterOutputStream(console, Utils.UTF8); final PrintStream out = new PrintStream(writerOutputStream); System.setOut(out); Thread.sleep(50);/* w w w . j a v a2 s. c o m*/ }
From source file:org.codelibs.fess.crawler.extractor.impl.TikaExtractor.java
@Override public ExtractData getText(final InputStream inputStream, final Map<String, String> params) { if (inputStream == null) { throw new CrawlerSystemException("The inputstream is null."); }/*from ww w.j a va2s . co m*/ final File tempFile; final boolean isByteStream = inputStream instanceof ByteArrayInputStream; if (isByteStream) { inputStream.mark(0); tempFile = null; } else { try { tempFile = File.createTempFile("tikaExtractor-", ".out"); } catch (final IOException e) { throw new ExtractException("Could not create a temp file.", e); } } try { final PrintStream originalOutStream = System.out; final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStream, true)); final PrintStream originalErrStream = System.err; final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); System.setErr(new PrintStream(errStream, true)); try { final String resourceName = params == null ? null : params.get(TikaMetadataKeys.RESOURCE_NAME_KEY); final String contentType = params == null ? null : params.get(HttpHeaders.CONTENT_TYPE); String contentEncoding = params == null ? null : params.get(HttpHeaders.CONTENT_ENCODING); // password for pdf String pdfPassword = params == null ? null : params.get(ExtractData.PDF_PASSWORD); if (pdfPassword == null && params != null) { pdfPassword = getPdfPassword(params.get(ExtractData.URL), resourceName); } final Metadata metadata = createMetadata(resourceName, contentType, contentEncoding, pdfPassword); final Parser parser = new DetectParser(); final ParseContext parseContext = new ParseContext(); parseContext.set(Parser.class, parser); String content = getContent(writer -> { InputStream in = null; try { if (!isByteStream) { try (OutputStream out = new FileOutputStream(tempFile)) { CopyUtil.copy(inputStream, out); } in = new FileInputStream(tempFile); } else { in = inputStream; } parser.parse(in, new BodyContentHandler(writer), metadata, parseContext); } finally { IOUtils.closeQuietly(in); } }, contentEncoding); if (StringUtil.isBlank(content)) { if (resourceName != null) { if (logger.isDebugEnabled()) { logger.debug("retry without a resource name: {}", resourceName); } final Metadata metadata2 = createMetadata(null, contentType, contentEncoding, pdfPassword); content = getContent(writer -> { InputStream in = null; try { if (isByteStream) { inputStream.reset(); in = inputStream; } else { in = new FileInputStream(tempFile); } parser.parse(in, new BodyContentHandler(writer), metadata2, parseContext); } finally { IOUtils.closeQuietly(in); } }, contentEncoding); } if (StringUtil.isBlank(content) && contentType != null) { if (logger.isDebugEnabled()) { logger.debug("retry without a content type: {}", contentType); } final Metadata metadata3 = createMetadata(null, null, contentEncoding, pdfPassword); content = getContent(writer -> { InputStream in = null; try { if (isByteStream) { inputStream.reset(); in = inputStream; } else { in = new FileInputStream(tempFile); } parser.parse(in, new BodyContentHandler(writer), metadata3, parseContext); } finally { IOUtils.closeQuietly(in); } }, contentEncoding); } if (readAsTextIfFailed && StringUtil.isBlank(content)) { if (logger.isDebugEnabled()) { logger.debug("read the content as a text."); } if (contentEncoding == null) { contentEncoding = Constants.UTF_8; } final String enc = contentEncoding; content = getContent(writer -> { BufferedReader br = null; try { if (isByteStream) { inputStream.reset(); br = new BufferedReader(new InputStreamReader(inputStream, enc)); } else { br = new BufferedReader( new InputStreamReader(new FileInputStream(tempFile), enc)); } String line; while ((line = br.readLine()) != null) { writer.write(line); } } catch (final Exception e) { logger.warn( "Could not read " + (tempFile != null ? tempFile.getAbsolutePath() : "a byte stream"), e); } finally { IOUtils.closeQuietly(br); } }, contentEncoding); } } final ExtractData extractData = new ExtractData(content); final String[] names = metadata.names(); Arrays.sort(names); for (final String name : names) { extractData.putValues(name, metadata.getValues(name)); } if (logger.isDebugEnabled()) { logger.debug("Result: metadata: {}", metadata); } return extractData; } catch (final TikaException e) { if (e.getMessage().indexOf("bomb") >= 0) { throw e; } final Throwable cause = e.getCause(); if (cause instanceof SAXException) { final Extractor xmlExtractor = crawlerContainer.getComponent("xmlExtractor"); if (xmlExtractor != null) { InputStream in = null; try { if (isByteStream) { inputStream.reset(); in = inputStream; } else { in = new FileInputStream(tempFile); } return xmlExtractor.getText(in, params); } finally { IOUtils.closeQuietly(in); } } } throw e; } finally { if (originalOutStream != null) { System.setOut(originalOutStream); } if (originalErrStream != null) { System.setErr(originalErrStream); } try { if (logger.isInfoEnabled()) { final byte[] bs = outStream.toByteArray(); if (bs.length != 0) { logger.info(new String(bs, outputEncoding)); } } if (logger.isWarnEnabled()) { final byte[] bs = errStream.toByteArray(); if (bs.length != 0) { logger.warn(new String(bs, outputEncoding)); } } } catch (final Exception e) { // NOP } } } catch (final Exception e) { throw new ExtractException("Could not extract a content.", e); } finally { if (tempFile != null && !tempFile.delete()) { logger.warn("Failed to delete " + tempFile.getAbsolutePath()); } } }
From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RuleAssetsBeanTest.java
@Test @SneakyThrows/*from w w w. j a v a 2s . c o m*/ public void testNoIdsToSendResponse() { when(producer.sendDataSourceMessage(anyString(), eq(DataSourceQueue.ASSET))).thenReturn("SomeCorrId"); when(consumer.getMessage(anyString(), eq(TextMessage.class))).thenReturn(textMessage); // One way to know what is being written to the System.out while the method executes PrintStream initialSysOut = System.err; System.setOut(new PrintStream(outContent)); faReportMessage = loadTestData(testXmlPathWithoutVesselIDs); List<IdTypeWithFlagState> assetList = ruleAssetsBean.getAssetList(faReportMessage); String stdOutput = outContent.toString(); // assertTrue(stdOutput.contains("No compatibile VesselTransportMeans IDs were found so the call to Assets will be avoided")); // assertTrue(StringUtils.countMatches(stdOutput, "Found not compatibile VesselTransportMeans ID") == 8); System.setOut(initialSysOut); System.out.println(stdOutput); assertTrue(CollectionUtils.isEmpty(assetList)); }