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