public static void main(String[] args) throws Exception { BioServer s = new BioServer(9999); s.start(); System.console().readLine("BioServer running on port 9999. Press enter to exit."); System.exit(0); s.stop(); }
/** * 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 static void main(String[] args) throws ClassNotFoundException, IOException { try { String server_name = args.length == 1 ? args[0] : "localhost"; DatagramSocket echoSocket = null; // == UDP Socket echoSocket = new DatagramSocket(); String message = "pre"; // init-Wert while (!message.equals("quit")) { System.out.println(" *** Contact with " + server_name + " ***"); System.out.println("Press Enter to send your message."); // <EntryPoint> System.out.print("> "); message = System.console().readLine(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(message); out.close(); buffer.close(); DatagramPacket packet = new DatagramPacket( buffer.toByteArray(), buffer.size(), InetAddress.getByName(server_name), udp_port); echoSocket.send(packet); } } catch (UnknownHostException e) { System.err.println("Unknown host"); return; } catch (NoRouteToHostException e) { System.err.println("Unreachable"); return; } catch (ConnectException e) { System.err.println("connect refused"); return; } catch (java.io.IOException e) { System.err.println(e.getMessage()); return; } finally { System.out.println("Bye"); // echoSocket.close(); } } // -- end of main
/** * 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"); } } }