public static void main(String[] args) { // enter version numbers System.out.println("Enter version 1:"); float ver1 = Float.parseFloat(System.console().readLine()); System.out.println("Enter version 2:"); float ver2 = Float.parseFloat(System.console().readLine()); int result = compareVersions(ver1, ver2); System.out.println("The results is :" + result); }
/** * Returns a password from standard input. * * @return password */ public static String password() { // use standard input if no console if defined (such as in Eclipse) if (NOCONSOLE) return input(); // hide password final char[] pw = System.console().readPassword(); return pw != null ? new String(pw) : ""; }
public void Cloner(String f1, String f2) { File file1 = new File(f1); File file2 = new File(f2); if (file2.exists()) { System.out.println( "That file already exists are you sure you want to continue, hit n to return and any other key to contine"); String str = System.console().readLine(); if (str == "n") { return; } } BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new FileReader(file1)); out = new PrintWriter(file2); String line; while ((line = in.readLine()) != null) { out.append(line + '\n'); } } catch (FileNotFoundException ex) { System.out.println("the file does not exist"); ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { System.out.println("okay thats been copied for you"); closeReader(in); out.close(); } }
public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
private void readDataConsole() { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String login = c.readLine("Enter your login: "); }
/** * Initialize software token * * @throws Exception if an error occurs */ @Command(description = "Initialize software token") public void initSoftwareToken() throws Exception { char[] pin = System.console().readPassword("PIN: "); char[] pin2 = System.console().readPassword("retype PIN: "); if (!Arrays.equals(pin, pin2)) { System.out.println("ERROR: PINs do not match"); return; } try { SignerClient.execute(new InitSoftwareToken(pin)); AuditLogger.log(INITIALIZE_THE_SOFTWARE_TOKEN_EVENT, XROAD_USER, null); } catch (Exception e) { AuditLogger.log(INITIALIZE_THE_SOFTWARE_TOKEN_EVENT, XROAD_USER, e.getMessage(), null); throw e; } }
/** * This Sample PrivilegedAction performs the following operations: * * <ul> * <li>Access the System property, <i>java.home</i> * <li>Access the System property, <i>user.home</i> * <li>Access the file, <i>foo.txt</i> * </ul> * * @return <code>null</code> in all cases. * @exception SecurityException if the caller does not have permission to perform the operations * listed above. */ public Object run() { Subject currentSubject = Subject.getSubject(AccessController.getContext()); Iterator iter = currentSubject.getPrincipals().iterator(); String dir = ""; Principal p = null; while (iter.hasNext()) { p = (Principal) iter.next(); dir = dir + p.getName() + " "; } if ((p.getName()).equals("Admin")) { String choice; while (!(choice = System.console().readLine("choice : ")).equals("exit")) { if (choice.equals("add")) { String directory = System.console().readLine("directory : "); String filename = System.console().readLine("name : "); String content = System.console().readLine("content : "); try { BufferedWriter bw = new BufferedWriter( new FileWriter("sample/db/" + directory + "/" + filename + ".txt")); bw.write(content); bw.close(); System.out.println(filename + ".txt generated."); } catch (Exception e) { System.out.println(e.toString()); continue; } } else if (choice.equals("rm")) { try { String filename = System.console().readLine("name : "); File f = new File(searchMovie(dir, filename)); if (f.exists()) { f.delete(); System.out.println(filename + ".txt deleted."); } } catch (Exception e) { System.out.println(e.toString()); continue; } } else if (choice.equals("read")) { String filename = System.console().readLine("Movie to watch : "); promptUser(dir, filename, p); } else { System.out.println("Invalid selection ( add, rm, read, exit )"); } } } else { String filename; while (!(filename = System.console().readLine("Movie to watch : ")).equals("exit")) { promptUser(dir, filename, p); } } return null; }
public class JChatComm { JChatSession session; Com com; Console console = System.console(); public JChatComm(String hostName, JChatSession csession) { if (hostName.equals("0")) com = new JServer(); else com = new JClient(hostName); session = csession; } public void sendMessage() throws Exception { String userInput; userInput = console.readLine(); JPacket packet = new JPacket(userInput); com.sendMessage(packet); if (userInput.equals("End Chat")) { endChat(); System.out.println("Chat Over"); } else logMessage(packet, "You"); } private void logMessage(JPacket packet, String sender) { session.addMsg(packet, sender); } public void readMessage() { JPacket packet = com.receiveMessage(); if (packet.jmsg.msg.equals("End Chat")) { endChat(); System.out.println("Chat Over"); } else { logMessage(packet, "OtherGuy"); System.out.println("OtherGuy: " + packet.jmsg.msg); } } public void endChat() { com.closeConnection(); System.out.println("\nLog"); System.out.println("-----------------------------------------------"); session.printLog(); System.exit(1); } }
/** * Log in token. * * @param tokenId token id * @throws Exception if an error occurs */ @Command(description = "Log in token", abbrev = "li") public void loginToken(@Param(name = "tokenId", description = "Token ID") String tokenId) throws Exception { char[] pin = System.console().readPassword("PIN: "); Map<String, Object> logData = new LinkedHashMap<>(); logData.put(TOKEN_ID_PARAM, tokenId); try { PasswordStore.storePassword(tokenId, pin); SignerClient.execute(new ActivateToken(tokenId, true)); AuditLogger.log(LOG_INTO_THE_TOKEN, XROAD_USER, logData); } catch (Exception e) { AuditLogger.log(LOG_INTO_THE_TOKEN, XROAD_USER, e.getMessage(), logData); throw e; } }
public static void main(String[] args) { Set<Character> hole1 = new HashSet<Character>(); Set<Character> hole2 = new HashSet<Character>(); hole1.add('A'); hole1.add('D'); hole1.add('O'); hole1.add('P'); hole1.add('R'); hole1.add('Q'); hole2.add('B'); Console c = System.console(); int n = Integer.parseInt(c.readLine()); for (int i = 0; i < n; i++) { int count = 0; String s = c.readLine(); for (int j = 0; j < s.length(); j++) { if (hole1.contains(s.charAt(j))) count++; else if (hole2.contains(s.charAt(j))) count += 2; } System.out.println(count + ""); } }
private void initiateQuery() { Console console = System.console(); String input = console.readLine("Please enter search term: "); while (input.isEmpty()) { input = console.readLine("Please enter a valid search term: "); } String precision = console.readLine("Please enter desired precision(between 0 and 1): "); while (precision.isEmpty() || !isPrecisionValid(precision)) { precision = console.readLine("Please enter a valid precision(between 0 and 1): "); } boolean complete = false; while (!complete) { try { String bingResults = searchBing(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } SearchResult[] searchResults = parseTenSearchResults(bingResults); int numOfRelevant = 0; for (SearchResult result : searchResults) { boolean relevant = isResultRelevant(result); if (relevant) { numOfRelevant++; } } if (numOfRelevant < (Double.parseDouble(precision) * 10)) { String[] additionalTerms = extractNewTerms(searchResults); } else { complete = true; } } }
/** * builds a StressTester object using the command line arguments * * @param args * @return * @throws Exception */ public static OStressTester getStressTester(String[] args) throws Exception { final Map<String, String> options = checkOptions(readOptions(args)); final OStressTesterSettings settings = new OStressTesterSettings(); settings.dbName = TEMP_DATABASE_NAME + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); settings.mode = OStressTester.OMode.valueOf(options.get(OPTION_MODE).toUpperCase()); settings.rootPassword = options.get(OPTION_ROOT_PASSWORD); settings.resultOutputFile = options.get(OPTION_OUTPUT_FILE); settings.plocalPath = options.get(OPTION_PLOCAL_PATH); settings.operationsPerTransaction = getNumber(options.get(OPTION_TRANSACTIONS), "transactions"); settings.concurrencyLevel = getNumber(options.get(OPTION_CONCURRENCY), "concurrency"); settings.remoteIp = options.get(OPTION_REMOTE_IP); settings.haMetrics = options.get(OPTION_HA_METRICS) != null ? Boolean.parseBoolean(options.get(OPTION_HA_METRICS)) : false; settings.workloadCfg = options.get(OPTION_WORKLOAD); settings.keepDatabaseAfterTest = options.get(OPTION_KEEP_DATABASE_AFTER_TEST) != null ? Boolean.parseBoolean(options.get(OPTION_KEEP_DATABASE_AFTER_TEST)) : false; settings.remotePort = 2424; settings.checkDatabase = Boolean.parseBoolean(options.get(OPTION_CHECK_DATABASE)); if (settings.plocalPath != null) { if (settings.plocalPath.endsWith(File.separator)) { settings.plocalPath = settings.plocalPath.substring( 0, settings.plocalPath.length() - File.separator.length()); } File plocalFile = new File(settings.plocalPath); if (!plocalFile.exists()) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_NOT_EXISTING_PLOCAL_PATH, settings.plocalPath)); } if (!plocalFile.canWrite()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NO_WRITE_PERMISSION_PLOCAL_PATH, settings.plocalPath)); } if (!plocalFile.isDirectory()) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_PLOCAL_PATH_IS_NOT_DIRECTORY, settings.plocalPath)); } } if (settings.resultOutputFile != null) { File outputFile = new File(settings.resultOutputFile); if (outputFile.exists()) { outputFile.delete(); } File parentFile = outputFile.getParentFile(); // if the filename does not contain a path (both relative and absolute) if (parentFile == null) { parentFile = new File("."); } if (!parentFile.exists()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NOT_EXISTING_OUTPUT_DIRECTORY, parentFile.getAbsoluteFile())); } if (!parentFile.canWrite()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NO_WRITE_PERMISSION_OUTPUT_FILE, parentFile.getAbsoluteFile())); } } if (options.get(OPTION_REMOTE_PORT) != null) { settings.remotePort = getNumber(options.get(OPTION_REMOTE_PORT), "remotePort"); if (settings.remotePort > 65535) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_INVALID_REMOTE_PORT_NUMBER, settings.remotePort)); } } if (settings.mode == OStressTester.OMode.DISTRIBUTED) { throw new IllegalArgumentException( String.format("OMode [%s] not yet supported.", settings.mode)); } if (settings.mode == OStressTester.OMode.REMOTE && settings.remoteIp == null) { throw new IllegalArgumentException(COMMAND_LINE_PARSER_MISSING_REMOTE_IP); } if (settings.rootPassword == null && settings.mode == OStressTester.OMode.REMOTE) { Console console = System.console(); if (console != null) { settings.rootPassword = String.valueOf( console.readPassword( String.format( CONSOLE_REMOTE_PASSWORD_PROMPT, settings.remoteIp, settings.remotePort))); } else { throw new Exception(ERROR_OPENING_CONSOLE); } } final List<OWorkload> workloads = parseWorkloads(settings.workloadCfg); final ODatabaseIdentifier databaseIdentifier = new ODatabaseIdentifier(settings); return new OStressTester(workloads, databaseIdentifier, settings); }
public static void mainCore(String[] args, Main main) throws IOException { LocalizedInput in = null; InputStream in1 = null; Main me; String file; String inputResourceName; boolean gotProp; Properties connAttributeDefaults = null; LocalizedResource langUtil = LocalizedResource.getInstance(); LocalizedOutput out = langUtil.getNewOutput(System.out); // Validate arguments, check for --help. if (util.invalidArgs(args)) { util.Usage(out); return; } // load the property file if specified gotProp = util.getPropertyArg(args); // get the default connection attributes connAttributeDefaults = util.getConnAttributeArg(args); // readjust output to gemfirexd.ui.locale and gemfirexd.ui.codeset if // they were loaded from a property file. langUtil.init(); out = langUtil.getNewOutput(System.out); main.initAppUI(); file = util.getFileArg(args); inputResourceName = util.getInputResourceNameArg(args); if (inputResourceName != null) { in = langUtil.getNewInput(util.getResourceAsStream(inputResourceName)); if (in == null) { out.println(langUtil.getTextMessage("IJ_IjErroResoNo", inputResourceName)); return; } } else if (file == null) { in = langUtil.getNewInput(System.in); out.flush(); } else { try { in1 = new FileInputStream(file); if (in1 != null) { in1 = new BufferedInputStream(in1, utilMain.BUFFEREDFILESIZE); in = langUtil.getNewInput(in1); } } catch (FileNotFoundException e) { if (Boolean.getBoolean("ij.searchClassPath")) { in = langUtil.getNewInput(util.getResourceAsStream(file)); } if (in == null) { out.println(langUtil.getTextMessage("IJ_IjErroFileNo", file)); return; } } } final String outFile = util.getSystemProperty("ij.outfile"); if (outFile != null && outFile.length() > 0) { LocalizedOutput oldOut = out; FileOutputStream fos = (FileOutputStream) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { FileOutputStream out = null; try { out = new FileOutputStream(outFile); } catch (FileNotFoundException e) { out = null; } return out; } }); out = langUtil.getNewOutput(fos); if (out == null) oldOut.println(langUtil.getTextMessage("IJ_IjErroUnabTo", outFile)); } // the old property name is deprecated... String maxDisplayWidth = util.getSystemProperty("maximumDisplayWidth"); if (maxDisplayWidth == null) maxDisplayWidth = util.getSystemProperty("ij.maximumDisplayWidth"); if (maxDisplayWidth != null && maxDisplayWidth.length() > 0) { try { int maxWidth = Integer.parseInt(maxDisplayWidth); JDBCDisplayUtil.setMaxDisplayWidth(maxWidth); } catch (NumberFormatException nfe) { out.println(langUtil.getTextMessage("IJ_IjErroMaxiVa", maxDisplayWidth)); } } /* Use the main parameter to get to * a new Main that we can use. * (We can't do the work in Main(out) * until after we do all of the work above * us in this method. */ me = main.getMain(out); // GemStone changes BEGIN if (in != null && in.isStandardInput() && System.console() != null && !"scala.tools.jline.UnsupportedTerminal".equals(System.getProperty("jline.terminal"))) { // use jline for reading input final String encode; if ((encode = in.getEncoding()) != null) { System.setProperty("input.encoding", encode); System.setProperty("jline.WindowsTerminal.input.encoding", encode); } final String historyFileName = System.getProperty("gfxd.history", ".gfxd.history"); // setup the input stream final ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); File histFile = new File(historyFileName); if (historyFileName.length() > 0) { final FileHistory hist; if (histFile.isAbsolute()) { hist = new FileHistory(new File(historyFileName)); } else { hist = new FileHistory(new File((System.getProperty("user.home")), historyFileName)); } reader.setHistory(hist); } // simple string completion for builtin ij commands reader.addCompleter( new StringsCompleter( new String[] { "PROTOCOL", "protocol", "DRIVER", "driver", "CONNECT CLIENT", "connect client", "CONNECT PEER", "connect peer", "SET CONNECTION", "set connection", "SHOW CONNECTIONS", "show connections", "AUTOCOMMIT ON;", "AUTOCOMMIT OFF;", "autocommit on;", "autocommit off;", "DISCONNECT", "DISCONNECT CURRENT;", "DISCONNECT ALL;", "disconnect", "disconnect current;", "disconnect all;", "SHOW SCHEMAS;", "show schemas;", "SHOW TABLES IN", "show tables in", "SHOW VIEWS IN", "show views in", "SHOW PROCEDURES IN", "show procedures in", "SHOW SYNONYMS IN", "show synonyms in", "SHOW INDEXES IN", "SHOW INDEXES FROM", "show indexes in", "show indexes from", "SHOW IMPORTEDKEYS IN", "SHOW IMPORTEDKEYS FROM", "show importedkeys in", "show importedkeys from", "SHOW MEMBERS", "show members", "DESCRIBE", "describe", "COMMIT;", "commit;", "ROLLBACK;", "rollback;", "PREPARE", "prepare", "EXECUTE", "execute", "REMOVE", "remove", "RUN", "run", "ELAPSEDTIME ON;", "ELAPSEDTIME OFF;", "elapsedtime on;", "elapsedtime off;", "MAXIMUMDISPLAYWIDTH", "maximumdisplaywidth", "MAXIMUMLINEWIDTH", "maximumlinewidth", "PAGING ON;", "paging on;", "PAGING OFF;", "paging off;", "ASYNC", "async", "WAIT FOR", "wait for", "GET", "GET CURSOR", "GET SCROLL INSENSITIVE CURSOR", "get", "get cursor", "get scroll insensitive cursor", "NEXT", "next", "FIRST", "first", "LAST", "last", "PREVIOUS", "previous", "ABSOLUTE", "absolute", "RELATIVE", "relative", "AFTER LAST", "after last", "BEFORE FIRST", "before first", "CLOSE", "close", "GETCURRENTROWNUMBER", "getcurrentrownumber", "LOCALIZEDDISPLAY ON;", "LOCALIZEDDISPLAY OFF;", "localizeddisplay on;", "localizeddisplay off;", "EXIT;", "exit;", "QUIT;", "quit;", "HELP;", "help;", "EXPLAIN ", "explain ", "EXPLAINMODE ON;", "explainmode on;", "EXPLAINMODE OFF;", "explainmode off;", })); // set the default max display width to terminal width int termWidth; if ((maxDisplayWidth == null || maxDisplayWidth.length() == 0) && (termWidth = reader.getTerminal().getWidth()) > 4) { JDBCDisplayUtil.setMaxLineWidth(termWidth, false); } in.setConsoleReader(reader); } // GemStone changes END /* Let the processing begin! */ me.go(in, out, connAttributeDefaults); in.close(); out.close(); }
public static void main(String[] args) { Vector<Carta> v = new Vector<Carta>(); Vector<Carta> b = new Vector<Carta>(); Map<String, Integer> m = new HashMap<String, Integer>(); int suma = 0; int opcion = 0; int sumaquina = 0; int veces = 3; boolean esGanador = false; m.put("as", 11); m.put("dos", 0); m.put("tres", 10); m.put("cuatro", 0); m.put("seis", 0); m.put("cinco", 0); m.put("sota", 2); m.put("caballo", 3); m.put("rey", 4); m.put("siete", 0); System.out.println( "\n¿Quieres jugar contra DefecaMachine?\nDebes sacar una tirada mayor que la maquina."); System.out.println("\n1-Jugar\t\t2-Salir\n"); System.out.print("Eliga. Su dinero esta en juego. OPCION: "); opcion = Integer.parseInt(System.console().readLine()); if (opcion == 1) { do { System.out.println("\n___Tu Jugada___"); v.addElement(new Carta()); v.addElement(new Carta()); v.addElement(new Carta()); v.addElement(new Carta()); v.addElement(new Carta()); for (Carta c : v) System.out.println(c); for (Carta c : v) suma += m.get(c.getNumero()); System.out.println("\n___Jugada Defecamachine___"); b.addElement(new Carta()); b.addElement(new Carta()); b.addElement(new Carta()); b.addElement(new Carta()); b.addElement(new Carta()); for (Carta k : b) System.out.println(k); for (Carta k : b) sumaquina += m.get(k.getNumero()); System.out.println("______________________________________________________"); System.out.println("Tienes " + suma + " puntos."); System.out.println("Defecamachine ha sacado " + sumaquina + " puntos."); System.out.println("______________________________________________________"); if (suma == sumaquina) { System.out.println("\n\nDESASTROSO EMPATE..."); esGanador = false; veces--; v.removeAll(v); b.removeAll(b); if (veces > 0) { System.out.print("\n1-Seguir.\t\t\t0-Salir. \n"); System.out.print("\t\tOPCION:"); opcion = Integer.parseInt(System.console().readLine()); } if (veces == 0) { System.out.print("Se acabaron las oportunidades."); } } if (suma < sumaquina) { System.out.println("\n\n\nHas perdido contra Defecamachine..."); esGanador = false; veces--; v.removeAll(v); b.removeAll(b); if (veces > 0) { System.out.print("\n1-Seguir.\t\t\t0-Salir. \n"); System.out.print("\t\tOPCION:"); opcion = Integer.parseInt(System.console().readLine()); } if (veces == 0) { System.out.print("Se acabaron las oportunidades."); } } if (suma > sumaquina) { System.out.println("¡¡Ganaste a Defecamachine!!"); esGanador = true; } } while ((!esGanador) && (veces > 0) && (opcion == 1)); } }
/** * This class contains static methods, which are used throughout the project. The methods are used * for dumping error output, debugging information, getting the application path, etc. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public final class Util { /** Flag for using default standard input. */ private static final boolean NOCONSOLE = System.console() == null; /** Hidden constructor. */ private Util() {} /** * Returns an information string for an unexpected exception. * * @param ex exception * @return dummy object */ public static String bug(final Throwable ex) { final TokenBuilder tb = new TokenBuilder(BUGINFO); tb.add(NL).add("Contact: ").add(MAIL); tb.add(NL).add("Version: ").add(TITLE); tb.add(NL).add("Java: ").add(System.getProperty("java.vendor")); tb.add(", ").add(System.getProperty("java.version")); tb.add(NL).add("OS: ").add(System.getProperty("os.name")); tb.add(", ").add(System.getProperty("os.arch")); tb.add(NL).add("Stack Trace: "); for (final String e : toArray(ex)) tb.add(NL).add(e); return tb.toString(); } /** * Throws a runtime exception for an unexpected exception. * * @param ext optional extension * @return runtime exception (indicates that an error is raised) */ public static RuntimeException notexpected(final Object... ext) { final TokenBuilder tb = new TokenBuilder(); tb.addExt("%", ext.length == 0 ? "Not Expected." : ext[0]); throw new RuntimeException(tb.toString()); } /** * Throws a runtime exception for an unimplemented method. * * @param ext optional extension * @return runtime exception (indicates that an error is raised) */ public static RuntimeException notimplemented(final Object... ext) { final TokenBuilder tb = new TokenBuilder("Not Implemented"); if (ext.length != 0) tb.addExt(" (%)", ext); throw new UnsupportedOperationException(tb.add('.').toString()); } /** * Returns the class name of the specified object. * * @param o object * @return class name */ public static String name(final Object o) { return name(o.getClass()); } /** * Returns the name of the specified class. * * @param o object * @return class name */ public static String name(final Class<?> o) { return o.getSimpleName(); } /** * Returns a single line from standard input. * * @return string */ public static String input() { final Scanner sc = new Scanner(System.in); return sc.hasNextLine() ? sc.nextLine().trim() : ""; } /** * Returns a password from standard input. * * @return password */ public static String password() { // use standard input if no console if defined (such as in Eclipse) if (NOCONSOLE) return input(); // hide password final char[] pw = System.console().readPassword(); return pw != null ? new String(pw) : ""; } /** Prints a newline to standard output. */ public static void outln() { out(NL); } /** * Prints a string to standard output, followed by a newline. * * @param str output string * @param ext text optional extensions */ public static void outln(final Object str, final Object... ext) { out((str instanceof byte[] ? Token.string((byte[]) str) : str) + NL, ext); } /** * Prints a string to standard output. * * @param str output string * @param ext text optional extensions */ public static void out(final Object str, final Object... ext) { System.out.print(info(str, ext)); } /** * Prints a string to standard error, followed by a newline. * * @param obj error string * @param ext text optional extensions */ public static void errln(final Object obj, final Object... ext) { err((obj instanceof Throwable ? message((Throwable) obj) : obj) + NL, ext); } /** * Prints a string to standard error. * * @param string debug string * @param ext text optional extensions */ public static void err(final String string, final Object... ext) { System.err.print(info(string, ext)); } /** * Returns a more user-friendly error message for the specified exception. * * @param ex throwable reference * @return error message */ public static String message(final Throwable ex) { debug(ex); if (ex instanceof BindException) return SRV_RUNNING; if (ex instanceof LoginException) return ACCESS_DENIED; if (ex instanceof ConnectException) return CONNECTION_ERROR; if (ex instanceof SocketTimeoutException) return TIMEOUT_EXCEEDED; if (ex instanceof SocketException) return CONNECTION_ERROR; String msg = ex.getMessage(); if (msg == null || msg.isEmpty()) msg = ex.toString(); if (ex instanceof FileNotFoundException) return info(RES_NOT_FOUND_X, msg); if (ex instanceof UnknownHostException) return info(UNKNOWN_HOST_X, msg); return msg; } /** * Prints the exception stack trace if the {@link Prop#debug} flag is set. * * @param ex exception */ public static void debug(final Throwable ex) { if (Prop.debug && ex != null) stack(ex); } /** * Prints a string to standard error if the {@link Prop#debug} flag is set. * * @param str debug string * @param ext text optional extensions */ public static void debug(final Object str, final Object... ext) { if (Prop.debug) errln(str, ext); } /** * Prints performance information if the {@link Prop#debug} flag is set. * * @param perf performance reference */ public static void memory(final Performance perf) { if (!Prop.debug) return; errln(" " + perf + " (" + Performance.getMemory() + ')'); } /** * Returns a string and replaces all % characters by the specified extensions (see {@link * TokenBuilder#addExt} for details). * * @param str string to be extended * @param ext text text extensions * @return extended string */ public static String info(final Object str, final Object... ext) { return Token.string(inf(str, ext)); } /** * Returns a token and replaces all % characters by the specified extensions (see {@link * TokenBuilder#addExt} for details). * * @param str string to be extended * @param ext text text extensions * @return token */ public static byte[] inf(final Object str, final Object... ext) { return new TokenBuilder().addExt(str, ext).finish(); } /** * Prints the current stack trace to System.err. * * @param i number of steps to print */ public static void stack(final int i) { errln("You're here:"); final String[] stack = toArray(new Throwable()); final int l = Math.min(Math.max(2, i + 2), stack.length); for (int s = 2; s < l; ++s) errln(stack[s]); } /** * Prints the stack of the specified error to standard error. * * @param th error/exception instance */ public static void stack(final Throwable th) { for (final String s : toArray(th)) errln(s); } /** * Returns an string array representation of the specified throwable. * * @param th throwable * @return string array */ private static String[] toArray(final Throwable th) { final StackTraceElement[] st = th.getStackTrace(); final String[] obj = new String[st.length + 1]; obj[0] = th.toString(); for (int i = 0; i < st.length; i++) obj[i + 1] = " " + st[i]; return obj; } /** * Starts the specified class in a separate process. * * @param clz class to start * @param args command-line arguments * @return reference to a {@link Process} instance representing the started process */ public static Process start(final Class<?> clz, final String... args) { final String[] largs = { "java", "-Xmx" + Runtime.getRuntime().maxMemory(), "-cp", System.getProperty("java.class.path"), clz.getName(), "-D", }; final StringList sl = new StringList().add(largs).add(args); try { return new ProcessBuilder(sl.toArray()).start(); } catch (final IOException ex) { notexpected(ex); return null; } } /** * Checks if the specified string is "yes", "true" or "on". * * @param string string to be checked * @return result of check */ public static boolean yes(final String string) { return Token.eqic(string, YES, TRUE, ON, INFOON); } /** * Checks if the specified string is "no", "false" or "off". * * @param string string to be checked * @return result of check */ public static boolean no(final String string) { return Token.eqic(string, NO, FALSE, OFF, INFOOFF); } /** * Returns an info message for the specified flag. * * @param flag current flag status * @return ON/OFF message */ public static String flag(final boolean flag) { return flag ? INFOON : INFOOFF; } }
public static void main(String[] args) throws Exception { boolean isInteractive = false; classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString(); isJar = (classUrl.indexOf("jar") == 0); if (!isJar) { System.err.println("Installer can only be run from inside a Myna distribution war file"); System.exit(1); } Thread.sleep(1000); Console console = System.console(); String response = null; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption( "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx); options.addOption("h", "help", false, "Displays help."); options.addOption( "w", "webroot", true, "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot); options.addOption( "l", "logfile", true, "Log file to use. Will be created if it does not exist. Default: ./<context>.log"); options.addOption( "s", "servername", true, "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined"); // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc. // Defaults to DEV" ); options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port); options.addOption( "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0"); options.addOption( "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore"); options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass); options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias); modeOptions.add("upgrade"); modeOptions.add("install"); options.addOption( "m", "mode", true, "Mode: one of " + modeOptions.toString() + ". \n" + "\"upgrade\": Upgrades myna installation in webroot and exits. " + "\"install\": Unpacks to webroot, and installs startup files"); options.addOption( "u", "user", true, "User to own and run the Myna installation. Only applies to unix installs. Default: nobody"); HelpFormatter formatter = new HelpFormatter(); String cmdSyntax = "java -jar myna-X.war -m <mode> [options]"; try { CommandLine line = parser.parse(options, args); Option option; if (args.length == 0) { formatter.printHelp(cmdSyntax, options); response = console.readLine("\nContinue with Interactive Install? (y/N)"); if (response.toLowerCase().equals("y")) { isInteractive = true; } else System.exit(1); } // Help if (line.hasOption("help")) { formatter.printHelp(cmdSyntax, options); System.exit(1); } // mode if (line.hasOption("mode")) { mode = line.getOptionValue("mode"); if (!modeOptions.contains(mode)) { System.err.println( "Invalid Arguments. Reason: Mode must be in " + modeOptions.toString()); formatter.printHelp(cmdSyntax, options); System.exit(1); } } else if (isInteractive) { option = options.getOption("mode"); console.printf("\n" + option.getDescription()); do { response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): "); if (!response.isEmpty()) mode = response; } while (!modeOptions.contains(mode)); } // webroot if (line.hasOption("webroot")) { webroot = line.getOptionValue("webroot"); } else if (isInteractive) { option = options.getOption("webroot"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): "); if (!response.isEmpty()) webroot = response; } // port if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } else if (isInteractive && mode.equals("install")) { option = options.getOption("port"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): "); if (!response.isEmpty()) port = Integer.parseInt(response); } // context if (line.hasOption("context")) { webctx = line.getOptionValue("context"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("context"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): "); if (!response.isEmpty()) webctx = response; } if (!webctx.startsWith("/")) { webctx = "/" + webctx; } // servername (depends on context) if (!webctx.equals("/")) { serverName = webctx.substring(1); } if (line.hasOption("servername")) { serverName = line.getOptionValue("servername"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("servername"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): "); if (!response.isEmpty()) serverName = response; } // user if (line.hasOption("user")) { user = line.getOptionValue("user"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("user"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): "); if (!response.isEmpty()) user = response; } // logfile logFile = "myna.log"; if (!webctx.equals("/")) { logFile = webctx.substring(1) + ".log"; } if (line.hasOption("logfile")) { logFile = line.getOptionValue("logfile"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("logfile"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): "); if (!response.isEmpty()) logFile = response; } // ssl-port if (line.hasOption("ssl-port")) { sslPort = Integer.parseInt(line.getOptionValue("ssl-port")); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ssl-port"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): "); if (!response.isEmpty()) sslPort = Integer.parseInt(response); } // ks-pass if (line.hasOption("ks-pass")) { ksPass = line.getOptionValue("ks-pass"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ks-pass"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): "); if (!response.isEmpty()) ksPass = response; } // ks-alias if (line.hasOption("ks-alias")) { ksAlias = line.getOptionValue("ks-alias"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ks-alias"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): "); if (!response.isEmpty()) ksAlias = response; } // keystore String appBase = new File(webroot).getCanonicalPath(); if (keystore == null) { keystore = appBase + "/WEB-INF/myna/myna_keystore"; } if (line.hasOption("keystore")) { keystore = line.getOptionValue("keystore"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("keystore"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): "); if (!response.isEmpty()) keystore = response; } javaOpts = line.getArgList(); } catch (ParseException exp) { System.err.println("Invalid Arguments. Reason: " + exp.getMessage()); formatter.printHelp(cmdSyntax, options); System.exit(1); } if (isInteractive) { System.out.println("\nProceeed with the following settings?:\n"); System.out.println("mode = " + mode); System.out.println("webroot = " + webroot); if (mode.equals("install")) { System.out.println("port = " + port); System.out.println("context = " + webctx); System.out.println("servername = " + serverName); System.out.println("user = "******"logfile = " + logFile); System.out.println("ssl-port = " + sslPort); System.out.println("ks-pass = "******"ks-alias = " + ksAlias); System.out.println("keystore = " + keystore); } response = console.readLine("Continue? (Y/n)"); if (response.toLowerCase().equals("n")) System.exit(1); } File wrFile = new File(webroot); webroot = wrFile.toString(); if (mode.equals("install")) { adminPassword = console.readLine("\nCreate an Admin password for this installation: "); } // unpack myna if necessary if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) { upgrade(wrFile); } if (mode.equals("install")) { File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties")); FileInputStream propertiesFileIS = new FileInputStream(propertiesFile); Properties generalProperties = new Properties(); generalProperties.load(propertiesFileIS); propertiesFileIS.close(); if (!adminPassword.isEmpty()) { org.jasypt.util.password.StrongPasswordEncryptor cryptTool = new org.jasypt.util.password.StrongPasswordEncryptor(); generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword)); } generalProperties.setProperty("instance_id", serverName); generalProperties.store( new java.io.FileOutputStream(propertiesFile), "Myna General Properties"); String javaHome = System.getProperty("java.home"); webroot = new File(webroot).getCanonicalPath(); if (serverName.length() == 0) serverName = "myna"; if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { if (!new File(logFile).isAbsolute()) { logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString(); } File templateFile = new File( wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd")); String initScript = FileUtils.readFileToString(templateFile) .replaceAll("\\{webctx\\}", webctx) .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName)) .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot)) .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile)) .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome)) .replaceAll("\\{port\\}", new Integer(port).toString()) .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString()) .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore)) .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass)) .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias)); File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd")); FileUtils.writeStringToFile(scriptFile, initScript); // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor(); System.out.println( "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n"); System.out.println( "\nInit script '" + scriptFile + "' created with the following settings:\n"); System.out.println("memory=256MB"); System.out.println("serverName=" + serverName); System.out.println("javaHome=" + javaHome); System.out.println("context=" + webctx); System.out.println("port=" + port); System.out.println("myna_home=" + webroot); System.out.println("logfile=" + logFile); System.out.println("sslPort=" + sslPort); System.out.println("keyStore=" + keystore); System.out.println("ksPass="******"ksAlias=" + ksAlias); System.out.println( "\nEdit and and run the command file in " + scriptFile + " to update this service"); } else { String curUser = java.lang.System.getProperty("user.name"); if (!curUser.equals("root")) { System.out.println("Install mode must be run as root."); System.exit(1); } if (!new File(logFile).isAbsolute()) { logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString(); } File templateFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script")); String initScript = FileUtils.readFileToString(templateFile) .replaceAll("\\{webctx\\}", webctx) .replaceAll("\\{server\\}", serverName) .replaceAll("\\{user\\}", user) .replaceAll("\\{webroot\\}", webroot) .replaceAll("\\{javahome\\}", javaHome) .replaceAll("\\{logfile\\}", logFile) .replaceAll("\\{port\\}", new Integer(port).toString()) .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString()) .replaceAll("\\{keystore\\}", keystore) .replaceAll("\\{ksPass\\}", ksPass) .replaceAll("\\{ksAlias\\}", ksAlias); File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName)); FileUtils.writeStringToFile(scriptFile, initScript); if (new File("/etc/init.d").exists()) { exec("chown -R " + user + " " + webroot); exec("chown root " + scriptFile.toString()); exec("chmod 700 " + scriptFile.toString()); exec("cp " + scriptFile.toString() + " /etc/init.d/"); System.out.println( "\nInit script '/etc/init.d/" + serverName + "' created with the following settings:\n"); } else { System.out.println( "\nInit script '" + scriptFile + "' created with the following settings:\n"); } System.out.println("user="******"memory=256MB"); System.out.println("server=" + serverName); System.out.println("context=" + webctx); System.out.println("port=" + port); System.out.println("myna_home=" + webroot); System.out.println("logfile=" + logFile); System.out.println("sslPort=" + sslPort); System.out.println("keyStore=" + keystore); System.out.println("ksPass="******"ksAlias=" + ksAlias); System.out.println("\nEdit this file to customize startup behavior"); } } }
public class DaemonParameters { static final int DEFAULT_IDLE_TIMEOUT = 3 * 60 * 60 * 1000; public static final List<String> DEFAULT_JVM_ARGS = ImmutableList.of("-Xmx1024m", "-XX:MaxPermSize=256m", "-XX:+HeapDumpOnOutOfMemoryError"); public static final String INTERACTIVE_TOGGLE = "org.gradle.interactive"; private final String uid; private final File gradleUserHomeDir; private File baseDir; private int idleTimeout = DEFAULT_IDLE_TIMEOUT; private final JvmOptions jvmOptions = new JvmOptions(new IdentityFileResolver()); private DaemonUsage daemonUsage = DaemonUsage.IMPLICITLY_DISABLED; private File javaHome; private boolean foreground; private boolean stop; private boolean interactive = System.console() != null || Boolean.getBoolean(INTERACTIVE_TOGGLE); public DaemonParameters(BuildLayoutParameters layout) { this(layout, Collections.<String, String>emptyMap()); } public DaemonParameters(BuildLayoutParameters layout, Map<String, String> extraSystemProperties) { this.uid = UUID.randomUUID().toString(); jvmOptions.setAllJvmArgs(DEFAULT_JVM_ARGS); jvmOptions.systemProperties(extraSystemProperties); baseDir = new File(layout.getGradleUserHomeDir(), "daemon"); gradleUserHomeDir = layout.getGradleUserHomeDir(); } public boolean isInteractive() { return interactive; } public DaemonParameters setEnabled(boolean enabled) { daemonUsage = enabled ? DaemonUsage.EXPLICITLY_ENABLED : DaemonUsage.EXPLICITLY_DISABLED; return this; } public String getUid() { return uid; } public File getBaseDir() { return baseDir; } public File getGradleUserHomeDir() { return gradleUserHomeDir; } public int getIdleTimeout() { return idleTimeout; } public void setIdleTimeout(int idleTimeout) { this.idleTimeout = idleTimeout; } public List<String> getEffectiveJvmArgs() { return jvmOptions.getAllImmutableJvmArgs(); } public List<String> getAllJvmArgs() { return jvmOptions.getAllJvmArgs(); } public File getEffectiveJavaHome() { if (javaHome == null) { return canonicalise(Jvm.current().getJavaHome()); } return javaHome; } public File getEffectiveJavaExecutable() { if (javaHome == null) { return Jvm.current().getJavaExecutable(); } return Jvm.forHome(javaHome).getJavaExecutable(); } public DaemonParameters setInteractive(boolean interactive) { this.interactive = interactive; return this; } public DaemonParameters setJavaHome(File javaHome) { this.javaHome = javaHome; return this; } public Map<String, String> getSystemProperties() { Map<String, String> systemProperties = new HashMap<String, String>(); GUtil.addToMap(systemProperties, jvmOptions.getSystemProperties()); return systemProperties; } public Map<String, String> getEffectiveSystemProperties() { Map<String, String> systemProperties = new HashMap<String, String>(); GUtil.addToMap(systemProperties, jvmOptions.getSystemProperties()); GUtil.addToMap(systemProperties, System.getProperties()); return systemProperties; } public void setJvmArgs(Iterable<String> jvmArgs) { jvmOptions.setAllJvmArgs(jvmArgs); } public void setDebug(boolean debug) { jvmOptions.setDebug(debug); } public DaemonParameters setBaseDir(File baseDir) { this.baseDir = baseDir; return this; } public boolean getDebug() { return jvmOptions.getDebug(); } public DaemonUsage getDaemonUsage() { return daemonUsage; } public boolean isForeground() { return foreground; } public void setForeground(boolean foreground) { this.foreground = foreground; } public boolean isStop() { return stop; } public void setStop(boolean stop) { this.stop = stop; } }