List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:uk.ac.ebi.metabolights.webservice.client.MetabolightsWsClient.java
private String makeRequestSendingData(String path, Object dataToSend, String method) { logger.debug("Making a {} request to {}", method, path); try {//from w w w.j av a 2 s . com // Get a post connection HttpURLConnection conn = getHttpURLConnection(path, method); conn.setRequestProperty("content-type", "application/json"); conn.setDoOutput(true); if (dataToSend != null) { String json = null; // If it's not a String if (!(dataToSend instanceof String)) { json = serializeObject(dataToSend); } else { json = (String) dataToSend; } // Send JSON content OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(json); out.close(); } // Read response if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("MetaboLights Java WS client: " + conn.getURL().toString() + "(" + method + ") request failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String message = org.apache.commons.io.IOUtils.toString(br); conn.disconnect(); return message; } catch (MalformedURLException e) { RestResponse response = new RestResponse(); response.setMessage("Malformed url: " + path); response.setErr(e); logger.error(response.getMessage(), e); return serializeObject(response); } catch (IOException e) { RestResponse response = new RestResponse(); response.setMessage("IO exception while trying to reach " + path); response.setErr(e); logger.error(response.getMessage(), e); return serializeObject(response); } }
From source file:com.dao.ShopThread.java
private boolean doJSShop() throws Exception { LogUtil.debugPrintf("?----------->"); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addJSDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.jsshopurl); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);//from www.j a va 2s. co m wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.jsshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "js"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } LogUtil.debugPrintf("??----------->"); // System.out.println(list.toHtml()); return result; }
From source file:com.dao.ShopThread.java
private boolean doPTShop() throws Exception { long startTime = System.currentTimeMillis(); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addPTDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.ptshopurl); loginConn.setRequestProperty("Host", "danbao.5173.com"); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);//from w ww. j av a2 s . c om wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.ptshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "db"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } return result; }
From source file:com.cloudant.http.interceptors.CookieInterceptor.java
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try {/* w w w.j a va 2s . com*/ boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: //403 //check if it was an expiry case InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject.class); String error = errorResponse.getAsJsonPrimitive("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive("reason").getAsString(); if (!"credentials_expired".equals(error)) { //wasn't a credentials expired, throw exception throw new HttpConnectionInterceptorException(error, reason); } else { // Was expired - set boolean to renew cookie renewCookie = true; } } catch (JsonParseException e) { //wasn't JSON throw an exception throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: //401 // We need to get a new cookie renewCookie = true; break; default: break; } if (renewCookie) { cookie = getCookie(connection.getURL(), context); // Don't resend request, failed to get cookie if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }
From source file:org.apache.hadoop.fs.http.client.HttpFSFileSystem.java
private FSDataOutputStream uploadData(String method, Path f, Map<String, String> params, int bufferSize, int expectedStatus) throws IOException { HttpURLConnection conn = getConnection(method, params, f, true); conn.setInstanceFollowRedirects(false); boolean exceptionAlreadyHandled = false; try {/*from ww w . j a v a2 s . c om*/ if (conn.getResponseCode() == HTTP_TEMPORARY_REDIRECT) { exceptionAlreadyHandled = true; String location = conn.getHeaderField("Location"); if (location != null) { conn = getConnection(new URL(location), method); conn.setRequestProperty("Content-Type", UPLOAD_CONTENT_TYPE); try { OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize); return new HttpFSDataOutputStream(conn, os, expectedStatus, statistics); } catch (IOException ex) { validateResponse(conn, expectedStatus); throw ex; } } else { validateResponse(conn, HTTP_TEMPORARY_REDIRECT); throw new IOException("Missing HTTP 'Location' header for [" + conn.getURL() + "]"); } } else { throw new IOException(MessageFormat.format("Expected HTTP status was [307], received [{0}]", conn.getResponseCode())); } } catch (IOException ex) { if (exceptionAlreadyHandled) { throw ex; } else { validateResponse(conn, HTTP_TEMPORARY_REDIRECT); throw ex; } } }
From source file:com.facebook.Request.java
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection) throws IOException, JSONException { Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request"); int numRequests = requests.size(); boolean shouldUseGzip = isGzipCompressible(requests); HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST; connection.setRequestMethod(connectionHttpMethod.name()); setConnectionContentType(connection, shouldUseGzip); URL url = connection.getURL(); logger.append("Request:\n"); logger.appendKeyValue("Id", requests.getId()); logger.appendKeyValue("URL", url); logger.appendKeyValue("Method", connection.getRequestMethod()); logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent")); logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type")); connection.setConnectTimeout(requests.getTimeout()); connection.setReadTimeout(requests.getTimeout()); // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will // turn it into a POST. boolean isPost = (connectionHttpMethod == HttpMethod.POST); if (!isPost) { logger.log();//from w w w. jav a 2s . c o m return; } connection.setDoOutput(true); OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(connection.getOutputStream()); if (shouldUseGzip) { outputStream = new GZIPOutputStream(outputStream); } if (hasOnProgressCallbacks(requests)) { ProgressNoopOutputStream countingStream = null; countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler()); processRequest(requests, null, numRequests, url, countingStream, shouldUseGzip); int max = countingStream.getMaxProgress(); Map<Request, RequestProgress> progressMap = countingStream.getProgressMap(); outputStream = new ProgressOutputStream(outputStream, requests, progressMap, max); } processRequest(requests, logger, numRequests, url, outputStream, shouldUseGzip); } finally { if (outputStream != null) { outputStream.close(); } } logger.log(); }
From source file:org.webical.dao.util.WebDavCalendarSynchronisation.java
/** * Uploads the eventlist to the remote calendar file * @param calendar the calendar witch holds the remote location * @param events the events to place in the calendar file * @throws DaoException with wrapped exception *///from w w w . j av a 2 s.co m public void writeToRemoteCalendarFile(final Calendar calendar, List<Event> events) throws DaoException { if (calendar == null || calendar.getUrl() == null) { throw new DaoException("calendar or url should not be null"); } if (log.isDebugEnabled()) log.debug("writeToRemoteCalendarFile " + calendar.getName() + ":" + events.size()); HttpURLConnection connection = null; try { try { //Set up authentication if needed if (calendar.getUsername() != null && calendar.getPassword() != null) { ConnectionUtil.setAuthentication(calendar.getUsername(), calendar.getPassword()); } } catch (Exception e) { log.error("Error in decrypting password", e); throw new DaoException("Error in decrypting password", e); } //Get the correct output source and build the calendar URL url = new URL(calendar.getUrl()); if (url.getProtocol().equalsIgnoreCase(ConnectionUtil.HTTPS_PROTOCOL)) { //TODO get from User Settings connection = ConnectionUtil.getHttpsUrlConnection(url, true); } else { connection = ConnectionUtil.getHttpUrlConnection(url); } //Set up the calendar builder and parse the calendar //XXX turned off validation - could not find out why this version of ical4j (1.0-beta4) is chocking on valid calendars. CalendarOutputter calendarOutputter = new CalendarOutputter(false); net.fortuna.ical4j.model.Calendar ical4jCalendar = ComponentFactory .buildIcal4JCalendarFromComponents(events, calendar); //Write the calendar to the remote file connection.setDoOutput(true); connection.setRequestMethod(ConnectionUtil.HTTP_PUT_METHOD); calendarOutputter.output(ical4jCalendar, connection.getOutputStream()); if (log.isDebugEnabled()) { log.debug("Flushing connection: " + connection.getURL()); } connection.getOutputStream().flush(); connection.getOutputStream().close(); //XXX Somehow the output is not writen if the input is not read, so read 1 byte. if (connection.getInputStream().available() > 0) { connection.getInputStream().read(); } } catch (URIException e) { log.error(e, e); throw new DaoException("Invalid url", e); } catch (IllegalArgumentException e) { log.error(e, e); throw new DaoException("Invalid url", e); } catch (IOException e) { log.error(e, e); throw new DaoException("Could not create connection", e); } catch (KeyManagementException e) { log.error(e, e); throw new DaoException("Could not connect to ssl socket", e); } catch (NoSuchAlgorithmException e) { log.error(e, e); throw new DaoException("Could not connect to ssl socket", e); } catch (ValidationException e) { log.error(e, e); throw new DaoException("Could not validate the Calendar", e); } catch (URISyntaxException e) { log.error(e, e); throw new DaoException("Invalid url", e); } catch (ParseException e) { log.error(e, e); throw new DaoException("Could not parse calendar", e); } }
From source file:bammerbom.ultimatecore.spongeapi.commands.CmdPlugin.java
@Override public void run(final CommandSender cs, String label, final String[] args) { //help//from ww w .j a v 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(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 www .java 2 s . co 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:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;/* w w w. j av a2 s . c o m*/ try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }