List of usage examples for org.apache.commons.lang StringUtils substringBetween
public static String substringBetween(String str, String open, String close)
Gets the String that is nested in between two Strings.
From source file:de.fme.topx.component.TopXSearchComponent.java
/** * reads the display path, the sitename and sitepath for correct linking in * ui//from ww w.j a v a 2 s . c o m * * @param nodeRef * @param newNode */ private void setPathAttributes(NodeRef nodeRef, Node newNode) { Path path = getNodeService().getPath(nodeRef); String displayPath = path.toDisplayPath(nodeService, permissionService); newNode.setDisplayPath(displayPath); String pathCutted = StringUtils.substringAfter(StringUtils.substringAfter(displayPath, "/"), "/"); if (pathCutted.startsWith("Sites/")) { String siteName = StringUtils.substringBetween(displayPath, "Sites/", "/"); newNode.setSiteName(siteName); String documentPath = StringUtils.substringAfter(displayPath, "Sites/" + siteName + "/documentLibrary/"); String sitePath = StringUtils.substringBeforeLast(documentPath, "/"); newNode.setSitePath(sitePath); } String parentNodeRef = getPrimaryParent(nodeRef); newNode.setParentNodeRef(parentNodeRef); }
From source file:io.ecarf.core.utils.LogParser.java
/** * Dictionary/*from w w w.j a va 2s.c om*/ * @param dStats * @param line */ private void extractDictionaryStats(DictionaryStats dStats, String line) { if (line.contains(MEM_USE)) { double[] values = this.extractAndGetMemoryDictionaryItems(line); double memory = values[0]; dStats.memoryFootprint.add(memory); if (values[1] > 0) { dStats.memoryUsage.add(new MemUsage((int) values[1], memory)); } } else if (line.contains(DIC_SIZE)) { int size = this.extractDictionarySize(line); dStats.memoryUsage.add(new MemUsage(size, dStats.getLatestMemoryUsage())); } if (line.contains(DIC_ASSEMBLE)) { //Successfully assembled dictionary with size: 53550116, max resourceId: 54291281, memory usage: 14.449545934796333GB, timer: 5.010 min dStats.items = Integer.parseInt(StringUtils.substringBetween(line, DIC_ASSEMBLE, MAX_RES_ID)); dStats.maxResourceId = Integer.parseInt(StringUtils.substringBetween(line, MAX_RES_ID, MEM_USE)); dStats.assemble = this.extractAndGetTimer(line, TIMER_PREFIX); } /** * term.dictionary.TermDictionaryConcurrent - Creating non concurrent dictionary, memory usage: 11.166048146784306 term.dictionary.TermDictionaryConcurrent - #TIMER finished creating non concurrent dictionary, memory usage: 13.966991074383259GB, timer: 1.577 min processor.dictionary.AssembleDictionaryTask - Successfully created non concurrent dictionary for serialization, memory usage: 13.966991074383259GB, timer: 6.992 min core.utils.Utils - Serializing object of class: class io.ecarf.core.term.dictionary.TermDictionaryCore to file: /tmp/dbpedia_dictionary_8c.kryo.gz, with compress = true term.dictionary.TermDictionary - TIMER# serialized dictionary to file: /tmp/dbpedia_dictionary_8c.kryo.gz, in: 3.274 min processor.dictionary.AssembleDictionaryTask - Successfully serialized dictionary with size: 53550116, memory usage: 13.964397609233856GB, timer: 10.27 min */ if (line.contains(NON_CON_TIMER)) { dStats.nonConcurrent = this.extractAndGetTimer(line, TIMER_PREFIX); } else if (line.contains(TERM_DIC_TIMER)) { dStats.serialize = this.extractAndGetTimer(line, " in:"); } else if (line.contains(SCHEMA_TERMS)) { //processor.dictionary.AssembleDictionaryTask - Schema terms added to the dictionary, final size: 53550784 , memory usage: 14.449545934796333GB dStats.itemsAfterSchema = Integer .parseInt(StringUtils.trim(StringUtils.substringBetween(line, SCHEMA_TERMS, MEM_USE))); } //processor.dictionary.AssembleDictionarySubTask - Processing: 1718527 term parts , memory usage: 17.80723436176777GB, timer: 4.839 s if (line.contains(TERM_PARTS)) { dStats.parts += Integer .parseInt(StringUtils.trim(StringUtils.substringBetween(line, PROCESSING, TERM_PARTS))); } }
From source file:autoInsurance.BeiJPingAnImpl.java
public String queryBaodhByToubdh(String in) { // TODO Auto-generated method stub JSONObject jsonObj = JSONObject.fromObject(in); String toubdh = jsonObj.getString("toubdh"); String url = "https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/workbench/qtWaitTaskInfo"; String postData = "{\"voucherType\":\"1\",\"voucherNo\":\"" + toubdh + "\",\"inputById\":\"LGXY-00001\",\"departmentCode\":\"20119\",\"lowDepartment\":true,\"applicantType\":\"\",\"coinsuranceMark\":\"\"}"; String retStr = httpClientUtil.doPost(url, postData, charset); System.out.println(retStr);//from www . j av a2s . c o m url = "https://icorepnbs.pingan.com.cn/icore_pnbs/bussiness/workbench/templates/view/popup/quotationDetail.tpl?voucherNo=" + toubdh + "&isFromCNBS=false&moduleType=detail&_u=" + HttpClientUtil.digestMap.get(toubdh); retStr = httpClientUtil.doGet(url, new HashMap(), charset); System.out.println(retStr); Document doc = Jsoup.parse(retStr); Element elm = doc.getElementsByAttributeValue("language", "javascript").get(0); String js = elm.data(); System.out.println(js); String quotationDTO = StringUtils.substringBetween(js, "var quotationDTO = ", " ;"); System.out.println(quotationDTO); Map<String, String> outMap = new HashMap<String, String>(); // outMap.put("proposalNo", jObj2.getString("proposalNo")); // outMap.put("policyNo", jObj2.getString("policyNo")); // outMap.put("insuredName", jObj2.getString("insuredName")); // //outMap.put("startDate", jObj2.getString("startDate")); // outMap.put("startDate", timeStamp2Date("" + (Long) ((Map) jObj2.get("startDate")).get("time"), "yyyy-M-d")); return JSONObject.fromObject(outMap).toString(); }
From source file:io.ecarf.core.utils.LogParser.java
/** * // www . j av a2s.co m * @throws FileNotFoundException * @throws IOException */ private void parse() throws FileNotFoundException, IOException { System.out.println("Parsing log files: "); for (String file : files) { boolean coordinator = file.contains(COORDINATOR); Stats stats; Stats dStats = null; List<Double> bigQuerySave = null; List<Double> bigQueryLoad = null; List<Double> bigQueryQueriesElapsed = null; if (coordinator) { stats = new CoordinatorStats(); this.coordinators.add((CoordinatorStats) stats); } else { stats = new ProcessorStats(); this.processors.add((ProcessorStats) stats); bigQuerySave = new ArrayList<>(); bigQueryLoad = new ArrayList<>(); bigQueryQueriesElapsed = new ArrayList<>(); dStats = new DictionaryStats(); dStats.filename = StringUtils.substringAfterLast(file, "/"); this.dictionaries.add((DictionaryStats) dStats); } stats.filename = StringUtils.substringAfterLast(file, "/"); //System.out.println(file); String line = null; int rows = 0; int inferred = 0; try (BufferedReader r = new BufferedReader(new FileReader(file))) { do { line = r.readLine(); if (line != null) { if (line.indexOf(TIMER) > -1) { this.parseTaskTimer(stats, line, coordinator); } else if (line.indexOf(ELAPSED_JOB) > -1 && coordinator) { ((CoordinatorStats) stats).endToEnd = this.extractAndGetTimer(line, ELAPSED_JOB); } else if (line.indexOf(REASON_TASK_SUMMARY) > -1) { this.extractProcessorReasoningStats(line, (ProcessorStats) stats); } else if (line.indexOf(BIGQUERY_SAVE) > -1) { bigQuerySave.add(this.extractAndGetTimer(line, BIGQUERY_SAVE, true)); } else if (line.contains(BIGQUERY_ROWS)) { rows = Integer.parseInt(StringUtils.substringBetween(line, DOWNLOADING, BIGQUERY_ROWS)); } else if (line.indexOf(BIGQUERY_JOB_ELAPSED) > -1) { double value = this.extractAndGetTimer(line, BIGQUERY_JOB_ELAPSED, true); r.readLine(); String line1 = r.readLine(); if (line1 != null && line1.indexOf("\"configuration\" : {") > -1) { line1 = r.readLine(); if (line1.indexOf("\"load\" : {") > -1) { bigQueryLoad.add(value); if (inferred > 0) { this.bigQueryImport.add(new Rows(inferred, value)); inferred = 0; } } else if (line1.indexOf("\"query\" : {") > -1) { // fast forward to this line //"recordsWritten" : "0", do { line1 = r.readLine(); } while (line1 != null && !line1.contains("\"recordsWritten\" :")); if (line1 != null && !line1.contains("\"recordsWritten\" : \"0\",")) { if (value > 0) { bigQueryQueriesElapsed.add(value); } } } else if (line1.indexOf("\"extract\" : {") > -1) { if (rows > 0) { this.bigQueryExport.add(new Rows(rows, value)); rows = 0; } } } } else if (line.indexOf(ASSEMBLE_DICTIONARY_SUBTASK) > -1 || line.contains(ASSEMBLE_DICT_TASK) || line.contains(TERM_DICT_CON) || line.contains(TERM_DICT)) { this.extractDictionaryStats((DictionaryStats) dStats, line); } else if (coordinator) { if (line.contains(JSON_NUM_VM)) { //"numberOfProcessors": 8.0 ((CoordinatorStats) stats).numOfProcessors = (int) Double .parseDouble(StringUtils.substringAfter(line, JSON_NUM_VM + " ")); } else if (line.contains(JSON_VM_TYPE)) { //"vmType": "n1-standard-2", ((CoordinatorStats) stats).vmType = StringUtils.substringBetween(line, JSON_VM_TYPE + " \"", "\","); } } else if (!coordinator && line.contains(FILE_ITEMS)) { // line occurs twice per file, so only add if hasn't been added yet if (((ProcessorStats) stats).fileItems.isEmpty()) { String items = StringUtils.substringAfter(line, FILE_ITEMS); //processor.files.ProcessFilesTask - Processing files: [revision_ids_en.nt.gz, revision_uris_en.nt.gz, yago_taxonomy.nt.gz, interlanguage_links_chapters_en.nt.gz, geo_coordinates_en.nt.gz] List<String> fileItems = Lists .newArrayList(StringUtils.substringBetween(items, "[", "]").split(", ")); ((ProcessorStats) stats).fileItems.addAll(fileItems); } } else if (line.contains(DICT_DOWNLOAD)) { //task.processor.ProcessLoadTask - Loading the dictionary from file: /tmp/dbpedia_dictionary.kryo.gz, memory usage: 1.8702433556318283GB, timer: 9.671 s ((ProcessorStats) stats).dictionaryDowload = this.extractAndGetTimer(line, TIMER_PREFIX, true); double[] values = this.extractAndGetMemoryDictionaryItems(line); ((ProcessorStats) stats).dictionaryMemBefore = values[0]; } else if (line.contains(DICT_LOAD)) { //task.processor.ProcessLoadTask - Dictionary loaded successfully, memory usage: 3.9780617877840996GB, timer: 1.160 min ((ProcessorStats) stats).dictionaryLoad = this.extractAndGetTimer(line, TIMER_PREFIX); double[] values = this.extractAndGetMemoryDictionaryItems(line); ((ProcessorStats) stats).dictionaryMemAfter = values[0]; } if (line.contains(BIGQUERY_INF)) { //System.out.println(line); if (line.contains("DoReasonTask8")) { inferred = Integer .parseInt(StringUtils.substringBetween(line, INSERTING8, BIGQUERY_INF)); } else { inferred = Integer .parseInt(StringUtils.substringBetween(line, INSERTING, BIGQUERY_INF)); } } } } while (line != null); } if (!coordinator) { ((ProcessorStats) stats).bigQuerySave = this.sum(bigQuerySave); ((ProcessorStats) stats).bigQueryInsert = this.sum(bigQueryLoad); if (!bigQueryQueriesElapsed.isEmpty()) { ((ProcessorStats) stats).bigQueryAverageQuery = this.sum(bigQueryQueriesElapsed) / bigQueryQueriesElapsed.size(); } } } //if(!this.jobElapsedTimes.isEmpty()) { // this.coordinators.get(0).endToEnd = this.jobElapsedTimes.get(this.jobElapsedTimes.size() - 1); //} }
From source file:com.hangum.tadpole.mongodb.core.ext.editors.javascript.ServerSideJavaScriptEditor.java
/** * execute javascript eval /*from w ww . j a v a2 s . c o m*/ * * @param strJavaScript */ private void executeEval(String strJavaScript) { Object[] arryArgs = null;//{25, 34}; logger.debug("[original javascript]" + strJavaScript); // argument String strArgument = StringUtils.substringBetween(strJavaScript, "function", "{"); if (strArgument != null) { int intArgumentCount = StringUtils.countMatches(strArgument, ",") + 1; EvalInputDialog dialog = new EvalInputDialog(getSite().getShell(), intArgumentCount); if (Dialog.OK == dialog.open()) { arryArgs = dialog.getInputObject(); try { Object objResult = MongoDBQuery.executeEval(getUserDB(), strJavaScript, arryArgs); textResultJavaScript.setText(objResult == null ? "" : objResult.toString()); } catch (Exception e) { textResultJavaScript.setText(""); logger.error("execute javascript", e); //$NON-NLS-1$ Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$ ExceptionDetailsErrorDialog.openError(getSite().getShell(), Messages.get().Error, Messages.get().MainEditor_19, errStatus); //$NON-NLS-1$ } } } }
From source file:bammerbom.ultimatecore.spongeapi.commands.CmdPlugin.java
@Override public void run(final CommandSender cs, String label, final String[] args) { //help/*from w w w .j av a 2 s . c o m*/ if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) { r.sendMes(cs, "noPermissions"); return; } cs.sendMessage(TextColors.GOLD + "================================"); r.sendMes(cs, "pluginHelpLoad"); r.sendMes(cs, "pluginHelpUnload"); r.sendMes(cs, "pluginHelpEnable"); r.sendMes(cs, "pluginHelpDisable"); r.sendMes(cs, "pluginHelpReload"); r.sendMes(cs, "pluginHelpReloadall"); r.sendMes(cs, "pluginHelpDelete"); r.sendMes(cs, "pluginHelpUpdate"); r.sendMes(cs, "pluginHelpCommands"); r.sendMes(cs, "pluginHelpList"); r.sendMes(cs, "pluginHelpUpdatecheck"); r.sendMes(cs, "pluginHelpUpdatecheckall"); r.sendMes(cs, "pluginHelpDownload"); r.sendMes(cs, "pluginHelpSearch"); cs.sendMessage(TextColors.GOLD + "================================"); } //load else if (args[0].equalsIgnoreCase("load")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpLoad"); return; } File f = new File(r.getUC().getDataFolder().getParentFile(), args[1].endsWith(".jar") ? args[1] : args[1] + ".jar"); if (!f.exists()) { r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar"); return; } if (!f.canRead()) { r.sendMes(cs, "pluginFileNoReadAcces"); return; } Plugin p; try { p = pm.loadPlugin(f); if (p == null) { r.sendMes(cs, "pluginLoadFailed"); return; } pm.enablePlugin(p); } catch (UnknownDependencyException ex) { r.sendMes(cs, "pluginLoadMissingDependency", "%Message", ex.getMessage() != null ? ex.getMessage() : ""); ex.printStackTrace(); return; } catch (InvalidDescriptionException ex) { r.sendMes(cs, "pluginLoadInvalidDescription"); ex.printStackTrace(); return; } catch (InvalidPluginException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } if (p.isEnabled()) { r.sendMes(cs, "pluginLoadSucces"); } else { r.sendMes(cs, "pluginLoadFailed"); } } //unload else if (args[0].equalsIgnoreCase("unload")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUnload"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } List<String> deps = PluginUtil.getDependedOnBy(p.getName()); if (!deps.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String dep : deps) { sb.append(r.neutral); sb.append(dep); sb.append(TextColors.RESET); sb.append(", "); } r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4)); return; } r.sendMes(cs, "pluginUnloadUnloading"); PluginUtil.unregisterAllPluginCommands(p.getName()); HandlerList.unregisterAll(p); Bukkit.getServicesManager().unregisterAll(p); Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p); Bukkit.getServer().getScheduler().cancelTasks(p); pm.disablePlugin(p); PluginUtil.removePluginFromList(p); r.sendMes(cs, "pluginUnloadUnloaded"); } //enable else if (args[0].equalsIgnoreCase("enable")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpEnable"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (p.isEnabled()) { r.sendMes(cs, "pluginAlreadyEnabled"); return; } pm.enablePlugin(p); if (p.isEnabled()) { r.sendMes(cs, "pluginEnableSucces"); } else { r.sendMes(cs, "pluginEnableFail"); } } //disable else if (args[0].equalsIgnoreCase("disable")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDisable"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (!p.isEnabled()) { r.sendMes(cs, "pluginNotEnabled"); return; } List<String> deps = PluginUtil.getDependedOnBy(p.getName()); if (!deps.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String dep : deps) { sb.append(r.neutral); sb.append(dep); sb.append(TextColors.RESET); sb.append(", "); } r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4)); return; } pm.disablePlugin(p); if (!p.isEnabled()) { r.sendMes(cs, "pluginDisableSucces"); } else { r.sendMes(cs, "pluginDisableFailed"); } } //reload else if (args[0].equalsIgnoreCase("reload")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpReload"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (!p.isEnabled()) { r.sendMes(cs, "pluginNotEnabled"); return; } pm.disablePlugin(p); pm.enablePlugin(p); r.sendMes(cs, "pluginReloadMessage"); } //reloadall else if (args[0].equalsIgnoreCase("reloadall")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) { r.sendMes(cs, "noPermissions"); return; } for (Plugin p : pm.getPlugins()) { pm.disablePlugin(p); pm.enablePlugin(p); } r.sendMes(cs, "pluginReloadallMessage"); } //delete else if (args[0].equalsIgnoreCase("delete")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDelete"); return; } String del = args[1]; if (!del.endsWith(".jar")) { del = del + ".jar"; } if (del.contains(File.separator)) { r.sendMes(cs, "pluginDeleteDontLeavePluginFolder"); return; } File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del); if (!f.exists()) { r.sendMes(cs, "pluginFileNotFound", "%File", del); return; } if (f.delete()) { r.sendMes(cs, "pluginDeleteSucces"); } else { r.sendMes(cs, "pluginDeleteFailed"); } } //commands else if (args[0].equalsIgnoreCase("commands")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpCommands"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } Map<String, Map<String, Object>> cmds = p.getDescription().getCommands(); if (cmds == null) { r.sendMes(cs, "pluginCommandsNoneRegistered"); return; } String command = "plugin " + p.getName(); String pageStr = args.length > 2 ? args[2] : null; UText input = new TextInput(cs); UText output; if (input.getLines().isEmpty()) { if ((r.isInt(pageStr)) || (pageStr == null)) { output = new PluginCommandsInput(cs, args[1].toLowerCase()); } else { r.sendMes(cs, "pluginCommandsPageNotNumber"); return; } } else { output = input; } TextPager pager = new TextPager(output); pager.showPage(pageStr, null, command, cs); } //update else if (args[0].equalsIgnoreCase("update")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUpdate"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain() .getCodeSource().getLocation(); File f; try { f = new File(u.toURI()); } catch (URISyntaxException e) { f = new File(u.getPath()); } PluginUtil.unregisterAllPluginCommands(p.getName()); HandlerList.unregisterAll(p); Bukkit.getServicesManager().unregisterAll(p); Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p); Bukkit.getServer().getScheduler().cancelTasks(p); pm.disablePlugin(p); PluginUtil.removePluginFromList(p); try { Plugin p2 = pm.loadPlugin(f); if (p2 == null) { r.sendMes(cs, "pluginLoadFailed"); return; } pm.enablePlugin(p2); } catch (UnknownDependencyException ex) { r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage()); ex.printStackTrace(); return; } catch (InvalidDescriptionException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } catch (InvalidPluginException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } } //list else if (args[0].equalsIgnoreCase("list")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) { r.sendMes(cs, "noPermissions"); return; } r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList()); } //info else if (args[0].equalsIgnoreCase("info")) { if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpInfo"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } PluginDescriptionFile pdf = p.getDescription(); if (pdf == null) { r.sendMes(cs, "pluginLoadInvalidDescription"); return; } String version = pdf.getVersion(); List<String> authors = pdf.getAuthors(); String site = pdf.getWebsite(); List<String> softDep = pdf.getSoftDepend(); List<String> dep = pdf.getDepend(); String name = pdf.getName(); String desc = pdf.getDescription(); if (name != null && !name.isEmpty()) { r.sendMes(cs, "pluginInfoName", "%Name", name); } if (version != null && !version.isEmpty()) { r.sendMes(cs, "pluginInfoVersion", "%Version", version); } if (site != null && !site.isEmpty()) { r.sendMes(cs, "pluginInfoWebsite", "%Website", site); } if (desc != null && !desc.isEmpty()) { r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", "")); } if (authors != null && !authors.isEmpty()) { r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author", StringUtil.join(TextColors.RESET + ", " + r.neutral, authors)); } if (softDep != null && !softDep.isEmpty()) { r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps", StringUtil.join(TextColors.RESET + ", " + r.neutral, softDep)); } if (dep != null && !dep.isEmpty()) { r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(TextColors.RESET + ", " + r.neutral, dep)); } r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no"))); } //updatecheck else if (args[0].equalsIgnoreCase("updatecheck")) { if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUpdatecheck"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } final String tag; try { tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8"); } catch (UnsupportedEncodingException ex) { r.sendMes(cs, "pluginNoUTF8"); return; } if (p.getDescription() == null) { r.sendMes(cs, "pluginLoadInvalidDescription"); return; } final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet") : p.getDescription().getVersion(); Runnable ru = new Runnable() { @Override public void run() { try { String n = ""; String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss"; URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); n = firstNodes.item(0).getNodeValue(); } r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + ""); r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + ""); } catch (Exception ex) { ex.printStackTrace(); r.sendMes(cs, "pluginUpdatecheckFailed"); } } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } //updatecheckall else if (args[0].equalsIgnoreCase("updatecheckall")) { if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } final Runnable ru = new Runnable() { @Override public void run() { int a = 0; for (Plugin p : pm.getPlugins()) { if (p.getDescription() == null) { continue; } String version = p.getDescription().getVersion(); if (version == null) { continue; } String n = ""; try { String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + p.getName().toLowerCase() + "/files.rss"; URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); n = firstNodes.item(0).getNodeValue(); a++; } } catch (Exception e) { continue; } if (n.contains(version)) { continue; } r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin", p.getName()); } r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a); } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } //download else if (args[0].equalsIgnoreCase("download")) { if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDownload"); cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core" + r.negative + "/"); return; } final Runnable ru = new Runnable() { @Override public void run() { String tag = args[1]; r.sendMes(cs, "pluginDownloadGettingtag"); String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss"; String file; try { final URL url = new URL(pluginUrlString); final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); final NodeList nodes = doc.getElementsByTagName("item"); final Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { final Element firstElement = (Element) firstNode; final NodeList firstElementTagName = firstElement.getElementsByTagName("link"); final Element firstNameElement = (Element) firstElementTagName.item(0); final NodeList firstNodes = firstNameElement.getChildNodes(); final String link = firstNodes.item(0).getNodeValue(); final URL dpage = new URL(link); final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream())); final StringBuilder content = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) { content.append(inputLine); } br.close(); file = StringUtils.substringBetween(content.toString(), "<li class=\"user-action user-action-download\"><span><a href=\"", "\">Download</a></span></li>"); } else { throw new Exception(); } } catch (Exception e) { r.sendMes(cs, "pluginDownloadInvalidtag"); cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core" + r.negative + "/"); return; } BufferedInputStream bis; final HttpURLConnection huc; try { huc = (HttpURLConnection) new URL(file).openConnection(); huc.setInstanceFollowRedirects(true); huc.connect(); bis = new BufferedInputStream(huc.getInputStream()); } catch (MalformedURLException e) { r.sendMes(cs, "pluginDownloadInvaliddownloadlink"); return; } catch (IOException e) { r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage()); return; } String[] urlParts = huc.getURL().toString().split("(\\\\|/)"); final String fileName = urlParts[urlParts.length - 1]; r.sendMes(cs, "pluginDownloadCreatingTemp"); File f = new File(System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID().toString() + File.separator + fileName); while (f.getParentFile().exists()) { f = new File(System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID().toString() + File.separator + fileName); } if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) { r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName); return; } f.getParentFile().mkdirs(); BufferedOutputStream bos; try { bos = new BufferedOutputStream(new FileOutputStream(f)); } catch (FileNotFoundException e) { r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir")); return; } int b; r.sendMes(cs, "pluginDownloadDownloading"); try { try { while ((b = bis.read()) != -1) { bos.write(b); } } finally { bos.flush(); bos.close(); } } catch (IOException e) { r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage()); return; } if (fileName.endsWith(".zip")) { r.sendMes(cs, "pluginDownloadDecompressing"); PluginUtil.decompress(f.getAbsolutePath(), f.getParent()); } String name = null; for (File fi : PluginUtil.listFiles(f.getParentFile())) { if (!fi.getName().endsWith(".jar")) { continue; } if (name == null) { name = fi.getName(); } r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName()); try { Files.move(fi, new File( r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName())); } catch (IOException e) { r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage()); } } PluginUtil.deleteDirectory(f.getParentFile()); r.sendMes(cs, "pluginDownloadSucces", "%File", fileName); } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } else if (args[0].equalsIgnoreCase("search")) { if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } int page = 1; if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpSearch"); return; } Boolean b = false; if (r.checkArgs(args, 2)) { try { page = Integer.parseInt(args[args.length - 1]); b = true; } catch (NumberFormatException ignored) { } } String search = r.getFinalArg(args, 1); if (b) { search = new StringBuilder(new StringBuilder(search).reverse().toString() .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString(); } try { search = URLEncoder.encode(search, "UTF-8"); } catch (UnsupportedEncodingException e) { r.sendMes(cs, "pluginNoUTF8"); return; } final URL u; try { u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page); } catch (MalformedURLException e) { r.sendMes(cs, "pluginSearchMalformedTerm"); return; } final Runnable ru = new Runnable() { @Override public void run() { final BufferedReader br; try { br = new BufferedReader(new InputStreamReader(u.openStream())); } catch (IOException e) { r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage()); return; } String inputLine; StringBuilder content = new StringBuilder(); try { while ((inputLine = br.readLine()) != null) { content.append(inputLine); } } catch (IOException e) { r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage()); return; } r.sendMes(cs, "pluginSearchHeader"); for (int i = 0; i < 20; i++) { final String project = StringUtils.substringBetween(content.toString(), " row-joined-to-next\">", "</tr>"); final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">", "</td>"); if (base == null) { if (i == 0) { r.sendMes(cs, "pluginSearchNoResults"); } return; } final Pattern p = Pattern .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>"); final Matcher m = p.matcher(base); if (!m.find()) { if (i == 0) { r.sendMes(cs, "pluginSearchNoResults"); } return; } final String name = m.group(2).replaceAll("</?\\w+>", ""); final String tag = m.group(1); final int beglen = StringUtils.substringBefore(content.toString(), base).length(); content = new StringBuilder(content.substring(beglen + project.length())); r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag); } } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } else { cs.sendMessage(TextColors.GOLD + "================================"); r.sendMes(cs, "pluginHelpLoad"); r.sendMes(cs, "pluginHelpUnload"); r.sendMes(cs, "pluginHelpEnable"); r.sendMes(cs, "pluginHelpDisable"); r.sendMes(cs, "pluginHelpReload"); r.sendMes(cs, "pluginHelpReloadall"); r.sendMes(cs, "pluginHelpDelete"); r.sendMes(cs, "pluginHelpUpdate"); r.sendMes(cs, "pluginHelpCommands"); r.sendMes(cs, "pluginHelpList"); r.sendMes(cs, "pluginHelpUpdatecheck"); r.sendMes(cs, "pluginHelpUpdatecheckall"); r.sendMes(cs, "pluginHelpDownload"); r.sendMes(cs, "pluginHelpSearch"); cs.sendMessage(TextColors.GOLD + "================================"); } }
From source file:bammerbom.ultimatecore.bukkit.commands.CmdPlugin.java
@Override public void run(final CommandSender cs, String label, final String[] args) { //help//from w w w. jav a2 s . c o m if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) { r.sendMes(cs, "noPermissions"); return; } cs.sendMessage(ChatColor.GOLD + "================================"); r.sendMes(cs, "pluginHelpLoad"); r.sendMes(cs, "pluginHelpUnload"); r.sendMes(cs, "pluginHelpEnable"); r.sendMes(cs, "pluginHelpDisable"); r.sendMes(cs, "pluginHelpReload"); r.sendMes(cs, "pluginHelpReloadall"); r.sendMes(cs, "pluginHelpDelete"); r.sendMes(cs, "pluginHelpUpdate"); r.sendMes(cs, "pluginHelpCommands"); r.sendMes(cs, "pluginHelpList"); r.sendMes(cs, "pluginHelpUpdatecheck"); r.sendMes(cs, "pluginHelpUpdatecheckall"); r.sendMes(cs, "pluginHelpDownload"); r.sendMes(cs, "pluginHelpSearch"); cs.sendMessage(ChatColor.GOLD + "================================"); return; } //load else if (args[0].equalsIgnoreCase("load")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpLoad"); return; } File f = new File(r.getUC().getDataFolder().getParentFile(), args[1].endsWith(".jar") ? args[1] : args[1] + ".jar"); if (!f.exists()) { r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar"); return; } if (!f.canRead()) { r.sendMes(cs, "pluginFileNoReadAcces"); return; } Plugin p; try { p = pm.loadPlugin(f); if (p == null) { r.sendMes(cs, "pluginLoadFailed"); return; } pm.enablePlugin(p); } catch (UnknownDependencyException ex) { r.sendMes(cs, "pluginLoadMissingDependency", "%Message", ex.getMessage() != null ? ex.getMessage() : ""); ex.printStackTrace(); return; } catch (InvalidDescriptionException ex) { r.sendMes(cs, "pluginLoadInvalidDescription"); ex.printStackTrace(); return; } catch (InvalidPluginException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } if (p.isEnabled()) { r.sendMes(cs, "pluginLoadSucces"); } else { r.sendMes(cs, "pluginLoadFailed"); } return; } //unload else if (args[0].equalsIgnoreCase("unload")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUnload"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } List<String> deps = PluginUtil.getDependedOnBy(p.getName()); if (!deps.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String dep : deps) { sb.append(r.neutral); sb.append(dep); sb.append(ChatColor.RESET); sb.append(", "); } r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4)); return; } r.sendMes(cs, "pluginUnloadUnloading"); PluginUtil.unregisterAllPluginCommands(p.getName()); HandlerList.unregisterAll(p); Bukkit.getServicesManager().unregisterAll(p); Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p); Bukkit.getServer().getScheduler().cancelTasks(p); pm.disablePlugin(p); PluginUtil.removePluginFromList(p); r.sendMes(cs, "pluginUnloadUnloaded"); return; } //enable else if (args[0].equalsIgnoreCase("enable")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpEnable"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (p.isEnabled()) { r.sendMes(cs, "pluginAlreadyEnabled"); return; } pm.enablePlugin(p); if (p.isEnabled()) { r.sendMes(cs, "pluginEnableSucces"); } else { r.sendMes(cs, "pluginEnableFail"); } return; } //disable else if (args[0].equalsIgnoreCase("disable")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDisable"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (!p.isEnabled()) { r.sendMes(cs, "pluginNotEnabled"); return; } List<String> deps = PluginUtil.getDependedOnBy(p.getName()); if (!deps.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String dep : deps) { sb.append(r.neutral); sb.append(dep); sb.append(ChatColor.RESET); sb.append(", "); } r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4)); return; } pm.disablePlugin(p); if (!p.isEnabled()) { r.sendMes(cs, "pluginDisableSucces"); } else { r.sendMes(cs, "pluginDisableFailed"); } return; } //reload else if (args[0].equalsIgnoreCase("reload")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpReload"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } if (!p.isEnabled()) { r.sendMes(cs, "pluginNotEnabled"); return; } pm.disablePlugin(p); pm.enablePlugin(p); r.sendMes(cs, "pluginReloadMessage"); return; } //reloadall else if (args[0].equalsIgnoreCase("reloadall")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) { r.sendMes(cs, "noPermissions"); return; } for (Plugin p : pm.getPlugins()) { pm.disablePlugin(p); pm.enablePlugin(p); } r.sendMes(cs, "pluginReloadallMessage"); return; } //delete else if (args[0].equalsIgnoreCase("delete")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDelete"); return; } String del = args[1]; if (!del.endsWith(".jar")) { del = del + ".jar"; } if (del.contains(File.separator)) { r.sendMes(cs, "pluginDeleteDontLeavePluginFolder"); return; } File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del); if (!f.exists()) { r.sendMes(cs, "pluginFileNotFound", "%File", del); return; } if (f.delete()) { r.sendMes(cs, "pluginDeleteSucces"); } else { r.sendMes(cs, "pluginDeleteFailed"); } return; } //commands else if (args[0].equalsIgnoreCase("commands")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpCommands"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } Map<String, Map<String, Object>> cmds = p.getDescription().getCommands(); if (cmds == null) { r.sendMes(cs, "pluginCommandsNoneRegistered"); return; } String command = "plugin " + p.getName(); String pageStr = args.length > 2 ? args[2] : null; UText input = new TextInput(cs); UText output; if (input.getLines().isEmpty()) { if ((r.isInt(pageStr)) || (pageStr == null)) { output = new PluginCommandsInput(cs, args[1].toLowerCase()); } else { r.sendMes(cs, "pluginCommandsPageNotNumber"); return; } } else { output = input; } TextPager pager = new TextPager(output); pager.showPage(pageStr, null, command, cs); return; } //update else if (args[0].equalsIgnoreCase("update")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUpdate"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain() .getCodeSource().getLocation(); File f; try { f = new File(u.toURI()); } catch (URISyntaxException e) { f = new File(u.getPath()); } PluginUtil.unregisterAllPluginCommands(p.getName()); HandlerList.unregisterAll(p); Bukkit.getServicesManager().unregisterAll(p); Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p); Bukkit.getServer().getScheduler().cancelTasks(p); pm.disablePlugin(p); PluginUtil.removePluginFromList(p); try { Plugin p2 = pm.loadPlugin(f); if (p2 == null) { r.sendMes(cs, "pluginLoadFailed"); return; } pm.enablePlugin(p2); } catch (UnknownDependencyException ex) { r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage()); ex.printStackTrace(); return; } catch (InvalidDescriptionException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } catch (InvalidPluginException ex) { r.sendMes(cs, "pluginLoadFailed"); ex.printStackTrace(); return; } return; } //list else if (args[0].equalsIgnoreCase("list")) { if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) { r.sendMes(cs, "noPermissions"); return; } r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList()); return; } //info else if (args[0].equalsIgnoreCase("info")) { if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpInfo"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } PluginDescriptionFile pdf = p.getDescription(); if (pdf == null) { r.sendMes(cs, "pluginLoadInvalidDescription"); return; } String version = pdf.getVersion(); List<String> authors = pdf.getAuthors(); String site = pdf.getWebsite(); List<String> softDep = pdf.getSoftDepend(); List<String> dep = pdf.getDepend(); String name = pdf.getName(); String desc = pdf.getDescription(); if (name != null && !name.isEmpty()) { r.sendMes(cs, "pluginInfoName", "%Name", name); } if (version != null && !version.isEmpty()) { r.sendMes(cs, "pluginInfoVersion", "%Version", version); } if (site != null && !site.isEmpty()) { r.sendMes(cs, "pluginInfoWebsite", "%Website", site); } if (desc != null && !desc.isEmpty()) { r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", "")); } if (authors != null && !authors.isEmpty()) { r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author", StringUtil.join(ChatColor.RESET + ", " + r.neutral, authors)); } if (softDep != null && !softDep.isEmpty()) { r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps", StringUtil.join(ChatColor.RESET + ", " + r.neutral, softDep)); } if (dep != null && !dep.isEmpty()) { r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(ChatColor.RESET + ", " + r.neutral, dep)); } r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no"))); return; } //updatecheck else if (args[0].equalsIgnoreCase("updatecheck")) { if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpUpdatecheck"); return; } Plugin p = pm.getPlugin(args[1]); if (p == null) { r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]); return; } final String tag; try { tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8"); } catch (UnsupportedEncodingException ex) { r.sendMes(cs, "pluginNoUTF8"); return; } if (p.getDescription() == null) { r.sendMes(cs, "pluginLoadInvalidDescription"); return; } final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet") : p.getDescription().getVersion(); Runnable ru = new Runnable() { @Override public void run() { try { String n = ""; String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss"; URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); n = firstNodes.item(0).getNodeValue(); } r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + ""); r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + ""); } catch (Exception ex) { ex.printStackTrace(); r.sendMes(cs, "pluginUpdatecheckFailed"); } } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); return; } //updatecheckall else if (args[0].equalsIgnoreCase("updatecheckall")) { if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } final Runnable ru = new Runnable() { @Override public void run() { int a = 0; for (Plugin p : pm.getPlugins()) { if (p.getDescription() == null) { continue; } String version = p.getDescription().getVersion(); if (version == null) { continue; } String n = ""; try { String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + p.getName().toLowerCase() + "/files.rss"; URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); n = firstNodes.item(0).getNodeValue(); a++; } } catch (Exception e) { continue; } if (n.contains(version)) { continue; } r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin", p.getName()); } r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a); return; } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); return; } //download else if (args[0].equalsIgnoreCase("download")) { if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpDownload"); cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core" + r.negative + "/"); return; } final Runnable ru = new Runnable() { @Override public void run() { String tag = args[1]; r.sendMes(cs, "pluginDownloadGettingtag"); String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss"; String file; try { final URL url = new URL(pluginUrlString); final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); final NodeList nodes = doc.getElementsByTagName("item"); final Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { final Element firstElement = (Element) firstNode; final NodeList firstElementTagName = firstElement.getElementsByTagName("link"); final Element firstNameElement = (Element) firstElementTagName.item(0); final NodeList firstNodes = firstNameElement.getChildNodes(); final String link = firstNodes.item(0).getNodeValue(); final URL dpage = new URL(link); final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream())); final StringBuilder content = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) { content.append(inputLine); } br.close(); file = StringUtils.substringBetween(content.toString(), "<li class=\"user-action user-action-download\"><span><a href=\"", "\">Download</a></span></li>"); } else { throw new Exception(); } } catch (Exception e) { r.sendMes(cs, "pluginDownloadInvalidtag"); cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core" + r.negative + "/"); return; } BufferedInputStream bis; final HttpURLConnection huc; try { huc = (HttpURLConnection) new URL(file).openConnection(); huc.setInstanceFollowRedirects(true); huc.connect(); bis = new BufferedInputStream(huc.getInputStream()); } catch (MalformedURLException e) { r.sendMes(cs, "pluginDownloadInvaliddownloadlink"); return; } catch (IOException e) { r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage()); return; } String[] urlParts = huc.getURL().toString().split("(\\\\|/)"); final String fileName = urlParts[urlParts.length - 1]; r.sendMes(cs, "pluginDownloadCreatingTemp"); File f = new File(System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID().toString() + File.separator + fileName); while (f.getParentFile().exists()) { f = new File(System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID().toString() + File.separator + fileName); } if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) { r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName); return; } f.getParentFile().mkdirs(); BufferedOutputStream bos; try { bos = new BufferedOutputStream(new FileOutputStream(f)); } catch (FileNotFoundException e) { r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir")); return; } int b; r.sendMes(cs, "pluginDownloadDownloading"); try { try { while ((b = bis.read()) != -1) { bos.write(b); } } finally { bos.flush(); bos.close(); } } catch (IOException e) { r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage()); return; } if (fileName.endsWith(".zip")) { r.sendMes(cs, "pluginDownloadDecompressing"); PluginUtil.decompress(f.getAbsolutePath(), f.getParent()); } String name = null; for (File fi : PluginUtil.listFiles(f.getParentFile())) { if (!fi.getName().endsWith(".jar")) { continue; } if (name == null) { name = fi.getName(); } r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName()); try { Files.move(fi, new File( r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName())); } catch (IOException e) { r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage()); } } PluginUtil.deleteDirectory(f.getParentFile()); r.sendMes(cs, "pluginDownloadSucces", "%File", fileName); } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } else if (args[0].equalsIgnoreCase("search")) { if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) { r.sendMes(cs, "noPermissions"); return; } int page = 1; if (!r.checkArgs(args, 1)) { r.sendMes(cs, "pluginHelpSearch"); return; } Boolean b = false; if (r.checkArgs(args, 2)) { try { page = Integer.parseInt(args[args.length - 1]); b = true; } catch (NumberFormatException ignored) { } } String search = r.getFinalArg(args, 1); if (b) { search = new StringBuilder(new StringBuilder(search).reverse().toString() .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString(); } try { search = URLEncoder.encode(search, "UTF-8"); } catch (UnsupportedEncodingException e) { r.sendMes(cs, "pluginNoUTF8"); return; } final URL u; try { u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page); } catch (MalformedURLException e) { r.sendMes(cs, "pluginSearchMalformedTerm"); return; } final Runnable ru = new Runnable() { @Override public void run() { final BufferedReader br; try { br = new BufferedReader(new InputStreamReader(u.openStream())); } catch (IOException e) { r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage()); return; } String inputLine; StringBuilder content = new StringBuilder(); try { while ((inputLine = br.readLine()) != null) { content.append(inputLine); } } catch (IOException e) { r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage()); return; } r.sendMes(cs, "pluginSearchHeader"); for (int i = 0; i < 20; i++) { final String project = StringUtils.substringBetween(content.toString(), " row-joined-to-next\">", "</tr>"); final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">", "</td>"); if (base == null) { if (i == 0) { r.sendMes(cs, "pluginSearchNoResults"); } return; } final Pattern p = Pattern .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>"); final Matcher m = p.matcher(base); if (!m.find()) { if (i == 0) { r.sendMes(cs, "pluginSearchNoResults"); } return; } final String name = m.group(2).replaceAll("</?\\w+>", ""); final String tag = m.group(1); final int beglen = StringUtils.substringBefore(content.toString(), base).length(); content = new StringBuilder(content.substring(beglen + project.length())); r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag); } } }; Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru); } else { cs.sendMessage(ChatColor.GOLD + "================================"); r.sendMes(cs, "pluginHelpLoad"); r.sendMes(cs, "pluginHelpUnload"); r.sendMes(cs, "pluginHelpEnable"); r.sendMes(cs, "pluginHelpDisable"); r.sendMes(cs, "pluginHelpReload"); r.sendMes(cs, "pluginHelpReloadall"); r.sendMes(cs, "pluginHelpDelete"); r.sendMes(cs, "pluginHelpUpdate"); r.sendMes(cs, "pluginHelpCommands"); r.sendMes(cs, "pluginHelpList"); r.sendMes(cs, "pluginHelpUpdatecheck"); r.sendMes(cs, "pluginHelpUpdatecheckall"); r.sendMes(cs, "pluginHelpDownload"); r.sendMes(cs, "pluginHelpSearch"); cs.sendMessage(ChatColor.GOLD + "================================"); return; } }
From source file:Default.YTDownloadThread.java
private boolean saveTextData() throws IOException { boolean rc = false; // read html lines one by one and search for java script array of video URLs String line = ""; String line0 = ""; String line1 = ""; while (line != null) { line = this.textReader.readLine(); try {/*from w ww .j a va 2s . c om*/ // FIXME audio is missing .. video and audio are in separated streams in adaptive_fmts if (this.recursionCount == 0 && line.matches(".*(\"adaptive_fmts\":|\"url_encoded_fmt_stream_map\":).*")) { // behind that two strings are the comma separated video URLs we use rc = true; HashMap<String, String> sourceCodeVideoUrls = new HashMap<String, String>(); line = line.replaceAll(" ", ""); line = line.replace("%25", "%"); line = line.replace("\\u0026", "&"); if (line.contains("\"url_encoded_fmt_stream_map\":\"")) { line1 = StringUtils.substringBetween(line, "\"url_encoded_fmt_stream_map\":\"", "\""); } line0 = ""; if (line.contains("\"adaptive_fmts\":\"")) { line0 = StringUtils.substringBetween(line, "\"adaptive_fmts\":\"", "\""); } if (line0 == null) { line0 = ""; } if (line1 == null) { line1 = ""; } line = line0 + "," + line1; outputDebugMessage( String.format("length sline0 sline1: %d %d", line0.length(), line1.length())); outputDebugMessage(String.format("sline0 (adaptive fmt) %s \n sline1 (url_encoded fmt): %s", line0, line1)); // by anonymous String[] sourceCodeYoutubeUrls = line.split(","); outputDebugMessage( "ssourcecodeuturls.length: ".concat(Integer.toString(sourceCodeYoutubeUrls.length))); String resolutions = "found video URL for resolution: "; for (String url : sourceCodeYoutubeUrls) { // assuming rtmpe is used for all resolutions, if found once - end download if (url.matches(".*conn=rtmpe.*")) { outputDebugMessage("RTMPE found. cannot download this one!"); output("Unable to download video due to unsupported protocol (RTMPE). sry!"); break; } String[] fmtUrlPair = url.split("url=http(s)?", 2); fmtUrlPair[1] = "url=http" + fmtUrlPair[1] + "&" + fmtUrlPair[0]; // grep itag=xz out and use xy as hash key // 2013-02 itag now has up to 3 digits fmtUrlPair[0] = fmtUrlPair[1].substring(fmtUrlPair[1].indexOf("itag=") + 5, fmtUrlPair[1].indexOf("itag=") + 5 + 1 + (fmtUrlPair[1].matches(".*itag=[0-9]{2}.*") ? 1 : 0) + (fmtUrlPair[1].matches(".*itag=[0-9]{3}.*") ? 1 : 0)); if (this.request.getURI().toString().startsWith("https")) { fmtUrlPair[1] = fmtUrlPair[1].replaceFirst("url=http%3A%2F%2F", "https://"); // webpage source code only provides http urls if accessed via wget or ytd2 - the browser does something unknown so google sends back httpS urls within source code! } else { fmtUrlPair[1] = fmtUrlPair[1].replaceFirst("url=http%3A%2F%2F", "http://"); } fmtUrlPair[1] = fmtUrlPair[1].replaceAll("%3F", "?").replaceAll("%2F", "/") .replaceAll("%3B", ";")/*.replaceAll("%2C",",")*/.replaceAll("%3D", "=") .replaceAll("%26", "&").replaceAll("%252C", "%2C").replaceAll("sig=", "signature=") .replaceAll("&s=", "&signature=").replaceAll("\\?s=", "?signature="); // remove duplicate parts between & String sortedUrl = this.sortStringAt(fmtUrlPair[1], "&"); outputDebugMessage(String.format("video tag: %s url: %s", fmtUrlPair[0], sortedUrl)); // fmtUrlPair[1] -> ssortedURL fmtUrlPair[1] = sortedUrl; try { sourceCodeVideoUrls.put(fmtUrlPair[0], fmtUrlPair[1]); // save that URL //debugoutput(String.format( "video url saved with key %s: %s",fmtUrlPair[0],ssourcecodevideourls.get(fmtUrlPair[0]) )); resolutions = resolutions.concat(fmtUrlPair[0].equals("138") ? "2304p mpeg, " : // 4k HD type=video/mp4;+codecs="avc1.640033" & size=4096x2304 fmtUrlPair[0].equals("264") ? "1440p mpeg, " : // <4k HD type=video/mp4;+codecs="avc1.640032" & size=2560x1440 fmtUrlPair[0].equals("266") ? "2160p mpeg, " : // <4k HD type=video/mp4;+codecs=%22avc1.640033" & size=3840x2160& fmtUrlPair[0].equals("271") ? "1440p webm, " : // <4k HD type=video/webm;+codecs=%22vp9" & size=2560x1440 fmtUrlPair[0].equals("272") ? "2160p webm, " : // <4k HD type=video/webm;+codecs="vp9" & size=3840x2160 fmtUrlPair[0].equals("248") ? "1080p mpeg, " : // HD type=video/webm;+codecs="vp9" & size=1920x1080 fmtUrlPair[0].equals("37") ? "1080p mpeg, " : // HD type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2" fmtUrlPair[0].equals("22") ? "720p mpeg, " : // HD type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2" fmtUrlPair[0].equals( "247") ? "1080p mpeg, " : // HD type=video/webm;+codecs="vp9" & size=1280x720 fmtUrlPair[0] .equals("84") ? "1080p 3d mpeg, " : // HD 3D type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2" fmtUrlPair[0] .equals("18") ? "360p mpeg, " : // SD type=video/mp4;+codecs="avc1.42001E,+mp4a.40.2" fmtUrlPair[0] .equals("35") ? "480p flv, " : // SD type=video/x-flv fmtUrlPair[0] .equals("34") ? "360p flv, " : // SD type=video/x-flv fmtUrlPair[0] .equals("82") ? "360p 3d mpeg, " : // SD 3D type=video/mp4;+codecs="avc1.42001E,+mp4a.40.2" fmtUrlPair[0] .equals("36") ? "240p mpeg 3gpp, " : // LD type=video/3gpp;+codecs="mp4v.20.3,+mp4a.40.2" fmtUrlPair[0] .equals("17") ? "114p mpeg 3gpp, " : // LD type=video/3gpp;+codecs="mp4v.20.3,+mp4a.40.2" fmtUrlPair[0] .equals("46") ? "1080p webm, " : // HD type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("45") ? "720p webm, " : // HD type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("100") ? "1080p 3d webm, " : // HD 3D type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("44") ? "480p webm, " : // SD type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("43") ? "360p webm, " : // SD type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("102") ? "360p 3d webm, " : // SD 3D type=video/webm;+codecs="vp8.0,+vorbis" fmtUrlPair[0] .equals("244") ? "480p webm, " : // SD type=video/webm;+codecs="vp9" & size=854x480 fmtUrlPair[0] .equals("5") ? "240p flv, " : // LD type=video/x-flv fmtUrlPair[0] .equals("137") ? "1080p mpeg, " : // HD type=video/mp4;+codecs="avc1.640028" & size=1920x1080 fmtUrlPair[0] .equals("136") ? "720p mpeg, " : // HD type=video/mp4;+codecs="avc1.4d401f" & size=1280x720 fmtUrlPair[0] .equals("135") ? "480p mpeg, " : // SD type=video/mp4;+codecs="avc1.4d401f" & size=854x480 fmtUrlPair[0] .equals("134") ? "360p mpeg, " : // SD type=video/mp4;+codecs="avc1.4d401e" & size=640x360 fmtUrlPair[0] .equals("133") ? "240p mpeg, " : // LD type=video/mp4;+codecs="avc1.4d4015" & size=426x240 fmtUrlPair[0] .equals("160") ? "144p mpeg, " : // LD type=video/mp4;+codecs="avc1.42c00c" & size=256x144 fmtUrlPair[0] .equals("243") ? "360p webm, " : // LD type=video/webm;+codecs="vp9" fmtUrlPair[0] .equals("242") ? "240p webm, " : // LD type=video/webm;+codecs="vp9" fmtUrlPair[0] .equals("140") ? "mpeg audio only, " : // ?? type=audio/mp4;+codecs="mp4a.40.2 & bitrate=127949 fmtUrlPair[0] .equals("171") ? "ogg vorbis audio only, " : // ?? audio/webm;+codecs="vorbis" & bitrate=127949 "unknown resolution! (" .concat(fmtUrlPair[0]) .concat(") ")); } catch (java.lang.ArrayIndexOutOfBoundsException aioobe) { //TODO catch must not be empty } } if (true) { output(resolutions); } outputDebugMessage(resolutions); // TODO move scope into the if blocks int index = 0; this.nextVideoUrl.removeAllElements(); outputDebugMessage( "ssourcecodevideourls.length: ".concat(Integer.toString(sourceCodeVideoUrls.size()))); // figure out what resolution-button is pressed right now (!!) and fill list with possible URLs of video currently being processed // try AUDIO ONLY setting before any video resolution if (false) { if (false) { this.nextVideoUrl.add(index++, new YoutubeUrl(sourceCodeVideoUrls.get("140"), this.url, "AUDIO")); // MP4 AUDIO ONLY mime=audio/mp4 type=audio/mp4;+codecs=%22mp4a.40.2%22 this.nextVideoUrl.add(index++, new YoutubeUrl(sourceCodeVideoUrls.get("171"), this.url, "AUDIO")); // WEBM AUDIO ONLY mime=audio/webm type=audio/webm;+codecs=%22vorbis%22 } else { this.nextVideoUrl.add(index++, new YoutubeUrl(sourceCodeVideoUrls.get("171"), this.url, "AUDIO")); // WEBM AUDIO ONLY mime=audio/webm type=audio/webm;+codecs=%22vorbis%22 this.nextVideoUrl.add(index++, new YoutubeUrl(sourceCodeVideoUrls.get("140"), this.url, "AUDIO")); // MP4 AUDIO ONLY mime=audio/mp4 type=audio/mp4;+codecs=%22mp4a.40.2%22 } } else { switch (2) { case 8: // ULTRA HD // try 1440p, 2160p and 2304p first, if selected in GUI if (true) { index = addMPEG_ULTRAHD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addWEBM_ULTRAHD_Urls(index, sourceCodeVideoUrls); } //$FALL-THROUGH$ case 4: // HD // try 1080p/720p in selected format first. if it's not available than the other format will be used if (true) { index = addMPEG_HD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addWBEM_HD_Urls(index, sourceCodeVideoUrls); } // there are no FLV HD URLs for now, so at least try mpg, webm HD then index = addMPEG_HD_Urls(index, sourceCodeVideoUrls); index = addWBEM_HD_Urls(index, sourceCodeVideoUrls); //$FALL-THROUGH$ case 2: // SD // try to download desired format first, if it's not available we take the other of same res if (true) { index = addMPEG_SD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addWBEM_SD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addFLV_SD_Urls(index, sourceCodeVideoUrls); } index = addMPEG_SD_Urls(index, sourceCodeVideoUrls); index = addWBEM_SD_Urls(index, sourceCodeVideoUrls); index = addFLV_SD_Urls(index, sourceCodeVideoUrls); //$FALL-THROUGH$ case 1: // LD if (true) { index = addMPEG_LD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addWEBM_LD_Urls(index, sourceCodeVideoUrls); } if (false) { index = addFLV_LD_Urls(index, sourceCodeVideoUrls); } // we must ensure all (16) possible URLs get added so the list of URLs is never empty index = addMPEG_LD_Urls(index, sourceCodeVideoUrls); index = addWEBM_LD_Urls(index, sourceCodeVideoUrls); index = addFLV_LD_Urls(index, sourceCodeVideoUrls); break; default: //this.vNextVideoURL = null; this.videoUrl = null; break; } } // if the first 2 entries are null than there are no URLs for the selected resolution // strictly speaking this is only true for HD as there are only two URLs in contrast to three of SD - in this case the output will not be shown but downloading should work anyway // 2014-01-25 since there is another block of video urls (including one for audio only) and a new list of itags, we check only the first entry try { if (this.nextVideoUrl.get(0).getUrl() == null) { String smsg = "could not find video url for selected resolution! trying lower res..."; output(smsg); outputDebugMessage(smsg); } } catch (java.lang.ArrayIndexOutOfBoundsException aioob) { String smsg = "could not find video url for selected resolution! trying lower res..."; output(smsg); outputDebugMessage(smsg); } // remove null entries in list - we later try to download the first (index 0) and if it fails the next one (at index 1) and so on for (int x = this.nextVideoUrl.size() - 1; x >= 0; x--) { if (this.nextVideoUrl.get(x).getUrl() == null) { this.nextVideoUrl.remove(x); } } try { this.videoUrl = this.nextVideoUrl.get(0).getUrl(); outputDebugMessage(String.format("trying this one: %s %s %s %s", this.nextVideoUrl.get(0).getHtmlTagId(), this.nextVideoUrl.get(0).getQuality(), this.nextVideoUrl.get(0).getSize(), this.nextVideoUrl.get(0).getHtmlType())); } catch (ArrayIndexOutOfBoundsException aioobe) { //TODO catch must not be empty } this.setTitle(this.getTitle().concat("Video") .concat(!this.nextVideoUrl.get(0).getRespart().equals("") ? "." + this.nextVideoUrl.get(0).getRespart() : "")); // java.lang.ArrayIndexOutOfBoundsException would be thrown here if no known resolution was found until here } if (this.recursionCount == 0 && line.matches("(.*)<meta name=\"title\" content=(.*)")) { String stmp = line.replaceFirst("(.*)<meta name=\"title\" content=", "").trim(); // change html characters to their UTF8 counterpart stmp = UTF8.changeHTMLtoUTF8(stmp); stmp = stmp.replaceFirst("^\"", "").replaceFirst("\">$", ""); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx // stmp = stmp.replaceAll("<", ""); stmp = stmp.replaceAll(">", ""); stmp = stmp.replaceAll(":", ""); stmp = stmp.replaceAll("/", " "); stmp = stmp.replaceAll("\\\\", " "); stmp = stmp.replaceAll("|", ""); stmp = stmp.replaceAll("\\?", ""); stmp = stmp.replaceAll("\\*", ""); stmp = stmp.replaceAll("/", " "); stmp = stmp.replaceAll("\"", " "); stmp = stmp.replaceAll("%", ""); this.setTitle(stmp); // complete file name without path } } catch (NullPointerException npe) { } } return rc; }
From source file:adalid.commons.util.StrUtils.java
/** * Replaces all occurrences of a String within another String that are found between another two Strings. * * @param text the String to search and replace in * @param search the String to search for * @param replacement the String to replace it with * @param preceding the String used as lower boundary of the search; if it is null or empty, the search begins at the beginning of text * @param following the String used as upper boundary of the search; if it is null or empty, the search ends at the end of text * @return the text with any replacements processed *///from www. ja v a 2s . c om public static String replaceBetween(String text, String search, String replacement, String preceding, String following) { final String turbofan = "\t\r\b\f\n"; if (text != null && search != null && replacement != null && text.length() > 0 && search.length() > 0 && text.contains(search)) { boolean preceded = preceding != null && preceding.length() > 0; if (preceded && !text.contains(preceding)) { return text; } boolean followed = following != null && following.length() > 0; if (followed && !text.contains(following)) { return text; } if (preceded || followed) { String searchless = text.replace(search, turbofan); String beforePreceding = preceded ? StringUtils.substringBefore(searchless, preceding) : ""; String afterPreceding = preceded ? StringUtils.substringAfter(searchless, preceding) : ""; String beforeFollowing = followed ? StringUtils.substringBefore(preceded ? afterPreceding : searchless, following) : ""; String afterFollowing = followed ? StringUtils.substringAfter(preceded ? afterPreceding : searchless, following) : ""; String inBetween = preceded && followed ? StringUtils.substringBetween(searchless, preceding, following) : ""; String substring = preceded && followed ? inBetween : preceded ? afterPreceding : beforeFollowing; if (StringUtils.contains(substring, turbofan)) { String string = substring.replace(turbofan, replacement); String concat = beforePreceding + (preceded ? preceding : "") + string + (followed ? following : "") + afterFollowing; String result = concat.replace(turbofan, search); return result; } } else { return text.replace(search, replacement); } } return text; }
From source file:ips1ap101.lib.core.jsf.JSF.java
private static TreeNode addTreeNode(TreeNode parent, RecursoCachedRowSetDataProvider dp, String colname, EnumColumnaEtiqueta coltype, String url, MethodExpression mex, RowKey rowKey, boolean activeOnly) { if (activeOnly && dp.isRecursoDesactivable() && BitUtils.valueOf(dp.getRecursoDesactivableDataProvider().getEsRecursoInactivo(rowKey))) { return null; }/*from w w w .j a va 2 s .co m*/ String clave = dp.getRecursoJerarquizableDataProvider().getColumnaRecursoSuperior(); Long id = dp.getRecursoJerarquizableDataProvider().getIdentificacionRecurso(rowKey); String tnid = getTreeNodeId(dp, rowKey); String text; String toolTip; if (dp.isRecursoDescriptible()) { toolTip = dp.getRecursoDescriptibleDataProvider().getDescripcionRecurso(rowKey); } else { toolTip = getTreeNodeText(dp, rowKey, EnumColumnaEtiqueta.AMBAS_COLUMNAS); } String urlx; String target = null; if (StringUtils.isBlank(colname)) { text = getTreeNodeText(dp, rowKey, coltype); } else { text = getTreeNodeText(dp, rowKey, colname); } if (dp.isRecursoLocalizable()) { urlx = dp.getRecursoLocalizableDataProvider().getUrl(rowKey); // <editor-fold> // if (urlx != null) { // target = Global.DEFAULT_WINDOW_NAME; // target = getWindowName(); // target = "_blank"; /* renders the response in a new, unnamed window */ // target = "_self"; /* renders the response in the current frame */ // target = "_parent"; /* renders the response in the immediate frameset parent */ // target = "_top"; /* renders the response in the full, unframed window */ // } // </editor-fold> if (urlx != null) { String war = StringUtils.substringBetween(urlx, REDIRECT, FACES); if (StringUtils.isNotBlank(war) && !war.equals(URX.WAR)) { urlx = urlx.replaceAll(war, URX.WAR); } urlx = urlx.replaceAll(WAR, URX.WAR); String sfn = StringUtils.substringBetween(urlx.replace("?sfn=", "&sfn=").concat("&"), "&sfn=", "&"); if (sfn != null && sfn.matches("[0-9\\-]*")) { Long funcion; boolean funcionAutorizada = false; String[] strings = StringUtils.split(sfn, '-'); for (String string : strings) { funcion = Long.valueOf(string); funcionAutorizada = TLC.getControlador().esFuncionAutorizada(funcion); if (funcionAutorizada) { break; } } if (funcionAutorizada) { } else { return null; } } } } else { urlx = addRequestPostBackParameters(url, id); } TreeNode child = addTreeNode(parent, tnid, text, toolTip, urlx, mex, target); if (dp.esFilaEscogida(rowKey)) { expand(child); } if (StringUtils.isBlank(clave)) { /* * para que no falle con ListaRecursoCachedRowSetDataProvider */ return child; } RowKey[] children = dp.findAll(clave, id); if (children != null && children.length > 0) { for (int i = 0; i < children.length; i++) { addTreeNode(child, dp, colname, coltype, url, mex, children[i], activeOnly); } } return child; }