List of usage examples for java.util Locale getDefault
public static Locale getDefault()
From source file:es.tunelator.Start.java
/** * Bootstraps the application, creates and shows the user interface * @param args/*from w ww. java 2s.c o m*/ */ public static void main(String[] args) { MainFrame frame = null; try { // LogFactory.getFactory().setAttribute(LogFactoryImpl.LOG_PROPERTY, // Log4JLogger.class.getName()); // PropertyConfigurator.configure(Start.class.getClassLoader(). // getResource("log4j.properties")); // Set log level as configured at the application parameters Logger.setLogThreshold(AppParameters.getParams().getProperty("log.threshold", AppParameters.LOG_ERROR)); // If the language of the default locale is not supported revert to english if (!isLocaleSupported()) { Locale.setDefault(new Locale("en", "", "")); } else { Locale.setDefault(new Locale(Locale.getDefault().getLanguage(), "", "")); } // Log application startup Logger.logInfo(Start.class, Resourcer.getString(null, "log.info.startup")); // To set up the Look and Feel UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows." + "WindowsLookAndFeel"); frame = new MainFrame(); frame.setVisible(true); frame.correctTabStatus(); // To change the Look and Feel. To be included as an option some day... // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk."+ // "GTKLookAndFeel"); // SwingUtilities.updateComponentTreeUI(frame); // frame.pack(); } catch (Exception e) { Logger.logFatal(Start.class, e); if (frame != null) { frame.showErrorMessage(Resourcer.getString(null, "error.internal")); frame.dispose(); } else { try { JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"), Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE); } catch (Exception e2) { String message = ""; // This is the last resort to give a localized message // As I'm spanish :-), we give a spanish message if it's // the default language, and an english one otherwise. if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) { message = message_es; } else { message = message_en; } JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); } } System.exit(1); } catch (InternalError e) { Logger.logFatal(Start.class, e); if (frame != null) { frame.showErrorMessage(Resourcer.getString(null, "error.internal")); frame.dispose(); } else { try { JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"), Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE); } catch (Exception e2) { String message = ""; // This is the last resort to give a localized message // As I'm spanish :-), we give a spanish message if it's // the default language, and an english one otherwise. if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) { message = message_es; } else { message = message_en; } JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); } } System.exit(1); } }
From source file:AndroidUninstallStock.java
@SuppressWarnings("static-access") public static void main(String[] args) { try {//from w w w. j a v a2s .c o 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:SimpleMenu.java
/** A simple test program for the above code */ public static void main(String[] args) { // Get the locale: default, or specified on command-line Locale locale;//from w w w . j ava2s . co m if (args.length == 2) locale = new Locale(args[0], args[1]); else locale = Locale.getDefault(); // Get the resource bundle for that Locale. This will throw an // (unchecked) MissingResourceException if no bundle is found. ResourceBundle bundle = ResourceBundle.getBundle("com.davidflanagan.examples.i18n.Menus", locale); // Create a simple GUI window to display the menu with final JFrame f = new JFrame("SimpleMenu: " + // Window title locale.getDisplayName(Locale.getDefault())); JMenuBar menubar = new JMenuBar(); // Create a menubar. f.setJMenuBar(menubar); // Add menubar to window // Define an action listener for that our menu will use. ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); Component c = f.getContentPane(); if (s.equals("red")) c.setBackground(Color.red); else if (s.equals("green")) c.setBackground(Color.green); else if (s.equals("blue")) c.setBackground(Color.blue); } }; // Now create a menu using our convenience routine with the resource // bundle and action listener we've created JMenu menu = SimpleMenu.create(bundle, "colors", new String[] { "red", "green", "blue" }, listener); // Finally add the menu to the GUI, and pop it up menubar.add(menu); // Add the menu to the menubar f.setSize(300, 150); // Set the window size. f.setVisible(true); // Pop the window up. }
From source file:generators.ExpressionMetaValidator.java
public static void main(String[] args) { ClassicEngineBoot.getInstance().start(); int invalidExpressionsCounter = 0; int deprecatedExpressionsCounter = 0; final HashNMap expressionsByGroup = new HashNMap(); ExpressionRegistry expressionRegistry = ExpressionRegistry.getInstance(); final ExpressionMetaData[] allExpressions = expressionRegistry.getAllExpressionMetaDatas(); for (int i = 0; i < allExpressions.length; i++) { final ExpressionMetaData expression = allExpressions[i]; if (expression == null) { logger.warn("Null Expression encountered"); continue; }// www . j a v a 2 s. c o m missingProperties.clear(); final Class type = expression.getExpressionType(); if (type == null) { logger.warn("Expression class is null"); } logger.debug("Processing " + type); final Class resultType = expression.getResultType(); if (resultType == null) { logger.warn("Expression '" + expression.getExpressionType() + " is null"); } try { final BeanInfo beanInfo = expression.getBeanDescriptor(); if (beanInfo == null) { logger.warn( "Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor: Null"); } } catch (IntrospectionException e) { logger.warn("Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor", e); } final Locale locale = Locale.getDefault(); final String displayName = expression.getDisplayName(locale); if (isValid(displayName, expression.getName()) == false) { logger.warn("Expression '" + expression.getExpressionType() + ": No valid display name"); } if (expression.isDeprecated()) { deprecatedExpressionsCounter += 1; final String deprecateMessage = expression.getDeprecationMessage(locale); if (isValid(deprecateMessage, "Use a Formula instead") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": No valid deprecate message"); } } final String grouping = expression.getGrouping(locale); if (isValid(grouping, "Group") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": No valid grouping message"); } expressionsByGroup.add(grouping, expression); final ExpressionPropertyMetaData[] properties = expression.getPropertyDescriptions(); for (int j = 0; j < properties.length; j++) { final ExpressionPropertyMetaData propertyMetaData = properties[j]; final String name = propertyMetaData.getName(); if (StringUtils.isEmpty(name)) { logger.warn("Expression '" + expression.getExpressionType() + ": Property without a name"); } final String propertyDisplayName = propertyMetaData.getDisplayName(locale); if (isValid(propertyDisplayName, name) == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": No DisplayName"); } final String propertyGrouping = propertyMetaData.getGrouping(locale); if (isValid(propertyGrouping, "Group") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Grouping is not valid"); } final int groupingOrdinal = propertyMetaData.getGroupingOrdinal(locale); if (groupingOrdinal == Integer.MAX_VALUE) { if (propertyMetaData instanceof DefaultExpressionMetaData) { final DefaultExpressionPropertyMetaData demd = (DefaultExpressionPropertyMetaData) propertyMetaData; missingProperties.add(demd.getKeyPrefix() + "grouping.ordinal=1000"); } logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Grouping ordinal is not valid"); } final int ordinal = propertyMetaData.getItemOrdinal(locale); if (groupingOrdinal == Integer.MAX_VALUE) { if (propertyMetaData instanceof DefaultExpressionMetaData) { final DefaultExpressionPropertyMetaData demd = (DefaultExpressionPropertyMetaData) propertyMetaData; missingProperties.add(demd.getKeyPrefix() + "ordinal=1000"); } logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Ordinal is not valid"); } final String propertyDescription = propertyMetaData.getDescription(locale); if (isValid(propertyDescription, "") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Description is not valid"); } final String propertyDeprecated = propertyMetaData.getDeprecationMessage(locale); if (isValid(propertyDeprecated, "") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Deprecation is not valid"); } final String role = propertyMetaData.getPropertyRole(); if (isValid(role, "Value") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Role is not valid"); } final Class propertyType = propertyMetaData.getPropertyType(); if (propertyType == null) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": Property Type is not valid"); } // should not crash! final PropertyDescriptor propertyDescriptor = propertyMetaData.getBeanDescriptor(); if (propertyMetaData.isDeprecated()) { final String deprecateMessage = propertyMetaData.getDeprecationMessage(locale); if (isValid(deprecateMessage, "Deprecated") == false) { logger.warn("Expression '" + expression.getExpressionType() + ": Property " + propertyMetaData.getName() + ": No valid deprecate message"); } } } try { final BeanInfo beanInfo = Introspector.getBeanInfo(expression.getExpressionType()); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int propIdx = 0; propIdx < descriptors.length; propIdx++) { final PropertyDescriptor descriptor = descriptors[propIdx]; final String key = descriptor.getName(); if ("runtime".equals(key)) { continue; } if ("active".equals(key)) { continue; } if ("preserve".equals(key)) { continue; } if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { continue; } if (expression.getPropertyDescription(key) == null) { logger.warn("Expression '" + expression.getExpressionType() + ": No property definition for " + key); missingPropertyDefs.add(" <property name=\"" + key + "\" mandatory=\"false\" preferred=\"false\" value-role=\"Value\" expert=\"false\" hidden=\"false\"/>"); } } } catch (Throwable e) { logger.warn("Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor", e); } System.err.flush(); try { Thread.sleep(25); } catch (InterruptedException e) { } for (int x = 0; x < missingProperties.size(); x++) { final String property = (String) missingProperties.get(x); System.out.println(property); } for (int j = 0; j < missingPropertyDefs.size(); j++) { final String def = (String) missingPropertyDefs.get(j); System.out.println(def); } if (missingProperties.isEmpty() == false || missingPropertyDefs.isEmpty() == false) { invalidExpressionsCounter += 1; missingProperties.clear(); missingPropertyDefs.clear(); } System.out.flush(); try { Thread.sleep(25); } catch (InterruptedException e) { } } logger.info("Validated " + allExpressions.length + " expressions. Invalid: " + invalidExpressionsCounter + " Deprecated: " + deprecatedExpressionsCounter); final Object[] keys = expressionsByGroup.keySet().toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { final Object key = keys[i]; logger.info("Group: '" + key + "' Size: " + expressionsByGroup.getValueCount(key)); final Object[] objects = expressionsByGroup.toArray(key); for (int j = 0; j < objects.length; j++) { ExpressionMetaData metaData = (ExpressionMetaData) objects[j]; logger.info(" " + metaData.getExpressionType()); } } }
From source file:sdmx.net.service.knoema.KnoemaRESTServiceRegistry.java
public static void main(String args[]) { KnoemaRESTServiceRegistry registry = new KnoemaRESTServiceRegistry("knoema", "http://knoema.com/api/1.0/sdmx"); List<DataflowType> dfs = registry.listDataflows(); for (DataflowType df : dfs) { System.out.println(NameableType.toString(df, Locale.getDefault())); }/*from w w w.ja va2s .c o m*/ }
From source file:be.dnsbelgium.rdap.client.RDAPCLI.java
public static void main(String[] args) { LOGGER.debug("Create the command line parser"); CommandLineParser parser = new GnuParser(); LOGGER.debug("Create the options"); Options options = new RDAPOptions(Locale.ENGLISH); try {/*from w w w . java2 s . c om*/ LOGGER.debug("Parse the command line arguments"); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { printHelp(options); return; } if (line.getArgs().length == 0) { throw new IllegalArgumentException("You must provide a query"); } String query = line.getArgs()[0]; Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase()) : guessQueryType(query); LOGGER.debug("Query: {}, Type: {}", query, type); try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (line.hasOption(RDAPOptions.TRUSTSTORE)) { sslContextBuilder.loadTrustMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)), line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS))); } if (line.hasOption(RDAPOptions.KEYSTORE)) { sslContextBuilder.loadKeyMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)), line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray()); } SSLContext sslContext = sslContextBuilder.build(); final String url = line.getOptionValue(RDAPOptions.URL); final HttpHost host = Utils.httpHost(url); HashSet<Header> headers = new HashSet<Header>(); headers.add(new BasicHeader("Accept-Language", line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString()))); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers) .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier()))); if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME), line.getOptionValue(RDAPOptions.PASSWORD))); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url); ObjectMapper mapper = new ObjectMapper(); JsonNode json = null; switch (type) { case DOMAIN: json = rdapClient.getDomainAsJson(query); break; case ENTITY: json = rdapClient.getEntityAsJson(query); break; case AUTNUM: json = rdapClient.getAutNum(query); break; case IP: json = rdapClient.getIp(query); break; case NAMESERVER: json = rdapClient.getNameserver(query); break; } PrintWriter out = new PrintWriter(System.out, true); if (line.hasOption(RDAPOptions.RAW)) { mapper.writer().writeValue(out, json); } else if (line.hasOption(RDAPOptions.PRETTY)) { mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json); } else if (line.hasOption(RDAPOptions.YAML)) { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setPrettyFlow(true); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setSplitLines(true); Yaml yaml = new Yaml(dumperOptions); Map data = mapper.convertValue(json, Map.class); yaml.dump(data, out); } else { mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json); } out.flush(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); System.exit(-1); } } catch (org.apache.commons.cli.ParseException e) { printHelp(options); System.exit(-1); } }
From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java
public static void main(String args[]) { NOMISRESTServiceRegistry registry = new NOMISRESTServiceRegistry("NOMIS", "http://www.nomisweb.co.uk/api", "uid=0xad235cca367972d98bd642ef04ea259da5de264f"); List<DataflowType> list = registry.listDataflows(); Locale loc = Locale.getDefault(); for (DataflowType df : list) { System.out.println(NameableType.toString(df, loc) + "," + df.getAgencyID() + "," + df.getId()); }//from www .ja va 2 s. com }
From source file:io.werval.cli.DamnSmallDevShell.java
public static void main(String[] args) { Options options = declareOptions();//from w w w . j a va 2 s . co m CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); // Handle --help if (cmd.hasOption("help")) { PrintWriter out = new PrintWriter(System.out); printHelp(options, out); out.flush(); System.exit(0); } // Handle --version if (cmd.hasOption("version")) { System.out.print(String.format( "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n" + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n" + "OS name: %s, version: %s, arch: %s\n", VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home"), Locale.getDefault().toString(), System.getProperty("file.encoding"), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))); System.out.flush(); System.exit(0); } // Debug final boolean debug = cmd.hasOption('d'); // Temporary directory final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp")); if (debug) { System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'."); } // Handle commands @SuppressWarnings("unchecked") List<String> commands = cmd.getArgList(); if (commands.isEmpty()) { commands = Collections.singletonList("start"); } if (debug) { System.out.println("Commands to be executed: " + commands); } Iterator<String> commandsIterator = commands.iterator(); while (commandsIterator.hasNext()) { String command = commandsIterator.next(); switch (command) { case "new": System.out.println(LOGO); newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd); break; case "clean": cleanCommand(debug, tmpDir); break; case "devshell": System.out.println(LOGO); devshellCommand(debug, tmpDir, cmd); break; case "start": System.out.println(LOGO); startCommand(debug, tmpDir, cmd); break; case "secret": secretCommand(); break; default: PrintWriter out = new PrintWriter(System.err); System.err.println("Unknown command: '" + command + "'"); printHelp(options, out); out.flush(); System.exit(1); break; } } } catch (IllegalArgumentException | ParseException | IOException ex) { PrintWriter out = new PrintWriter(System.err); printHelp(options, out); out.flush(); System.exit(1); } catch (WervalException ex) { ex.printStackTrace(System.err); System.err.flush(); System.exit(1); } }
From source file:com.clustercontrol.HinemosManagerMain.java
/** * Hinemos Manager?main<br/>//from w w w . ja va 2 s .co m * @param args * @throws Exception */ public static void main(String args[]) { try { try { if (System.getProperty("systime.iso") != null) { String oldVmName = System.getProperty("java.vm.name"); //System?mock?????HotSpot?????????? System.setProperty("java.vm.name", "HotSpot 64-Bit Server VM"); Class.forName("com.clustercontrol.util.SystemTimeShifter"); System.setProperty("java.vm.name", oldVmName); } } catch (Exception e) { log.error(e); } catch (Error e) { log.error(e); } long bootTime = System.currentTimeMillis(); log.info("Hinemos Manager is starting." + " (startupMode=" + _startupMode + ", clustered=" + _isClustered + ", locale=" + Locale.getDefault() + ")"); // Hinemos(??????)??????? // (???????????????????????) long offset = HinemosPropertyUtil.getHinemosPropertyNum("common.time.offset", Long.valueOf(0)); HinemosTime.setTimeOffsetMillis(offset); // Hinemos?(UTC??)??/(??) int timeZoneOffset = HinemosPropertyUtil .getHinemosPropertyNum("common.timezone", Long.valueOf(TimeZone.getDefault().getRawOffset())) .intValue(); HinemosTime.setTimeZoneOffset(timeZoneOffset); // ???HinemosPlugin??(create)? HinemosPluginService.getInstance().create(); // ???HinemosPlugin?(activate)? HinemosPluginService.getInstance().activate(); // Hinemos Manger???? Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { log.info("shutdown hook called."); synchronized (shutdownLock) { // Hinemos Manager??? String[] msgArgsShutdown = { _hostname }; AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR, MessageConstant.MESSAGE_SYS_002_MNG, msgArgsShutdown); // ???HinemosPlugin??(deactivate)? HinemosPluginService.getInstance().deactivate(); // ???HinemosPlugin?(destroy)? HinemosPluginService.getInstance().destroy(); log.info("Hinemos Manager is stopped."); shutdown = true; shutdownLock.notify(); } } }); // ?? long startupTime = System.currentTimeMillis(); long initializeSec = (startupTime - bootTime) / 1000; long initializeMSec = (startupTime - bootTime) % 1000; log.info("Hinemos Manager Started in " + initializeSec + "s:" + initializeMSec + "ms"); // Hinemos Manager?? String[] msgArgsStart = { _hostname }; AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR, MessageConstant.MESSAGE_SYS_001_MNG, msgArgsStart); // Hinemos Manager??????? synchronized (shutdownLock) { while (!shutdown) { try { shutdownLock.wait(); } catch (InterruptedException e) { log.warn("shutdown lock interrupted.", e); try { Thread.sleep(1000); } catch (InterruptedException sleepE) { } ; } } } System.exit(0); } catch (Throwable e) { log.error("unknown error occured.", e); } }
From source file:edu.ku.brc.specify.config.init.SpecifyDBSetupWizardFrame.java
/** * @param args/*from w w w. j a v a 2s .c o m*/ */ public static void main(String[] args) { // Set App Name, MUST be done very first thing! UIRegistry.setAppName("Specify"); //$NON-NLS-1$ try { ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$ } catch (MissingResourceException ex) { Locale.setDefault(Locale.ENGLISH); UIRegistry.setResourceLocale(Locale.ENGLISH); } try { if (!System.getProperty("os.name").equals("Mac OS X")) { UIManager.setLookAndFeel(new Plastic3DLookAndFeel()); PlasticLookAndFeel.setPlasticTheme(new DesertBlue()); } } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyDBSetupWizard.class, e); e.printStackTrace(); } AppBase.processArgs(args); AppBase.setupTeeForStdErrStdOut(true, false); System.setProperty("appdatadir", ".."); // Then set this IconManager.setApplicationClass(Specify.class); IconManager.loadIcons(XMLHelper.getConfigDir("icons_datamodel.xml")); //$NON-NLS-1$ IconManager.loadIcons(XMLHelper.getConfigDir("icons_plugins.xml")); //$NON-NLS-1$ IconManager.loadIcons(XMLHelper.getConfigDir("icons_disciplines.xml")); //$NON-NLS-1$ // Load Local Prefs AppPreferences localPrefs = AppPreferences.getLocalPrefs(); //try { //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "+(new File(UIRegistry.getAppDataDir()).getCanonicalPath())+"]"); //} catch (IOException ex) {} localPrefs.setDirPath(UIRegistry.getAppDataDir()); // Check to see if we should check for a new version if (localPrefs.getBoolean(VERSION_CHECK, null) == null) { localPrefs.putBoolean(VERSION_CHECK, true); } if (localPrefs.getBoolean(EXTRA_CHECK, null) == null) { localPrefs.putBoolean(EXTRA_CHECK, true); } if (UIHelper.isLinux()) { Specify.checkForSpecifyAppsRunning(); } if (UIRegistry.isEmbedded()) { ProcessListUtil.checkForMySQLProcesses(new ProcessListener() { @Override public void done(PROC_STATUS status) // called on the UI thread { if (status == PROC_STATUS.eOK || status == PROC_STATUS.eFoundAndKilled) { startupContinuing(); } } }); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { startupContinuing(); } }); } }