List of usage examples for java.lang System setErr
public static void setErr(PrintStream err)
From source file:net.minecraftforge.fml.relauncher.FMLLaunchHandler.java
private void redirectStdOutputToLog() { FMLLog.log.debug("Injecting tracing printstreams for STDOUT/STDERR."); System.setOut(new TracingPrintStream(LogManager.getLogger("STDOUT"), System.out)); System.setErr(new TracingPrintStream(LogManager.getLogger("STDERR"), System.err)); }
From source file:org.apache.jackrabbit.oak.run.DataStoreCheckTest.java
@After public void tearDown() { System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.err))); }
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()); }/* w ww .j ava2 s . com*/ /** 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.hadoop.yarn.client.cli.TestLogsCLI.java
@Before public void setUp() { sysOutStream = new ByteArrayOutputStream(); sysOut = new PrintStream(sysOutStream); System.setOut(sysOut);//from w ww .j a v a 2 s . c o m sysErrStream = new ByteArrayOutputStream(); sysErr = new PrintStream(sysErrStream); System.setErr(sysErr); }
From source file:org.seasar.robot.extractor.impl.TikaExtractor.java
@Override public ExtractData getText(final InputStream inputStream, final Map<String, String> params) { if (inputStream == null) { throw new RobotSystemException("The inputstream is null."); }//from ww w .j a v a 2 s.c o m File tempFile = null; try { tempFile = File.createTempFile("tikaExtractor-", ".out"); } catch (final IOException e) { throw new ExtractException("Could not create a temp file.", e); } try { OutputStream out = null; try { out = new FileOutputStream(tempFile); StreamUtil.drain(inputStream, out); } finally { IOUtils.closeQuietly(out); } InputStream in = new FileInputStream(tempFile); 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); final StringWriter writer = new StringWriter(initialBufferSize); parser.parse(in, new BodyContentHandler(writer), metadata, parseContext); String content = normalizeContent(writer); if (StringUtil.isBlank(content)) { if (resourceName != null) { IOUtils.closeQuietly(in); if (logger.isDebugEnabled()) { logger.debug("retry without a resource name: {}", resourceName); } in = new FileInputStream(tempFile); final Metadata metadata2 = createMetadata(null, contentType, contentEncoding, pdfPassword); final StringWriter writer2 = new StringWriter(initialBufferSize); parser.parse(in, new BodyContentHandler(writer2), metadata2, parseContext); content = normalizeContent(writer2); } if (StringUtil.isBlank(content) && contentType != null) { IOUtils.closeQuietly(in); if (logger.isDebugEnabled()) { logger.debug("retry without a content type: {}", contentType); } in = new FileInputStream(tempFile); final Metadata metadata3 = createMetadata(null, null, contentEncoding, pdfPassword); final StringWriter writer3 = new StringWriter(initialBufferSize); parser.parse(in, new BodyContentHandler(writer3), metadata3, parseContext); content = normalizeContent(writer3); } if (readAsTextIfFailed && StringUtil.isBlank(content)) { IOUtils.closeQuietly(in); if (logger.isDebugEnabled()) { logger.debug("read the content as a text."); } if (contentEncoding == null) { contentEncoding = Constants.UTF_8; } BufferedReader br = null; try { br = new BufferedReader( new InputStreamReader(new FileInputStream(tempFile), contentEncoding)); final StringWriter writer4 = new StringWriter(initialBufferSize); String line; while ((line = br.readLine()) != null) { writer4.write(line.replaceAll("\\p{Cntrl}", " ").replaceAll("\\s+", " ").trim()); writer4.write(' '); } content = writer4.toString().trim(); } catch (final Exception e) { logger.warn("Could not read " + tempFile.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(br); } } } 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 = SingletonS2Container.getComponent("xmlExtractor"); if (xmlExtractor != null) { IOUtils.closeQuietly(in); in = new FileInputStream(tempFile); return xmlExtractor.getText(in, params); } } throw e; } finally { IOUtils.closeQuietly(in); 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: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 www . j av a 2s . c o m*/ 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:org.apache.avalon.framework.logger.test.CommonsLoggerTestCase.java
/** * Test creation of a child logger. Nees <tt>simplelog.properties</tt> as resource. *///from ww w. j a va 2 s. c o m public void testChildLogger() { final Properties systemProperties = System.getProperties(); final PrintStream err = System.err; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(buffer, true); System.setProperty(Log.class.getName(), SimpleLog.class.getName()); LogFactory.releaseAll(); System.setErr(stream); final Logger logger = new CommonsLogger(LogFactory.getLog("JUnit"), "JUnit"); final Logger child = logger.getChildLogger("test"); child.fatalError("foo"); assertEquals("[FATAL] JUnit.test - foo", buffer.toString().trim()); } finally { System.setProperties(systemProperties); System.setErr(err); } }
From source file:webx.studio.projectcreation.ui.ProjectCreationWizard.java
@Override public boolean performFinish() { if (_DEBUG)/*from ww w .j a va 2 s. c o m*/ time = System.currentTimeMillis(); final NameRule nameRule = new NameRule(projectInfomationWizardPage.getProjectGroupId(), projectInfomationWizardPage.getProjectName()); final Model parentModel = projectInfomationWizardPage.getModel(nameRule); projectStructureWizardPage.updateModel(parentModel, nameRule); final IPath location = Path.fromOSString(projectInfomationWizardPage.getPathValue()); final JejuProject webxProject = new JejuProject(nameRule.getProjectName()); webxProject.setWebxVersion(projectInfomationWizardPage.getWebxVersion()); final WebxStructureModel webxStructureModel = projectStructureWizardPage.getWebxStructureModel(); final String settingFilePath = projectInfomationWizardPage.getSeetingFilePath(); final String antxPropertiesPath = projectInfomationWizardPage.getAntxPropertiesPath(); final String autoconfigCharset = projectInfomationWizardPage.getAutoconfigCharset(); webxProject.setSettingFile(StringUtils.trimToEmpty(settingFilePath)); webxProject.setAntxPropertiesFile(StringUtils.trimToEmpty(antxPropertiesPath)); webxProject.setAutoconfigCharset(StringUtils.trimToEmpty(autoconfigCharset)); webxProject.setWebRoot(getWebRoot(location, nameRule)); WorkspaceModifyOperation op = new WorkspaceModifyOperation() { protected void execute(IProgressMonitor monitor) throws CoreException { IOConsole mc = getIOConsole(); IOConsoleOutputStream consoleStream = mc.newOutputStream(); System.setIn(mc.getInputStream()); System.setErr(new PrintStream(consoleStream)); System.setOut(new PrintStream(consoleStream)); try { if (_DEBUG) { time = System.currentTimeMillis(); } monitor.beginTask("Create a Jeju project[ " + nameRule.getProjectName() + " ]", 20); List<IProject> projects = ProjectHelper.createProject(location, parentModel, webxStructureModel, nameRule, new SubProgressMonitor(monitor, 10)); if (_DEBUG) { System.out.println("Creating eclipse project costs " + (System.currentTimeMillis() - time) / 1000 + " second."); time = System.currentTimeMillis(); } if (JavaCore.getClasspathVariable(ProjectCreationConstants.M2_REPO_KEY) == null) { JavaCore.setClasspathVariable(ProjectCreationConstants.M2_REPO_KEY, new Path(MavenHelper.getLocalRepository())); } File parentPomFile = new File(location.toFile(), nameRule.getProjectName() + "/pom.xml"); MavenHelper.generateEclipse(parentPomFile.getParent(), settingFilePath, new SubProgressMonitor(monitor, 10)); if (_DEBUG) System.out.println("Running maven command costs " + (System.currentTimeMillis() - time) / 1000 + " second."); for (IProject project : projects) { webxProject.getProjectNames().add(project.getName()); } Job job = new Job("Save Metadata") { protected IStatus run(IProgressMonitor monitor) { JejuProjectCore.addWebXProject(webxProject); return Status.OK_STATUS; } }; job.schedule(); } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, ProjectCreationPlugin.PLUGIN_ID, -1, e.getMessage(), e)); } finally { System.setIn(System.in); System.setErr(System.err); System.setOut(System.out); try { // mc.getInputStream().close(); consoleStream.close(); } catch (Exception e) { ProjectCreationPlugin.logThrowable(e); } } } }; try { getContainer().run(true, true, op); UIUtil.refreshPackageExplorer(); } catch (InterruptedException e) { return false; } catch (InvocationTargetException e) { e.printStackTrace(); Throwable t = e.getTargetException(); if (t instanceof CoreException) { CoreException ce = (CoreException) t; Throwable tmpt = ce.getStatus().getException(); String errMessage = null; if (tmpt instanceof MavenExecuteException) { errMessage = "Maven command execute failed!"; } ErrorDialog.openError(getShell(), NLS.bind("Failed to create project \"{0}\"", nameRule.getProjectName()), errMessage, ((CoreException) t).getStatus()); } else { MessageDialog.openError(getShell(), "Creation Problems", NLS.bind("Internal error: {0}", t.getMessage())); } ProjectCreationPlugin.logThrowable(t); return false; } return true; }
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 v a2 s . c o 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:org.apache.jasper.compiler.JspRuntimeContext.java
/** * Create a JspRuntimeContext for a web application context. * * Loads in any previously generated dependencies from file. * * @param ServletContext for web application *//*from w w w . j a v a2 s . c o m*/ public JspRuntimeContext(ServletContext context, Options options) { System.setErr(new SystemLogHandler(System.err)); this.context = context; this.options = options; // Get the parent class loader parentClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); if (parentClassLoader == null) { parentClassLoader = (URLClassLoader) this.getClass().getClassLoader(); } if (log.isDebugEnabled()) { if (parentClassLoader != null) { log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", parentClassLoader.toString())); } else { log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>")); } } initClassPath(); if (context instanceof org.apache.jasper.servlet.JspCServletContext) { return; } if (System.getSecurityManager() != null) { initSecurity(); } // If this web application context is running from a // directory, start the background compilation thread String appBase = context.getRealPath("/"); if (!options.getDevelopment() && appBase != null && options.getReloading()) { if (appBase.endsWith(File.separator)) { appBase = appBase.substring(0, appBase.length() - 1); } String directory = appBase.substring(appBase.lastIndexOf(File.separator)); threadName = threadName + "[" + directory + "]"; threadStart(); } }