001/* 002 * Syncany, www.syncany.org 003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com> 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU General Public License for more details. 014 * 015 * You should have received a copy of the GNU General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package org.syncany.cli.util; 019 020import java.io.BufferedReader; 021import java.io.Console; 022import java.io.InputStreamReader; 023import java.io.OutputStreamWriter; 024import java.io.PrintWriter; 025 026/** 027 * Wrapper class for {@link Console} to enable mocking for tests. 028 * 029 * @author Pim Otte 030 */ 031public class InitConsole { 032 private static InitConsole instance; 033 034 private Console console; 035 private BufferedReader systemIn; 036 private PrintWriter systemOut; 037 038 private InitConsole() { 039 this.console = System.console(); 040 this.systemIn = null; 041 this.systemOut = null; 042 } 043 044 public static InitConsole getInstance() { 045 if (instance == null) { 046 instance = new InitConsole(); 047 } 048 049 return instance; 050 } 051 052 public static void setInstance(InitConsole initConsole) { 053 instance = initConsole; 054 } 055 056 public String readLine() { 057 try { 058 if (console == null) { 059 return getSystemInReader().readLine(); 060 } 061 else { 062 return console.readLine(); 063 } 064 } 065 catch (Exception e) { 066 throw new RuntimeException(e); 067 } 068 } 069 070 public String readLine(String fmt, Object... args) { 071 if (console == null) { 072 getSystemOutWriter().write(String.format(fmt, args)); 073 return readLine(); 074 } 075 else { 076 return console.readLine(fmt, args); 077 } 078 } 079 080 public char[] readPassword() { 081 if (console == null) { 082 return readLine().toCharArray(); 083 } 084 else { 085 return console.readPassword(); 086 } 087 } 088 089 public char[] readPassword(String fmt, Object... args) { 090 if (console == null) { 091 getSystemOutWriter().write(String.format(fmt, args)); 092 return readLine().toCharArray(); 093 } 094 else { 095 return console.readPassword(fmt, args); 096 } 097 } 098 099 private BufferedReader getSystemInReader() { 100 if (systemIn == null) { 101 systemIn = new BufferedReader(new InputStreamReader(System.in)); 102 } 103 104 return systemIn; 105 } 106 107 private PrintWriter getSystemOutWriter() { 108 if (systemOut == null) { 109 systemOut = new PrintWriter(new OutputStreamWriter(System.out)); 110 } 111 112 return systemOut; 113 } 114}