List of usage examples for java.util Map get
V get(Object key);
From source file:com.music.tools.InstrumentExtractor.java
public static void main(String[] args) { Map<Integer, String> instrumentNames = new HashMap<>(); Field[] fields = ProgramChanges.class.getDeclaredFields(); try {/* ww w . ja v a2s .c o m*/ for (Field field : fields) { Integer value = (Integer) field.get(null); if (!instrumentNames.containsKey(value)) { instrumentNames.put(value, StringUtils.capitalize(field.getName().toLowerCase()).replace('_', ' ')); } } } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } Score score = new Score(); Read.midi(score, "C:\\Users\\bozho\\Downloads\\7938.midi"); for (Part part : score.getPartArray()) { System.out.println(part.getChannel() + " : " + part.getInstrument() + ": " + instrumentNames.get(part.getInstrument())); } }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>/*from ww w . java 2 s . c o m*/ * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5bGoldLabelStatistics.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];//w ww .j a v a 2 s . c o m Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); Map<String, Integer> goldDataDistribution = new HashMap<>(); int totalGoldReasonTokens = 0; for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; for (AnnotatedArgumentPair annotatedArgumentPair : argumentPairs) { String goldLabel = annotatedArgumentPair.getGoldLabel(); int sameInOnePair = 0; if (goldLabel != null) { if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; totalGoldReasonTokens += assignment.getReason().split("\\W+").length; } } pairsPerTopicCounter++; } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } statsPerTopic.addValue(pairsPerTopicCounter); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println(goldDataDistribution); System.out.println(goldDataDistribution.values()); System.out.println("Total pairs: " + totalPairs); System.out.println("Stats per topic: " + statsPerTopic); System.out.println("Total gold reason tokens: " + totalGoldReasonTokens); }
From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH) .desc("Mysql client jar url to download").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL) .desc("JDBC url to connect DBMS via admin.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER) .desc("Admin user name: should be able to create and grant privileges.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD) .desc("Admin user's password: should be able to create and grant privileges.").build()); options.addOption(//w ww.j a va 2s .c om Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build()); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL, OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD, OPTION_TARGET_DATABASE }; boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt)); if (optNotFound) { usage(options); System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine); if (!adminOptionsOptional.isPresent()) { usage(options); System.exit(1); } AdminOptions adminOptions = adminOptionsOptional.get(); Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine); if (!targetOptionsOptional.isPresent()) { usage(options); System.exit(1); } TargetOptions targetOptions = targetOptionsOptional.get(); DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl()); Map<String, Object> conf; try { conf = Utils.readConfig(confFilePath); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } String bootstrapDirPath = null; try { bootstrapDirPath = System.getProperty("bootstrap.dir"); Proxy proxy = Proxy.NO_PROXY; String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL); String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME); String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD); if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) { URL url = new URL(httpProxyUrl); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())); if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) { Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername, httpProxyPassword)); } } StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get( adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(), adminOptions.getDatabaseType()); MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy); } catch (Exception e) { System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } try (Connection conn = getConnectionViaAdmin(adminOptions)) { DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); String database = targetOptions.getDatabase(); String username = targetOptions.getUsername(); createDatabase(databaseCreator, database); createUser(targetOptions, userCreator, username); grantPrivileges(databaseCreator, database, username); } }
From source file:rooms.Application.java
public static void main(String[] args) throws ValueException, ThingException, InterruptedException { AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfig.class); //AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfigMongo.class); // MongoOperations mo = (MongoOperations) context.getBean("mongoTemplate"); final ThingControl tc = (ThingControl) context.getBean("thingControl"); for (String s : context.getBeanDefinitionNames()) { System.out.println(s);/* w w w . j a v a2 s . c om*/ } System.out.println("THINGSSSS"); for (Thing t : tc.findAllThings()) { System.out.println("THING: " + t); } // mo.dropCollection(Thing.class); // mo.dropCollection(Bridge.class); // mo.dropCollection(Light.class); List<Thing> t = tc.findThingsForType("bridge"); Bridge b = new Bridge("10.0.0.40"); Thing tb = tc.createThing("bridge", b); Light l = new Light(Group.GROUP_1, "white"); Thing tl = tc.createThing("bedroom_ceiling", l); Light l2 = new Light(Group.GROUP_2, "white"); Thing tl2 = tc.createThing("bedroom_bed", l2); Light l3 = new Light(Group.GROUP_3, "white"); Thing tl3 = tc.createThing("bedroom_desk", l3); tc.addChildThing(tb, tl); tc.addChildThing(tb, tl2); tc.addChildThing(tb, tl3); List<Thing<Bridge>> bridges = tc.findThingsForType(Bridge.class); Map<String, LightWhiteV2> lights = Maps.newHashMap(); for (Thing<Bridge> bridgeThing : bridges) { Bridge bridge = tc.getValue(bridgeThing); LimitlessLEDControllerV2 c = new LimitlessLEDControllerV2(b.getHost(), b.getPort()); List<Thing<Light>> lightThings = tc.getChildrenForType(Observable.just(bridgeThing), Light.class, true); for (Thing<Light> tempLight : lightThings) { Light ll = tc.getValue(tempLight); LightWhiteV2 white = new LightWhiteV2(tempLight.getKey(), c, ll.getLightGroup()); lights.put(white.getName(), white); System.out.println("LIGHT: " + white.getName()); } } // lights.get("bedroom_ceiling").setOn(true); lights.get("bedroom_bed").setOn(true); Thread.sleep(2000); // lights.get("bedroom_ceiling").setOn(false); lights.get("bedroom_bed").setOn(false); Thread.sleep(2000); }
From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java
public static void main(String args[]) throws Exception { try {/*from www .j a v a2 s. c o m*/ // Perform setup operations if (log.isDebugEnabled()) { log.debug("Processing command line options"); } Map options = options(args); String dtd = (String) options.get("--dtd"); if (log.isDebugEnabled()) { log.debug("Configuring digester instance with public identifiers and DTD '" + dtd + "'"); } StringTokenizer st = new StringTokenizer(dtd, "|"); int arrayLen = st.countTokens(); if (arrayLen == 0) { // PENDING I18n throw new Exception("No DTDs specified"); } String[] dtds = new String[arrayLen]; int i = 0; while (st.hasMoreTokens()) { dtds[i] = st.nextToken(); i++; } directories((String) options.get("--dir")); Digester digester = digester(dtds, false, true, false); String config = (String) options.get("--config"); if (log.isDebugEnabled()) { log.debug("Parsing configuration file '" + config + "'"); } fcb = parse(digester, config); if (log.isInfoEnabled()) { log.info("Generating HTML component classes"); } // Generate render-kit documentation // copy the static files to the output area copyResourceToFile("com/sun/faces/generate/facesdoc/index.html", new File(directory, "index.html")); copyResourceToFile("com/sun/faces/generate/facesdoc/stylesheet.css", new File(directory, "stylesheet.css")); generateAllRenderersFrame(); generateRenderKitSummary(); generateRenderersDocs(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:com.heliosapm.benchmarks.json.JSONUnmarshalling.java
/** * @param args//w w w .ja va2 s . co m */ public static void main(String[] args) { final Map<String, ChannelBuffer> bufferMap = DIRECT_DATA_BUFFERS; log("JSON Test"); InputStream is = null; for (String sample : DATA) { try { final String jsonText = bufferMap.get(sample).duplicate().toString(UTF8); Person[] p = parseToObject(jsonText, Person[].class); log("Parsed STRING [%s] to objects: %s", sample, p.length); p = parseToObject(bufferMap.get(sample).duplicate(), Person[].class); log("Parsed BUFFER [%s] to objects: %s", sample, p.length); String s = serializeToString(p); log("Serialized to STRING [%s], size: %s", sample, s.length()); ChannelBuffer c = serializeToBuffer(heapFactory, p); log("Serialized to Heap Buffer [%s], size: %s", sample, c.readableBytes()); c = serializeToBuffer(directFactory, p); log("Serialized to Direct Buffer [%s], size: %s", sample, c.readableBytes()); } catch (Exception ex) { throw new RuntimeException("Failed to process string sample [" + sample + "]", ex); } finally { if (is != null) try { is.close(); } catch (Exception x) { /* No Op */} } } }
From source file:com.hortonworks.registries.storage.tool.sql.TablesInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH) .desc("Root directory of script path").build()); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH) .desc("Mysql client jar url to download").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CREATE.toString()) .desc("Run sql migrations from scatch").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.DROP.toString()) .desc("Drop all the tables in the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CHECK_CONNECTION.toString()) .desc("Check the connection for configured data source").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.MIGRATE.toString()) .desc("Execute schema migration from last check point").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.INFO.toString()) .desc("Show the status of the schema migration compared to the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.VALIDATE.toString()) .desc("Validate the target database changes with the migration scripts").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.REPAIR.toString()).desc( "Repairs the DATABASE_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script") .build());/*from www .j ava2 s . c om*/ options.addOption(Option.builder().hasArg(false).longOpt(DISABLE_VALIDATE_ON_MIGRATE) .desc("Disable flyway validation checks while running migrate").build()); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) { usage(options); System.exit(1); } boolean isSchemaMigrationOptionSpecified = false; SchemaMigrationOption schemaMigrationOptionSpecified = null; for (SchemaMigrationOption schemaMigrationOption : SchemaMigrationOption.values()) { if (commandLine.hasOption(schemaMigrationOption.toString())) { if (isSchemaMigrationOptionSpecified) { System.out.println( "Only one operation can be execute at once, please select one of 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection'."); System.exit(1); } isSchemaMigrationOptionSpecified = true; schemaMigrationOptionSpecified = schemaMigrationOption; } } if (!isSchemaMigrationOptionSpecified) { System.out.println( "One of the option 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection' must be specified to execute."); System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); StorageProviderConfiguration storageProperties; Map<String, Object> conf; try { conf = Utils.readConfig(confFilePath); StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader(); storageProperties = confReader.readStorageConfig(conf); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } String bootstrapDirPath = null; try { bootstrapDirPath = System.getProperty("bootstrap.dir"); Proxy proxy = Proxy.NO_PROXY; String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL); String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME); String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD); if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) { URL url = new URL(httpProxyUrl); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())); if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) { Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername, httpProxyPassword)); } } MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy); } catch (Exception e) { System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } boolean disableValidateOnMigrate = commandLine.hasOption(DISABLE_VALIDATE_ON_MIGRATE); if (disableValidateOnMigrate) { System.out.println("Disabling validation on schema migrate"); } SchemaMigrationHelper schemaMigrationHelper = new SchemaMigrationHelper( SchemaFlywayFactory.get(storageProperties, scriptRootPath, !disableValidateOnMigrate)); try { schemaMigrationHelper.execute(schemaMigrationOptionSpecified); System.out .println(String.format("\"%s\" option successful", schemaMigrationOptionSpecified.toString())); } catch (Exception e) { System.err.println( String.format("\"%s\" option failed : %s", schemaMigrationOptionSpecified.toString(), e)); System.exit(1); } }
From source file:io.dockstore.client.cli.Client.java
public static void main(String[] argv) { List<String> args = new ArrayList<>(Arrays.asList(argv)); if (flag(args, "--debug") || flag(args, "--d")) { DEBUG.set(true);/*ww w. j a va2s. c o m*/ } // user home dir String userHome = System.getProperty("user.home"); try { String configFile = optVal(args, "--config", userHome + File.separator + ".dockstore" + File.separator + "config"); InputStreamReader f = new InputStreamReader(new FileInputStream(configFile), Charset.defaultCharset()); YamlReader reader = new YamlReader(f); Object object = reader.read(); Map map = (Map) object; // pull out the variables from the config String token = (String) map.get("token"); String serverUrl = (String) map.get("server-url"); if (token == null) { err("The token is missing from your config file."); System.exit(GENERIC_ERROR); } if (serverUrl == null) { err("The server-url is missing from your config file."); System.exit(GENERIC_ERROR); } ApiClient defaultApiClient; defaultApiClient = Configuration.getDefaultApiClient(); defaultApiClient.addDefaultHeader("Authorization", "Bearer " + token); defaultApiClient.setBasePath(serverUrl); containersApi = new ContainersApi(defaultApiClient); usersApi = new UsersApi(defaultApiClient); defaultApiClient.setDebugging(DEBUG.get()); if (isHelp(args, true)) { out(""); out("HELP FOR DOCKSTORE"); out("------------------"); out("See https://www.dockstore.org for more information"); out(""); out("Possible sub-commands include:"); out(""); out(" list : lists all the containers registered by the user "); out(""); out(" search <pattern> : allows a user to search for all containers that match the criteria"); out(""); out(" publish : register a container in the dockstore"); out(""); out(" manual_publish : register a Docker Hub container in the dockstore"); out(""); out(" info <container> : print detailed information about a particular container"); out(""); out(" cwl <container> : returns the Common Workflow Language tool definition for this Docker image "); out(" which enables integration with Global Alliance compliant systems"); out(""); out(" refresh : updates your list of containers stored on Dockstore"); out("------------------"); out(""); out("Flags:"); out(" --debug Print debugging information"); out(" --version Print dockstore's version"); out(" --config <file> Override config file"); } else { try { // check user info after usage so that users can get usage without live webservice user = usersApi.getUser(); if (user == null) { throw new NotFoundException("User not found"); } String cmd = args.remove(0); if (null != cmd) { switch (cmd) { case "-v": case "--version": kill("dockstore: version information is provided by the wrapper script."); break; case "list": list(args); break; case "search": search(args); break; case "publish": publish(args); break; case "manual_publish": manualPublish(args); break; case "info": info(args); break; case "cwl": cwl(args); break; case "refresh": refresh(args); break; case "dev": dev(args); break; default: invalid(cmd); break; } } } catch (Kill k) { System.exit(GENERIC_ERROR); } } } catch (IOException | NotFoundException | ApiException ex) { out("Exception: " + ex); System.exit(GENERIC_ERROR); } catch (ProcessingException ex) { out("Could not connect to Dockstore web service: " + ex); System.exit(CONNECTION_ERROR); } }
From source file:com.aistor.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????//w ww . j a v a 2 s.c o m // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.aistor.modules"; String moduleName = "factory"; // ???sys String subModuleName = ""; // ????? String className = "product"; // ??user String classAuthor = "Zaric"; // Zaric String functionName = "?"; // ?? // ??? Boolean isEnable = false; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; String classPath = new DefaultResourceLoader().getResource("").getFile().getPath(); String templatePath = classPath.replace( separator + "webapp" + separator + "WEB-INF" + separator + "classes", separator + "java" + separator + "com" + separator + "aistor" + separator + "modules"); String javaPath = classPath.replace(separator + "webapp" + separator + "WEB-INF" + separator + "classes", separator + "java" + separator + (StringUtils.lowerCase(packageName)).replace(".", separator)); String viewPath = classPath.replace(separator + "classes", separator + "views"); // ??? Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading( new File(templatePath.replace("modules", "generate" + separator + "template"))); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", StringUtils.substringAfterLast(model.get("packageName"), ".") + "/" + model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info(filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info(filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info(filePath); // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info(filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info(filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info(filePath); logger.info("????"); }