List of usage examples for java.lang String equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
From source file:de.clusteval.serverclient.BackendClient.java
/** * @param args/* www .j av a2s .c om*/ * Command line parameters for the backend client (see * {@link #params}). * @throws IOException */ @SuppressWarnings("unused") public static void main(String[] args) throws IOException { try { CommandLine params = parseParams(args, false); if (params.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("clustevalClient", clientCLIOptions); System.exit(0); } if (params.hasOption("version")) { System.out.println(VERSION); System.exit(0); } initLogging(params); Logger log = LoggerFactory.getLogger(BackendClient.class); System.out.println("Starting clusteval client"); System.out.println(VERSION); System.out.println("========================="); // if command line arguments (except connection parameters) are // passed, we do not start a console Set<String> paramKeys = new HashSet<String>(); @SuppressWarnings("unchecked") Iterator<Option> it = params.iterator(); while (it.hasNext()) { paramKeys.add(it.next().getOpt()); } paramKeys.remove("ip"); paramKeys.remove("port"); paramKeys.remove("clientId"); if (paramKeys.size() > 0) { try { new BackendClient(args); } catch (Exception e) { } } else { String clientId; if (params.hasOption("clientId")) clientId = params.getOptionValue("clientId"); else // parse args because of possible connection parameters clientId = new BackendClient(args).clientId; reader = new ConsoleReader(); List<Completer> completers = new LinkedList<Completer>(); completers.add(new BackendClientCompleter(clientId, args)); String ip = params.hasOption("ip") ? params.getOptionValue("ip") : "localhost"; String port = params.hasOption("port") ? params.getOptionValue("port") : "1099"; setDefaultPromptAndCompleter(ip, port, completers); String line; while ((line = reader.readLine()) != null) { if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { break; } boolean connectException = false; do { try { new BackendClient( ArraysExt.merge(args, ("-clientId " + clientId + " -" + line).split(" "))); connectException = false; } catch (ConnectException e) { e.printStackTrace(); connectException = true; } catch (Exception e) { log.warn(e.getMessage()); } Thread.sleep(1000); } while (connectException); // } } } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("clustevalClient", "Invoking this client without any parameters will open a shell with tab-completion.", clientCLIOptions, "", true); } catch (Throwable t) { // t.printStackTrace(); } }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
public static void main(String[] args) throws Exception { logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName()); Options options = new Options(); options.addOption("unisonXMLFile", true, "The full path to the Unison xml file"); options.addOption("keystorePath", true, "The full path to the Unison keystore"); options.addOption("chainName", true, "The name of the authentication chain"); options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2"); options.addOption("idpName", true, "The name of the identity provider application"); options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file"); options.addOption("createDefault", false, "If set, add default parameters"); options.addOption("action", true, "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey"); options.addOption("urlBase", true, "Base URL, no URI; https://host:port"); options.addOption("alias", true, "Key alias"); options.addOption("newKeystorePath", true, "Path to the new keystore"); options.addOption("newKeystorePassword", true, "Password for the new keystore"); options.addOption("help", false, "Prints this message"); options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key"); options.addOption("dlqName", true, "The name of the dead letter queue"); options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6"); options.addOption("secretkey", true, "base64 encoded secret key"); options.addOption("envFile", true, "Environment variables for parmaterized configs"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, true); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("OpenUnisonUtils", options); }/* w w w . j a v a 2s .c o m*/ logger.info("Loading Unison Configuration"); String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options); TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options); String action = loadOption(cmd, "action", options); TremoloType ttWrite = null; if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) { ttWrite = loadTremoloType(unisonXMLFile); } logger.info("Configuration loaded"); logger.info("Loading the keystore..."); String ksPath = loadOption(cmd, "keystorePath", options); KeyStore ks = loadKeyStore(ksPath, ttRead); logger.info("...loaded"); if (action.equalsIgnoreCase("import-sp-metadata")) { importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-sp-metadata")) { exportSPMetaData(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("print-secretkey")) { printSecreyKey(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("import-secretkey")) { importSecreyKey(options, cmd, ttRead, ks, ksPath); } else if (action.equalsIgnoreCase("create-secretkey")) { Security.addProvider(new BouncyCastleProvider()); logger.info("Creating AES-256 secret key"); String alias = loadOption(cmd, "alias", options); logger.info("Alias : '" + alias + "'"); KeyGenerator kg = KeyGenerator.getInstance("AES", "BC"); kg.init(256, new SecureRandom()); SecretKey sk = kg.generateKey(); ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null); logger.info("Saving key"); ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray()); logger.info("Finished"); } else if (action.equalsIgnoreCase("export-secretkey")) { logger.info("Export Secret Key"); logger.info("Loading key"); String alias = loadOption(cmd, "alias", options); SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray()); logger.info("Loading new keystore path"); String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options); logger.info("Loading new keystore password"); String ksPassword = loadOption(cmd, "newKeystorePassword", options); KeyStore newKS = KeyStore.getInstance("PKCS12"); newKS.load(null, ttRead.getKeyStorePassword().toCharArray()); newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null); newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray()); logger.info("Exported"); } else if (action.equalsIgnoreCase("import-idp-metadata")) { importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-idp-metadata")) { exportIdPMetadata(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("clear-dlq")) { logger.info("Getting the DLQ Name..."); String dlqName = loadOption(cmd, "dlqName", options); QueUtils.emptyDLQ(ttRead, dlqName); } else if (action.equalsIgnoreCase("upgradeFrom106")) { logger.info("Upgrading OpenUnison's configuration from 1.0.6"); String backupFileName = unisonXMLFile + ".bak"; logger.info("Backing up to '" + backupFileName + "'"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile))); PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName)); String line = null; while ((line = in.readLine()) != null) { out.println(line); } out.flush(); out.close(); in.close(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout); FileOutputStream fsout = new FileOutputStream(unisonXMLFile); fsout.write(bout.toByteArray()); fsout.flush(); fsout.close(); } }
From source file:net.yacy.yacy.java
/** * Main-method which is started by java. Checks for special arguments or * starts up the application./*from ww w. ja v a2 s.com*/ * * @param args * Given arguments from the command line. */ public static void main(String args[]) { try { // check assertion status //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); boolean assertionenabled = false; assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement" if (assertionenabled) System.out.println("Asserts are enabled"); // check memory amount System.gc(); final long startupMemFree = MemoryControl.free(); final long startupMemTotal = MemoryControl.total(); // maybe go into headless awt mode: we have three cases depending on OS and one exception: // windows : better do not go into headless mode // mac : go into headless mode because an application is shown in gui which may not be wanted // linux : go into headless mode because this does not need any head operation // exception : if the -gui option is used then do not go into headless mode since that uses a gui boolean headless = true; if (OS.isWindows) headless = false; if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) headless = false; System.setProperty("java.awt.headless", headless ? "true" : "false"); String s = ""; for (final String a : args) s += a + " "; yacyRelease.startParameter = s.trim(); File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/')); File dataRoot = applicationRoot; //System.out.println("args.length=" + args.length); //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]"); if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) { // normal start-up of yacy if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) { // start-up of yacy with gui if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true); } else if ((args.length >= 1) && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) { // normal shutdown of yacy if (args.length == 2) applicationRoot = new File(args[1]); shutdown(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) { // aut-update yacy if (args.length == 2) applicationRoot = new File(args[1]); update(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) { // show yacy version System.out.println(copyright); } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) { // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password) // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043") File f = new File(dataRoot, "DATA/SETTINGS/"); if (!f.exists()) { mkdirsIfNeseccary(f); } else { if (new File(dataRoot, "DATA/yacy.running").exists()) { System.out.println("please restart YaCy"); } } // use serverSwitch to read config properties (including init values from yacy.init serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init", "DATA/SETTINGS/yacy.conf"); for (int icnt = 1; icnt < args.length; icnt++) { String cfg = args[icnt]; int pos = cfg.indexOf('='); if (pos > 0) { String cmd = cfg.substring(0, pos); String val = cfg.substring(pos + 1); if (!val.isEmpty()) { if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd if (cpos >= 0) { String username = val.substring(0, cpos); String pwdtxt = val.substring(cpos + 1); if (!username.isEmpty()) { ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username); } else { username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, "admin"); } ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "MD5:" + Digest.encodeMD5Hex(username + ":" + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":" + pwdtxt)); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5 + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "")); } } else { ss.setConfig(cmd, val); System.out.println("Set property " + cmd + " = " + val); } } } else { System.out.println( "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)"); } System.out.println(); } } else { if (args.length == 1) { applicationRoot = new File(args[0]); } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } } finally { ConcurrentLog.shutdown(); } }
From source file:com.sforce.dataset.DatasetUtilMain.java
public static void main(String[] args) { printBanner();/*www .j a va 2s.co m*/ DatasetUtilParams params = new DatasetUtilParams(); if (args.length > 0) params.server = false; System.out.println(""); System.out.println("DatsetUtils called with {" + args.length + "} Params:"); for (int i = 0; i < args.length; i++) { if ((i & 1) == 0) { System.out.print("{" + args[i] + "}"); } else { if (i > 0 && args[i - 1].equalsIgnoreCase("--p")) System.out.println(":{*******}"); else System.out.println(":{" + args[i] + "}"); } if (i > 0 && args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; else if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; } } System.out.println(""); if (!printlneula(params.server)) { System.out.println( "You do not have permission to use this software. Please delete it from this computer"); System.exit(-1); } String action = null; if (args.length >= 2) { for (int i = 1; i < args.length; i = i + 2) { if (args[i - 1].equalsIgnoreCase("--help") || args[i - 1].equalsIgnoreCase("-help") || args[i - 1].equalsIgnoreCase("help")) { printUsage(); } else if (args[i - 1].equalsIgnoreCase("--u")) { params.username = args[i]; } else if (args[i - 1].equalsIgnoreCase("--p")) { params.password = args[i]; } else if (args[i - 1].equalsIgnoreCase("--sessionId")) { params.sessionId = args[i]; } else if (args[i - 1].equalsIgnoreCase("--token")) { params.token = args[i]; } else if (args[i - 1].equalsIgnoreCase("--endpoint")) { params.endpoint = args[i]; } else if (args[i - 1].equalsIgnoreCase("--action")) { action = args[i]; } else if (args[i - 1].equalsIgnoreCase("--operation")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("overwrite")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("upsert")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("append")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("delete")) { params.Operation = args[i]; } else { System.out.println("Invalid Operation {" + args[i] + "} Must be Overwrite or Upsert or Append or Delete"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--debug")) { params.debug = true; DatasetUtilConstants.debug = true; } else if (args[i - 1].equalsIgnoreCase("--ext")) { DatasetUtilConstants.ext = true; } else if (args[i - 1].equalsIgnoreCase("--inputFile")) { String tmp = args[i]; if (tmp != null) { File tempFile = new File(tmp); if (tempFile.exists()) { params.inputFile = tempFile.toString(); } else { System.out.println("File {" + args[i] + "} does not exist"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--dataset")) { params.dataset = args[i]; } else if (args[i - 1].equalsIgnoreCase("--datasetLabel")) { params.datasetLabel = args[i]; } else if (args[i - 1].equalsIgnoreCase("--app")) { params.app = args[i]; } else if (args[i - 1].equalsIgnoreCase("--useBulkAPI")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.useBulkAPI = true; } else if (args[i - 1].equalsIgnoreCase("--uploadFormat")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("csv")) params.uploadFormat = "csv"; else if (args[i] != null && args[i].trim().equalsIgnoreCase("binary")) params.uploadFormat = "binary"; } else if (args[i - 1].equalsIgnoreCase("--rowLimit")) { if (args[i] != null && !args[i].trim().isEmpty()) params.rowLimit = (new BigDecimal(args[i].trim())).intValue(); } else if (args[i - 1].equalsIgnoreCase("--rootObject")) { params.rootObject = args[i]; } else if (args[i - 1].equalsIgnoreCase("--fileEncoding")) { params.fileEncoding = args[i]; } else if (args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; else if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; } else if (args[i - 1].equalsIgnoreCase("--codingErrorAction")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("IGNORE")) { params.codingErrorAction = CodingErrorAction.IGNORE; } else if (args[i].equalsIgnoreCase("REPORT")) { params.codingErrorAction = CodingErrorAction.REPORT; } else if (args[i].equalsIgnoreCase("REPLACE")) { params.codingErrorAction = CodingErrorAction.REPLACE; } } } else { printUsage(); System.out.println("\nERROR: Invalid argument: " + args[i - 1]); System.exit(-1); } } //end for if (params.username != null) { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } if (params.server) { System.out.println(); System.out.println("\n*******************************************************************************"); try { DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); datasetUtilServer.init(args, true); } catch (Exception e) { e.printStackTrace(); } System.out.println("Server ended, exiting JVM....."); System.out.println("*******************************************************************************\n"); System.out.println("QUITAPP"); System.exit(0); } if (params.sessionId == null) { if (params.username == null || params.username.trim().isEmpty()) { params.username = getInputFromUser("Enter salesforce username: ", true, false); } if (params.username.equals("-1")) { params.sessionId = getInputFromUser("Enter salesforce sessionId: ", true, false); params.username = null; params.password = null; } else { if (params.password == null || params.password.trim().isEmpty()) { params.password = getInputFromUser("Enter salesforce password: ", true, true); } } } if (params.sessionId != null && !params.sessionId.isEmpty()) { while (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) System.out.println("\nERROR: endpoint must be specified when sessionId is specified"); } while (params.endpoint.toLowerCase().contains("login.salesforce.com") || params.endpoint.toLowerCase().contains("test.salesforce.com") || params.endpoint.toLowerCase().contains("test") || params.endpoint.toLowerCase().contains("prod") || params.endpoint.toLowerCase().contains("sandbox")) { System.out.println("\nERROR: endpoint must be the actual serviceURL and not the login url"); params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); } } else { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url (default=prod): ", false, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } try { if (params.endpoint.equalsIgnoreCase("PROD") || params.endpoint.equalsIgnoreCase("PRODUCTION")) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } else if (params.endpoint.equalsIgnoreCase("TEST") || params.endpoint.equalsIgnoreCase("SANDBOX")) { params.endpoint = DatasetUtilConstants.defaultEndpoint.replace("login", "test"); } URL uri = new URL(params.endpoint); String protocol = uri.getProtocol(); String host = uri.getHost(); if (protocol == null || !protocol.equalsIgnoreCase("https")) { if (host == null || !(host.toLowerCase().endsWith("internal.salesforce.com") || host.toLowerCase().endsWith("localhost"))) { System.out.println("\nERROR: Invalid endpoint. UNSUPPORTED_CLIENT: HTTPS Required in endpoint"); System.exit(-1); } } if (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/")) { uri = new URL(uri.getProtocol(), uri.getHost(), uri.getPort(), DatasetUtilConstants.defaultSoapEndPointPath); } params.endpoint = uri.toString(); } catch (MalformedURLException e) { e.printStackTrace(); System.out.println("\nERROR: endpoint is not a valid URL"); System.exit(-1); } PartnerConnection partnerConnection = null; if (params.username != null || params.sessionId != null) { try { partnerConnection = DatasetUtils.login(0, params.username, params.password, params.token, params.endpoint, params.sessionId, params.debug); } catch (ConnectionException e) { e.printStackTrace(); System.exit(-1); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(-1); } } if (args.length == 0 || action == null) { // System.out.println("\n*******************************************************************************"); //// FileListenerUtil.startAllListener(partnerConnection); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // } // System.out.println("*******************************************************************************\n"); // System.out.println(); // System.out.println("\n*******************************************************************************"); // try { // DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); // datasetUtilServer.init(args, false); // } catch (Exception e) { // e.printStackTrace(); // } // System.out.println("*******************************************************************************\n"); // System.out.println(); while (true) { action = getActionFromUser(); if (action == null || action.isEmpty()) { System.exit(-1); } params = new DatasetUtilParams(); getRequiredParams(action, partnerConnection, params); @SuppressWarnings("unused") boolean status = doAction(action, partnerConnection, params); // if(status) // { // if(action.equalsIgnoreCase("load") && params.debug) // createListener(partnerConnection, params); // } } } else { doAction(action, partnerConnection, params); } }
From source file:AndroidUninstallStock.java
@SuppressWarnings("static-access") public static void main(String[] args) { try {/*from w w w . j ava2 s .co m*/ String lang = Locale.getDefault().getLanguage(); GnuParser cmdparser = new GnuParser(); Options cmdopts = new Options(); for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) { // hack for printOptions java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld); fieldopt.setAccessible(true); fieldopt.set(cmdopts, new LinkedHashMap<>()); } cmdopts.addOption("h", "help", false, "Help"); cmdopts.addOption("t", "test", false, "Show only report"); cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg() .withDescription("Path to ADB from Android SDK").create("a")); cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg() .withDescription("Select device (\"adb devices\")").create("d")); cmdopts.addOption(null, "restore", false, "If packages have not yet removed and are disabled, " + "you can activate them again"); cmdopts.addOption(null, "google", false, "Delete packages are in the Google section"); cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex" + System.lineSeparator() + "(It is required to repeat command execution)"); cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]"); //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)"); cmdopts.addOption(null, "scanlibs", false, "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib"); cmdopts.addOptionGroup(new OptionGroup() { { addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired() .withDescription("Create file with list packages").create()); addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create()); } }); cmdopts.getOption("lang").setDescription( "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market"); CommandLine cmd = cmdparser.parse(cmdopts, args); if (args.length == 0 || cmd.hasOption("help")) { PrintWriter console = new PrintWriter(System.out); HelpFormatter cmdhelp = new HelpFormatter(); cmdhelp.setOptionComparator(new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return 0; } }); console.println("WARNING: Before use make a backup with ClockworkMod Recovery!"); console.println(); console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]"); cmdhelp.printOptions(console, 80, cmdopts, 3, 2); console.flush(); return; } String adb = cmd.getOptionValue("adb", "adb"); try { run(adb, "start-server"); } catch (IOException e) { System.out.println("Error: Not found ADB! Use -a or --adb"); return; } final boolean NotTest = !cmd.hasOption("test"); String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev")); if (!deverror.isEmpty()) { System.out.println(deverror); return; } System.out.println("Getting list packages:"); LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>(); for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) { // "pm list packages" give list sorted by packages ;) String pckg = ln.substring("package:".length()); String pckgname = ln.substring(ln.lastIndexOf('=') + 1); pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1); if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) { apklist.put(pckg, pckgname); } } for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) { String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk"); if (!apklist.containsKey(path)) { apklist.put(path, ""); } } apklist.remove("/system/app/mcRegistry"); for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } String genfile = cmd.getOptionValue("genfile"); if (genfile != null) { Path genpath = Paths.get(genfile); try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8, new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE })) { if (cmd.getOptionValue("lang") != null) { lang = cmd.getOptionValue("lang"); } LinkedHashSet<String> listsystem = new LinkedHashSet<String>() { { add("com.android"); add("com.google.android"); //add("com.sec.android.app"); add("com.monotype.android"); add("eu.chainfire.supersu"); } }; // \r\n for Windows Notepad gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); gen.write("<!-- & raplace with & or use <![CDATA[ ]]> -->\r\n"); gen.write("<AndroidUninstallStock>\r\n\r\n"); gen.write("<Normal>\r\n"); System.out.println(); System.out.println("\tNormal:"); writeInfo(gen, apklist, lang, listsystem, true); gen.write("\t<apk name=\"Exclude Google and etc\">\r\n"); for (String exc : listsystem) { gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n"); } gen.write("\t</apk>\r\n"); gen.write("</Normal>\r\n\r\n"); gen.write("<Google>\r\n"); System.out.println(); System.out.println("\tGoogle:"); writeInfo(gen, apklist, lang, listsystem, false); gen.write("</Google>\r\n\r\n"); gen.write("</AndroidUninstallStock>\r\n"); System.out.println("File " + genpath.toAbsolutePath() + " created."); } return; } String[] FileName = cmd.getArgs(); if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) { System.out.println("Error: File " + FileName[0] + " not found!"); return; } DocumentBuilderFactory xmlfactory = getXmlDocFactory(); // DocumentBuilder.setErrorHandler() for print errors Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0])); LinkedList<AusInfo> Normal = new LinkedList<AusInfo>(); LinkedList<AusInfo> Google = new LinkedList<AusInfo>(); NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes(); for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) { Node ndnow = ndaus.item(ndausx); NodeList nd = ndnow.getChildNodes(); String ndname = ndnow.getNodeName(); for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) { if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) { continue; } if (ndname.equalsIgnoreCase("Normal")) { Normal.add(getApkInfo(nd.item(ndx))); } else if (ndname.equalsIgnoreCase("Google")) { Google.add(getApkInfo(nd.item(ndx))); } } } // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages. // Now requires a restart. System.out.println(); System.out.println("Include and Exclude packages (Normal):"); LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false); System.out.println(); System.out.println("Global Exclude packages (Normal):"); apkNormal = getApkFromPattern(apkNormal, Normal, true); System.out.println(); System.out.println("Final list packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Include and Exclude packages (Google):"); apkGoogle = getApkFromPattern(apklist, Google, false); System.out.println(); System.out.println("Global Exclude packages (Google):"); apkGoogle = getApkFromPattern(apkGoogle, Google, true); System.out.println(); System.out.println("Final list packages (Google):"); for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } } if (NotTest) { if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } } if (cmd.hasOption("restore")) { System.out.println(); System.out.println("Enable (Restore) packages (Normal):"); damage(adb, "pm enable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Enable (Restore) packages (Google):"); damage(adb, "pm enable ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("FINISH :)"); return; } else { System.out.println(); System.out.println("Disable packages (Normal):"); damage(adb, "pm disable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Disable packages (Google):"); damage(adb, "pm disable ", NotTest, apkGoogle, 2); } } if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) { System.out.println(); System.out.println("FINISH :)"); return; } // Reboot now not needed /*if (NotTest) { reboot(adb, "-s", lastdevice, "reboot"); if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } }*/ if (cmd.hasOption("unlib")) { // "find" not found System.out.println(); System.out.println("Getting list libraries:"); LinkedList<String> liblist = new LinkedList<String>(); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/")); String dircur = "/system/lib/"; for (int x = 0; x < liblist.size(); x++) { if (liblist.get(x).startsWith("scan:")) { dircur = liblist.get(x).substring("scan:".length()); liblist.remove(x); x--; } else if (liblist.get(x).startsWith("d")) { String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/"; liblist.remove(x); x--; liblist.add("scan:/system/lib/" + dir); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir)); continue; } liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4)); System.out.println(liblist.get(x)); } final boolean scanlibs = cmd.hasOption("scanlibs"); LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal, "Normal", scanlibs); libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal"); System.out.println(); System.out.println("Final list libraries (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs); libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google"); System.out.println(); System.out.println("Final list libraries (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } } LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist); for (String key : apkNormal.keySet()) { apkExclude.remove(key); } for (String key : apkGoogle.keySet()) { apkExclude.remove(key); } System.out.println(); System.out.println("Include libraries from Exclude packages:"); LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude); System.out.println(); System.out.println("Enclude libraries from Exclude packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libNormal.remove(info.getKey()); } } System.out.println(); System.out.println("Enclude libraries from Exclude packages (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libGoogle.remove(info.getKey()); } } System.out.println(); System.out.println("Delete libraries (Normal):"); damage(adb, "rm ", NotTest, libNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete libraries (Google):"); damage(adb, "rm ", NotTest, libGoogle, 1); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Cleaning data packages (Normal):"); damage(adb, "pm clear ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Cleaning data packages (Google):"); damage(adb, "pm clear ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("Uninstall packages (Normal):"); damage(adb, "pm uninstall ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Uninstall packages (Google):"); damage(adb, "pm uninstall ", NotTest, apkGoogle, 2); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Delete packages (Normal):"); LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkNormal.entrySet()) { dexNormal.put(apk.getKey(), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete packages (Google):"); LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkGoogle.entrySet()) { dexGoogle.put(apk.getKey(), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexGoogle, 1); } } if (NotTest) { run(adb, "-s", lastdevice, "reboot"); } System.out.println(); System.out.println("FINISH :)"); } catch (SAXException e) { System.out.println("Error parsing list: " + e); } catch (Throwable e) { e.printStackTrace(); } }
From source file:com.okta.tools.awscli.java
public static void main(String[] args) throws Exception { awsSetup();/*from w ww . j av a 2 s. c om*/ extractCredentials(); // Step #1: Initiate the authentication and capture the SAML assertion. CloseableHttpClient httpClient = null; String resultSAML = ""; try { String strOktaSessionToken = oktaAuthntication(); if (!strOktaSessionToken.equalsIgnoreCase("")) //Step #2 get SAML assertion from Okta resultSAML = awsSamlHandler(strOktaSessionToken); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnknownHostException e) { logger.error( "\nUnable to establish a connection with AWS. \nPlease verify that your OKTA_AWS_APP_URL parameter is correct and try again"); System.exit(0); } catch (ClientProtocolException e) { logger.error("\nNo Org found, please specify an OKTA_ORG parameter in your config.properties file"); System.exit(0); } catch (IOException e) { e.printStackTrace(); } // Step #3: Assume an AWS role using the SAML Assertion from Okta AssumeRoleWithSAMLResult assumeResult = assumeAWSRole(resultSAML); com.amazonaws.services.securitytoken.model.AssumedRoleUser aru = assumeResult.getAssumedRoleUser(); String arn = aru.getArn(); // Step #4: Get the final role to assume and update the config file to add it to the user's profile GetRoleToAssume(crossAccountRoleName); logger.trace("Role to assume ARN: " + roleToAssume); // Step #5: Write the credentials to ~/.aws/credentials String profileName = setAWSCredentials(assumeResult, arn); UpdateConfigFile(profileName, roleToAssume); UpdateConfigFile(DefaultProfileName, roleToAssume); // Print Final message resultMessage(profileName); }
From source file:gr.demokritos.iit.demos.Demo.java
public static void main(String[] args) { try {//from w w w . ja va2s.c o m Options options = new Options(); options.addOption("h", HELP, false, "show help."); options.addOption("i", INPUT, true, "The file containing JSON " + " representations of tweets or SAG posts - 1 per line" + " default file looked for is " + DEFAULT_INFILE); options.addOption("o", OUTPUT, true, "Where to write the output " + " default file looked for is " + DEFAULT_OUTFILE); options.addOption("p", PROCESS, true, "Type of processing to do " + " ner for Named Entity Recognition re for Relation Extraction" + " default is NER"); options.addOption("s", SAG, false, "Whether to process as SAG posts" + " default is off - if passed means process as SAG posts"); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); // DEFAULTS String filename = DEFAULT_INFILE; String outfilename = DEFAULT_OUTFILE; String process = NER; boolean isSAG = false; if (cmd.hasOption(HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("NER + RE extraction module", options); System.exit(0); } if (cmd.hasOption(INPUT)) { filename = cmd.getOptionValue(INPUT); } if (cmd.hasOption(OUTPUT)) { outfilename = cmd.getOptionValue(OUTPUT); } if (cmd.hasOption(SAG)) { isSAG = true; } if (cmd.hasOption(PROCESS)) { process = cmd.getOptionValue(PROCESS); } System.out.println(); System.out.println("Reading from file: " + filename); System.out.println("Process type: " + process); System.out.println("Processing SAG: " + isSAG); System.out.println("Writing to file: " + outfilename); System.out.println(); List<String> jsoni = new ArrayList(); Scanner in = new Scanner(new FileReader(filename)); while (in.hasNextLine()) { String json = in.nextLine(); jsoni.add(json); } PrintWriter writer = new PrintWriter(outfilename, "UTF-8"); System.out.println("Read " + jsoni.size() + " lines from " + filename); if (process.equalsIgnoreCase(RE)) { System.out.println("Running Relation Extraction"); System.out.println(); String json = API.RE(jsoni, isSAG); System.out.println(json); writer.print(json); } else { System.out.println("Running Named Entity Recognition"); System.out.println(); jsoni = API.NER(jsoni, isSAG); /* for(String json: jsoni){ NamedEntityList nel = NamedEntityList.fromJSON(json); nel.prettyPrint(); } */ for (String json : jsoni) { System.out.println(json); writer.print(json); } } writer.close(); } catch (ParseException | UnsupportedEncodingException | FileNotFoundException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.sds.acube.ndisc.xadmin.XNDiscAdminUtil.java
public static void main(String args[]) { if (args.length == 0) { XNDiscAdminUtil.printAdminUsage(null, null); // System.exit(0); }/*from w w w. java2s.co m*/ XNDiscAdminFile file = new XNDiscAdminFile(printlog, out, logger); XNDiscAdminMedia media = new XNDiscAdminMedia(printlog, out, logger); XNDiscAdminVolume volume = new XNDiscAdminVolume(printlog, out, logger); XNDiscAdminEnDecrypt endecrypt = new XNDiscAdminEnDecrypt(printlog, out, logger); Scanner in = new Scanner(System.in); String input = ""; List<String> options = null; Scanner part = null; do { input = in.nextLine(); part = new Scanner(input).useDelimiter(" "); options = new ArrayList<String>(); while (part.hasNext()) { String val = part.next().trim(); if (StringUtils.isEmpty(val)) { continue; } options.add(val); } if (options.size() < 2 || input.equalsIgnoreCase("q")) { if (input != null && input.trim().equalsIgnoreCase("q")) { System.out.println(LINE_SEPERATOR + "XNDiscAdminUtil quit!!!" + LINE_SEPERATOR); } else { System.out .println(LINE_SEPERATOR + "XNDiscAdminUtil are invalid parameters!!!" + LINE_SEPERATOR); } System.exit(0); } String main_op = (StringUtils.isEmpty(options.get(0))) ? "" : options.get(0); String process_op = (StringUtils.isEmpty(options.get(1))) ? "" : options.get(1); if (main_op.equals("clear")) { if (process_op.equals("screen")) { clearConsoleOutput(); } } else if (main_op.equals("file")) { if (process_op.equals("ls")) { String fileid = ""; if (options.size() > 2) { fileid = options.get(2); } if (StringUtils.isEmpty(fileid)) { file.selectFileList(); } else { file.selectFileById(fileid); } } else if (process_op.equals("reg")) { String host = ""; int port = -1; String filepath = ""; int vol = -1; if (options.size() == 4) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); filepath = options.get(2); if (isInteger(options.get(3))) { vol = Integer.parseInt(options.get(3)); } } else if (options.size() > 5) { host = options.get(2); port = Integer.parseInt(options.get(3)); filepath = options.get(4); if (isInteger(options.get(5))) { vol = Integer.parseInt(options.get(5)); } } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(filepath) && port > 0 && vol > 0) { file.regFile(host, port, filepath, vol, "0"); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("get")) { String host = ""; int port = -1; String fileid = ""; String filepath = ""; if (options.size() == 4) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); fileid = options.get(2); filepath = options.get(3); } else if (options.size() > 5) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } fileid = options.get(4); filepath = options.get(5); } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && !StringUtils.isEmpty(filepath) && port > 0) { file.getFile(host, port, fileid, filepath); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("wh")) { String fileid = ""; if (options.size() > 2) { fileid = options.get(2); } if (!StringUtils.isEmpty(fileid)) { file.getFilePathByFileId(fileid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("rm")) { String host = ""; int port = -1; String fileid = ""; if (options.size() == 3) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); fileid = options.get(2); } else if (options.size() > 4) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } fileid = options.get(4); } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && port > 0) { file.removeFile(host, port, fileid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("media")) { if (process_op.equals("mk")) { String host = ""; int port = -1; String name = ""; int type = 0; String path = ""; String desc = " "; int maxsize = -1; int vol = -1; if (options.size() == 7) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); name = options.get(2); if (isInteger(options.get(3))) { type = Integer.parseInt(options.get(3)); } path = options.get(4); if (isInteger(options.get(5))) { maxsize = Integer.parseInt(options.get(5)); } if (isInteger(options.get(6))) { vol = Integer.parseInt(options.get(6)); } } else if (options.size() == 8) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); name = options.get(2); if (isInteger(options.get(3))) { type = Integer.parseInt(options.get(3)); } path = options.get(4); desc = options.get(5) + " "; if (isInteger(options.get(6))) { maxsize = Integer.parseInt(options.get(6)); } if (isInteger(options.get(7))) { vol = Integer.parseInt(options.get(7)); } } else if (options.size() == 9) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } name = options.get(4); if (isInteger(options.get(5))) { type = Integer.parseInt(options.get(5)); } path = options.get(6); if (isInteger(options.get(7))) { maxsize = Integer.parseInt(options.get(7)); } if (isInteger(options.get(8))) { vol = Integer.parseInt(options.get(8)); } } else if (options.size() > 9) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } name = options.get(4); if (isInteger(options.get(5))) { type = Integer.parseInt(options.get(5)); } path = options.get(6); desc = options.get(7) + " "; if (isInteger(options.get(8))) { maxsize = Integer.parseInt(options.get(8)); } if (isInteger(options.get(9))) { vol = Integer.parseInt(options.get(9)); } } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && port > 0 && vol > 0 && maxsize > 0) { media.makeMedia(host, port, name, type, path, desc, maxsize, vol); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ls")) { String mediaid = "-1"; if (options.size() > 2) { mediaid = options.get(2); } if (StringUtils.isEmpty(mediaid) || mediaid.equals("-1")) { media.selectMediaList(); } else { int id = -1; if (isInteger(mediaid)) { id = Integer.parseInt(mediaid); } if (id > 0) { media.selectMediaById(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("rm")) { String mediaid = "-1"; if (options.size() > 2) { mediaid = options.get(2); } if (!StringUtils.isEmpty(mediaid)) { int id = -1; if (isInteger(mediaid)) { id = Integer.parseInt(options.get(2)); } if (id > 0) { media.removeMedia(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("ch")) { int mediaid = -1; String name = ""; int type = 0; String path = ""; String desc = ""; int maxsize = -1; int vol = -1; if (options.size() == 8) { if (isInteger(options.get(2))) { mediaid = Integer.parseInt(options.get(2)); } name = options.get(3); if (isInteger(options.get(4))) { type = Integer.parseInt(options.get(4)); } path = options.get(5); if (isInteger(options.get(6))) { maxsize = Integer.parseInt(options.get(6)); } if (isInteger(options.get(7))) { vol = Integer.parseInt(options.get(7)); } } else if (options.size() > 8) { if (isInteger(options.get(2))) { mediaid = Integer.parseInt(options.get(2)); } name = options.get(3); if (isInteger(options.get(4))) { type = Integer.parseInt(options.get(4)); } path = options.get(5); desc = options.get(6); if (isInteger(options.get(7))) { maxsize = Integer.parseInt(options.get(7)); } if (isInteger(options.get(8))) { vol = Integer.parseInt(options.get(8)); } } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && mediaid > 0 && maxsize > 0 && vol > 0) { media.changeMedia(mediaid, name, type, path, desc, maxsize, vol); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("vol")) { if (process_op.equals("mk")) { String name = ""; String access = ""; String desc = " "; if (options.size() == 4) { name = options.get(2); access = options.get(3); } else if (options.size() > 4) { name = options.get(2); access = options.get(3); desc = options.get(4) + " "; } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access)) { volume.makeVolume(name, access, desc); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ls")) { String volid = "-1"; if (options.size() > 2) { volid = options.get(2); } if (StringUtils.isEmpty(volid) || volid.equals("-1")) { volume.selectVolumeList(); } else { int volumeid = -1; if (isInteger(volid)) { volumeid = Integer.parseInt(volid); } if (volumeid > 0) { volume.selectVolumeById(volumeid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("rm")) { String volid = "-1"; if (options.size() > 2) { volid = options.get(2); } if (!StringUtils.isEmpty(volid)) { int volumeid = -1; if (isInteger(volid)) { volumeid = Integer.parseInt(volid); } if (volumeid > 0) { volume.removeVolume(volumeid); } } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ch")) { int volumeid = -1; String name = ""; String access = ""; String desc = ""; if (options.size() == 5) { if (isInteger(options.get(2))) { volumeid = Integer.parseInt(options.get(2)); } name = options.get(3); access = options.get(4); } else if (options.size() > 5) { if (isInteger(options.get(2))) { volumeid = Integer.parseInt(options.get(2)); } name = options.get(3); access = options.get(4); desc = options.get(5) + " "; } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access) && volumeid > 0) { volume.changeVolume(volumeid, name, access, desc); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("id")) { String id = ""; if (options.size() > 2) { id = options.get(2); } if (process_op.equals("enc")) { if (!StringUtils.isEmpty(id)) { endecrypt.encrypt(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("dec")) { if (!StringUtils.isEmpty(id)) { endecrypt.decrypt(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } part.close(); } while (!input.equalsIgnoreCase("q")); in.close(); }
From source file:driver.ieSystem2.java
public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); boolean login = false; int check = 0; int id = 0;/* ww w. j a v a 2 s. c o m*/ String user = ""; String pass = ""; Person person = null; Date day = null; JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project", JOptionPane.INFORMATION_MESSAGE); do { System.out.println("What do you want?"); System.out.println("press 1 : Login"); System.out.println("press 2 : Create New User"); System.out.println("Press 3 : Exit "); System.out.println(""); do { try { System.out.print("Enter: "); check = sc.nextInt(); } catch (InputMismatchException e) { JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE); sc.next(); } } while (check <= 1 && check >= 3); // EXIT if (check == 3) { System.out.println("Close Application"); System.exit(0); } // CREATE USER if (check == 2) { System.out.println("-----------------------------------------"); System.out.println("Create New User"); System.out.println("-----------------------------------------"); System.out.print("Account ID: "); id = sc.nextInt(); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); try { Person.createUser(id, user, pass, 0, 0, 0, 0, 0); System.out.println("-----------------------------------------"); System.out.println("Create Complete"); System.out.println("-----------------------------------------"); } catch (Exception e) { System.out.println("-----------------------------------------"); System.out.println("Error, Try again"); System.out.println("-----------------------------------------"); } } else if (check == 1) { // LOGIN do { System.out.println("-----------------------------------------"); System.out.println("LOGIN "); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); if (Person.checkUser(user, pass)) { System.out.println("-----------------------------------------"); System.out.println("Login Complete"); } else { System.out.println("-----------------------------------------"); System.out.println("Invalid Username / Password"); } } while (!Person.checkUser(user, pass)); } } while (check != 1); login = true; person = new Person(user); do { System.out.println("-----------------------------------------"); System.out.println("Hi " + person.getPerName()); System.out.println("Press 1 : Add Income"); System.out.println("Press 2 : Add Expense"); System.out.println("Press 3 : Add Save"); System.out.println("Press 4 : History"); System.out.println("Press 5 : Search"); System.out.println("Press 6 : Analytics"); System.out.println("Press 7 : Total"); System.out.println("Press 8 : All Summary"); System.out.println("Press 9 : Sign Out"); do { try { System.out.print("Enter : "); check = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid Input"); sc.next(); } } while (check <= 1 && check >= 5); // Add Income if (check == 1) { double Income; String catalog = ""; double IncomeTotal = 0; catalog = JOptionPane.showInputDialog("What is your income : "); Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addIncome(person.getPerId(), day, catalog, Income); person.update(); } //Add Expense else if (check == 2) { double Expense; String catalog = ""; catalog = JOptionPane.showInputDialog("What is your expense :"); Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addExpense(person.getPerId(), day, catalog, Expense); person.update(); } //Add Save else if (check == 3) { double Saving; double SavingTotal = 0; String catalog = ""; Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); SavingTotal += Saving; person.addSave(person.getPerId(), day, catalog, Saving); person.update(); } //History else if (check == 4) { String x; do { System.out.println("-----------------------------------------"); System.out.println("YOUR HISTORY"); System.out.println("Date Type Amount"); System.out.println("-----------------------------------------"); List<History> history = person.getHistory(); if (history != null) { int count = 1; for (History h : history) { if (count++ <= 1) { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } else { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } } } System.out.println("-----------------------------------------"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //Searh else if (check == 5) { try { Connection conn = ConnectionDB.getConnection(); long a = person.getPerId(); String NAME = "Salary"; PreparedStatement ps = conn.prepareStatement( "SELECT * FROM INCOME WHERE PERID = " + a + " and CATALOG LIKE '%" + NAME + "%' "); ResultSet rec = ps.executeQuery(); while ((rec != null) && (rec.next())) { System.out.print(rec.getDate("Days")); System.out.print(" - "); System.out.print(rec.getString("CATALOG")); System.out.print(" - "); System.out.print(rec.getDouble("AMOUNT")); System.out.print(" - "); } ps.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Analy else if (check == 6) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); System.out.println("-----------------------------------------"); System.out.println("Income : " + df.format((in / sum) * 100) + "%"); System.out.println("Expense : " + df.format((ex / sum) * 100) + "%"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //TOTAL else if (check == 7) { String x; do { System.out.println("-----------------------------------------"); System.out.println("TOTALSAVE TOTAL"); System.out.println( person.getTotalSave() + " Baht" + " " + person.getTotal() + " Baht"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //ALL Summy else if (check == 8) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); double a = ((in / sum) * 100); double b = ((ex / sum) * 100); System.out.println("-----------------------------------------"); System.out.println("ALL SUMMARY"); System.out.println("Account: " + person.getPerName()); System.out.println(""); System.out.println("Total Save ------------- Total"); System.out .println(person.getTotalSave() + " Baht " + person.getTotal() + " Baht"); System.out.println(""); System.out.println("INCOME --------------- EXPENSE"); System.out.println(df.format(a) + "%" + " " + df.format(b) + "%"); System.out.println("-----------------------------------------"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //LOG OUT else { System.out.println("See ya.\n"); login = false; break; } } while (true); }
From source file:com.frostvoid.trekwar.server.TrekwarServer.java
public static void main(String[] args) { // load language try {/*from www .j a v a 2s . co m*/ lang = new Language(Language.ENGLISH); } catch (IOException ioe) { System.err.println("FATAL ERROR: Unable to load language file!"); System.exit(1); } System.out.println(lang.get("trekwar_server") + " " + VERSION); System.out.println("==============================================".substring(0, lang.get("trekwar_server").length() + 1 + VERSION.length())); // Handle parameters Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg() .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load"); options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg() .withDescription("the port number to bind to (default 8472)").create("p")); options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg() .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s")); options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg() .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF") .create("l")); options.addOption("h", "help", false, "prints this help message"); CommandLineParser cliParser = new BasicParser(); try { CommandLine cmd = cliParser.parse(options, args); String portStr = cmd.getOptionValue("p"); String galaxyFileStr = cmd.getOptionValue("g"); String saveIntervalStr = cmd.getOptionValue("s"); String logLevelStr = cmd.getOptionValue("l"); if (cmd.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("TrekwarServer", options); System.exit(0); } if (cmd.hasOption("g") && galaxyFileStr != null) { galaxyFileName = galaxyFileStr; } else { throw new ParseException("galaxy file not specified"); } if (cmd.hasOption("p") && portStr != null) { port = Integer.parseInt(portStr); if (port < 1 || port > 65535) { throw new NumberFormatException(lang.get("port_number_out_of_range")); } } else { port = 8472; } if (cmd.hasOption("s") && saveIntervalStr != null) { saveInterval = Integer.parseInt(saveIntervalStr); if (saveInterval < 1 || saveInterval > 100) { throw new NumberFormatException("Save Interval out of range (1-100)"); } } else { saveInterval = 5; } if (cmd.hasOption("l") && logLevelStr != null) { if (logLevelStr.equalsIgnoreCase("finest")) { LOG.setLevel(Level.FINEST); } else if (logLevelStr.equalsIgnoreCase("finer")) { LOG.setLevel(Level.FINER); } else if (logLevelStr.equalsIgnoreCase("fine")) { LOG.setLevel(Level.FINE); } else if (logLevelStr.equalsIgnoreCase("config")) { LOG.setLevel(Level.CONFIG); } else if (logLevelStr.equalsIgnoreCase("info")) { LOG.setLevel(Level.INFO); } else if (logLevelStr.equalsIgnoreCase("warning")) { LOG.setLevel(Level.WARNING); } else if (logLevelStr.equalsIgnoreCase("severe")) { LOG.setLevel(Level.SEVERE); } else if (logLevelStr.equalsIgnoreCase("off")) { LOG.setLevel(Level.OFF); } else if (logLevelStr.equalsIgnoreCase("all")) { LOG.setLevel(Level.ALL); } else { System.err.println("ERROR: invalid log level: " + logLevelStr); System.err.println("Run again with -h flag to see valid log level values"); System.exit(1); } } else { LOG.setLevel(Level.INFO); } // INIT LOGGING try { LOG.setUseParentHandlers(false); initLogging(); } catch (IOException ex) { System.err.println("Unable to initialize logging to file"); System.err.println(ex); System.exit(1); } } catch (Exception ex) { System.err.println("ERROR: " + ex.getMessage()); System.err.println("use -h for help"); System.exit(1); } LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up"); // LOAD GALAXY File galaxyFile = new File(galaxyFileName); if (galaxyFile.exists()) { try { long timer = System.currentTimeMillis(); LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile)); galaxy = (Galaxy) ois.readObject(); timer = System.currentTimeMillis() - timer; LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer); ois.close(); } catch (IOException ioe) { LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe); } catch (ClassNotFoundException cnfe) { LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe); } } else { System.err.println("Error: file " + galaxyFileName + " not found"); System.exit(1); } // if turn == 0 (start of game), execute first turn to update fog of war. if (galaxy.getCurrentTurn() == 0) { TurnExecutor.executeTurn(galaxy); } LOG.log(Level.INFO, "Current turn : {0}", galaxy.getCurrentTurn()); LOG.log(Level.INFO, "Turn speed : {0} seconds", galaxy.getTurnSpeed() / 1000); LOG.log(Level.INFO, "Save Interval : {0}", saveInterval); LOG.log(Level.INFO, "Users / max : {0} / {1}", new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() }); // START SERVER try { server = new ServerSocket(port); LOG.log(Level.INFO, "Server listening on port {0}", port); } catch (BindException be) { LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port); System.err.println(be); System.exit(1); } catch (IOException ioe) { LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port); System.err.println(ioe); System.exit(1); } galaxy.startup(); Thread timerThread = new Thread(new Runnable() { @Override @SuppressWarnings("SleepWhileInLoop") public void run() { while (true) { try { Thread.sleep(1000); // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING) if (System.currentTimeMillis() > galaxy.nextTurnDate) { StringBuffer loggedInUsers = new StringBuffer(); for (User u : galaxy.getLoggedInUsers()) { loggedInUsers.append(u.getUsername()).append(", "); } long time = TurnExecutor.executeTurn(galaxy); LOG.log(Level.INFO, "Turn {0} executed in {1} ms", new Object[] { galaxy.getCurrentTurn(), time }); LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString()); LOG.log(Level.INFO, "===================================================================================="); if (galaxy.getCurrentTurn() % saveInterval == 0) { saveGalaxy(); } galaxy.lastTurnDate = System.currentTimeMillis(); galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed; } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e); } } } }); timerThread.start(); // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS while (true) { Socket clientConnection; try { clientConnection = server.accept(); ClientSession c = new ClientSession(clientConnection, galaxy); Thread t = new Thread(c); t.start(); } catch (IOException ex) { LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex); } } }