001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions Copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2008 Sun Microsystems, Inc. 015 * Portions Copyright 2015 ForgeRock AS. 016 */ 017 018package org.opends.quicksetup.util; 019 020import java.io.OutputStream; 021import java.io.IOException; 022import java.io.PrintStream; 023 024/** 025 * Tool for suppressing and unsuppressing output to standard 026 * output streams. 027 */ 028public class StandardOutputSuppressor { 029 030 private static Token token; 031 032 /** Object to return to this class for unsuppressing output. */ 033 private static class Token { 034 PrintStream out; 035 PrintStream err; 036 } 037 038 /** Suppresses output to the standard output streams. */ 039 public static synchronized void suppress() { 040 if (token == null) { 041 token = new Token(); 042 token.out = System.out; 043 token.err = System.err; 044 System.out.flush(); 045 System.err.flush(); 046 System.setOut(new PrintStream(new NullOutputStream())); 047 System.setErr(new PrintStream(new NullOutputStream())); 048 } else { 049 throw new IllegalStateException("Standard streams currently suppressed"); 050 } 051 } 052 053 /** 054 * Unsuppresses the standard output streams. Following a call to this 055 * method System.out and System.err will point to the descriptor prior 056 * to calling <code>suppress()</code>. 057 */ 058 public static synchronized void unsuppress() { 059 if (token != null) { 060 System.setOut(token.out); 061 System.setErr(token.err); 062 token = null; 063 } else { 064 throw new IllegalStateException( 065 "Standard streams not currently suppressed"); 066 } 067 } 068 069 /** 070 * Checks whether or not this class has suppressed standard out streams. 071 * @return boolean where true indicates output is suppressed 072 */ 073 public static boolean isSuppressed() { 074 return token != null; 075 } 076 077 /** 078 * PrintWriter for suppressing stream. 079 */ 080 private static class NullOutputStream extends OutputStream { 081 082 /** {@inheritDoc} */ 083 public void write(int b) throws IOException { 084 // do nothing; 085 } 086 } 087}