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-2016 ForgeRock AS.
016 */
017
018package org.opends.quicksetup.util;
019
020import java.io.OutputStream;
021import java.io.IOException;
022import java.io.PrintStream;
023
024/** Tool for suppressing and unsuppressing output to standard output streams. */
025public class StandardOutputSuppressor {
026
027  private static Token token;
028
029  /** Object to return to this class for unsuppressing output. */
030  private static class Token {
031    PrintStream out;
032    PrintStream err;
033  }
034
035  /** Suppresses output to the standard output streams. */
036  public static synchronized void suppress() {
037    if (token == null) {
038      token = new Token();
039      token.out = System.out;
040      token.err = System.err;
041      System.out.flush();
042      System.err.flush();
043      System.setOut(new PrintStream(new NullOutputStream()));
044      System.setErr(new PrintStream(new NullOutputStream()));
045    } else {
046      throw new IllegalStateException("Standard streams currently suppressed");
047    }
048  }
049
050  /**
051   * Unsuppresses the standard output streams.  Following a call to this
052   * method System.out and System.err will point to the descriptor prior
053   * to calling <code>suppress()</code>.
054   */
055  public static synchronized void unsuppress() {
056    if (token != null) {
057      System.setOut(token.out);
058      System.setErr(token.err);
059      token = null;
060    } else {
061      throw new IllegalStateException(
062              "Standard streams not currently suppressed");
063    }
064  }
065
066  /**
067   * Checks whether this class has suppressed standard out streams.
068   * @return boolean where true indicates output is suppressed
069   */
070  public static boolean isSuppressed() {
071    return token != null;
072  }
073
074  /** PrintWriter for suppressing stream. */
075  private static class NullOutputStream extends OutputStream {
076
077    @Override
078    public void write(int b) throws IOException {
079      // do nothing;
080    }
081  }
082}