List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java
public String responseCaptcha(String responseCaptcha) { String url = "https://ipv4.google.com/sorry/CaptchaRedirect"; String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha=" + responseCaptcha + "&submit=Enviar"; String newCookie = ""; try {// w ww.j a v a 2 s .c om URL obj = new URL(request); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header con.setRequestProperty("Host", "ipv4.google.com"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3"); con.setRequestProperty("Accept-Encoding", "gzip, deflate, br"); con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com"); con.addRequestProperty("Connection", "keep-alive"); con.setRequestProperty("Referer", referer); //con.connect(); boolean redirect = false; con.setInstanceFollowRedirects(false); int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = con.getHeaderField("Location"); // open the new connnection again con = (HttpURLConnection) new URL(newUrl).openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Referer", referer); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); con.setRequestProperty("Cookie", tokenCookie); con.addRequestProperty("Connection", "keep-alive"); // Find the cookie String nextURL = URLDecoder.decode(newUrl, "UTF-8"); String[] k = nextURL.split("&"); for (String a : k) { if (a.startsWith("google_abuse=")) { String temp = a.replace("google_abuse=", ""); String[] c = temp.split(";"); for (String j : c) { if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) { newCookie = j; } } } } } con.connect(); if (con.getResponseCode() == 200) { newCookie = tokenCookie; } } catch (IOException e) { e.printStackTrace(); } return newCookie; }
From source file:uk.ac.vfb.geppetto.VFBProcessTermInfo.java
/** * @param urlString//from w ww. ja v a 2 s.co m */ private String checkURL(String urlString) { try { urlString = urlString.replace("https://", "http://").replace(":5000", ""); urlString = urlString.replace("//virtualflybrain.org", "//www.virtualflybrain.org"); URL url = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("HEAD"); huc.setInstanceFollowRedirects(true); int response = huc.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { return urlString; } else if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM) { return checkURL(huc.getHeaderField("Location")); } return null; } catch (Exception e) { System.out.println("Error checking url (" + urlString + ") " + e.toString()); return null; } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Returns an <code>HttpURLConnection</code> fully ready to attempt * connection. This means it sets the request method (GET or POST), headers, * cookies, and authorization for the URL request. * <p>//from w ww .j a v a2s . c o m * The request infos are saved into the sample result if one is provided. * * @param u * <code>URL</code> of the URL request * @param method * GET, POST etc * @param res * sample result to save request infos to * @return <code>HttpURLConnection</code> ready for .connect * @exception IOException * if an I/O Exception occurs */ protected HttpURLConnection setupConnection(URL u, String method, HTTPSampleResult res) throws IOException { SSLManager sslmgr = null; if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { sslmgr = SSLManager.getInstance(); // N.B. this needs to be done before opening the connection } catch (Exception e) { log.warn("Problem creating the SSLManager: ", e); } } final HttpURLConnection conn; final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); if (proxyHost.length() > 0 && proxyPort > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); //TODO - how to define proxy authentication for a single connection? // It's not clear if this is possible // String user = getProxyUser(); // if (user.length() > 0){ // Authenticator auth = new ProxyAuthenticator(user, getProxyPass()); // } conn = (HttpURLConnection) u.openConnection(proxy); } else { conn = (HttpURLConnection) u.openConnection(); } // Update follow redirects setting just for this connection conn.setInstanceFollowRedirects(getAutoRedirects()); int cto = getConnectTimeout(); if (cto > 0) { conn.setConnectTimeout(cto); } int rto = getResponseTimeout(); if (rto > 0) { conn.setReadTimeout(rto); } if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { if (null != sslmgr) { sslmgr.setContext(conn); // N.B. must be done after opening connection } } catch (Exception e) { log.warn("Problem setting the SSLManager for the connection: ", e); } } // a well-behaved browser is supposed to send 'Connection: close' // with the last request to an HTTP server. Instead, most browsers // leave it to the server to close the connection after their // timeout period. Leave it to the JMeter user to decide. if (getUseKeepAlive()) { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE); } else { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE); } conn.setRequestMethod(method); setConnectionHeaders(conn, u, getHeaderManager(), getCacheManager()); String cookies = setConnectionCookie(conn, u, getCookieManager()); setConnectionAuthorization(conn, u, getAuthManager()); if (method.equals(HTTPConstants.POST)) { setPostHeaders(conn); } else if (method.equals(HTTPConstants.PUT)) { setPutHeaders(conn); } if (res != null) { res.setRequestHeaders(getConnectionHeaders(conn)); res.setCookies(cookies); } return conn; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java
/** * Returns an <code>HttpURLConnection</code> fully ready to attempt * connection. This means it sets the request method (GET or POST), headers, * cookies, and authorization for the URL request. * <p>/* ww w . j a va 2 s .com*/ * The request infos are saved into the sample result if one is provided. * * @param u * <code>URL</code> of the URL request * @param method * GET, POST etc * @param res * sample result to save request infos to * @return <code>HttpURLConnection</code> ready for .connect * @exception IOException * if an I/O Exception occurs */ protected HttpURLConnection setupConnection(URL u, String method, HTTPSampleResult res) throws IOException { SSLManager sslmgr = null; if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { sslmgr = SSLManager.getInstance(); // N.B. this needs to be done // before opening the // connection } catch (Exception e) { log.warn("Problem creating the SSLManager: ", e); } } final HttpURLConnection conn; final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); if (proxyHost.length() > 0 && proxyPort > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); // TODO - how to define proxy authentication for a single // connection? // It's not clear if this is possible // String user = getProxyUser(); // if (user.length() > 0){ // Authenticator auth = new ProxyAuthenticator(user, // getProxyPass()); // } conn = (HttpURLConnection) u.openConnection(proxy); } else { conn = (HttpURLConnection) u.openConnection(); } // Update follow redirects setting just for this connection conn.setInstanceFollowRedirects(getAutoRedirects()); int cto = getConnectTimeout(); if (cto > 0) { conn.setConnectTimeout(cto); } int rto = getResponseTimeout(); if (rto > 0) { conn.setReadTimeout(rto); } if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { if (null != sslmgr) { sslmgr.setContext(conn); // N.B. must be done after opening // connection } } catch (Exception e) { log.warn("Problem setting the SSLManager for the connection: ", e); } } // a well-bahaved browser is supposed to send 'Connection: close' // with the last request to an HTTP server. Instead, most browsers // leave it to the server to close the connection after their // timeout period. Leave it to the JMeter user to decide. if (getUseKeepAlive()) { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE); } else { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE); } conn.setRequestMethod(method); setConnectionHeaders(conn, u, getHeaderManager(), getCacheManager()); String cookies = setConnectionCookie(conn, u, getCookieManager()); setConnectionAuthorization(conn, u, getAuthManager()); if (method.equals(HTTPConstants.POST)) { setPostHeaders(conn); } else if (method.equals(HTTPConstants.PUT)) { setPutHeaders(conn); } if (res != null) { res.setRequestHeaders(getConnectionHeaders(conn)); res.setCookies(cookies); } return conn; }
From source file:iracing.webapi.IracingWebApi.java
private boolean forumLoginAndGetCookie() { try {//from www.java2 s. c o m // Make a connect to the server URL url = new URL(FORUM_LOGIN_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty(COOKIE, cookie); conn.setDoInput(true); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); HttpURLConnection.setFollowRedirects(false); conn.connect(); if (isMaintenancePage(conn)) return false; String headerName; boolean containsCookie = false; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase(SET_COOKIE)) { containsCookie = true; addToCookieMap(conn.getHeaderField(i)); } } if (containsCookie) createCookieFromMap(); conn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
From source file:bammerbom.ultimatecore.spongeapi.commands.CmdPlugin.java
@Override public void run(final CommandSender cs, String label, final String[] args) { //help//w ww . ja va2 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:org.lockss.proxy.ProxyHandler.java
/** Proxy a connection using Java's native URLConection */ void doSun(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { URI uri = request.getURI();// ww w . j a v a 2 s. c om try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) { sendForbid(request, response, uri); logAccess(request, "forbidden method: " + request.getMethod()); } return; } if (jlog.isDebugEnabled()) jlog.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean hasContent = false; Enumeration en = request.getFieldNames(); while (en.hasMoreElements()) { // XXX could be better than this! String hdr = (String) en.nextElement(); if (_DontProxyHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equalsIgnoreCase(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); } } } // Proxy headers connection.addRequestProperty(HttpFields.__Via, makeVia(request)); connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(jlog, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(jlog, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addField(HttpFields.__Via, makeVia(request)); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warning("doSun error", e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request, e.getMessage()); } }
From source file:bammerbom.ultimatecore.bukkit.commands.CmdPlugin.java
@Override public void run(final CommandSender cs, String label, final String[] args) { //help/*from www.j a v 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(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:com.spotify.helios.client.DefaultRequestDispatcher.java
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity, final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy, final Identity identity) throws IOException { if (log.isTraceEnabled()) { log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(), Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length, Json.asPrettyStringUnchecked(entity)); } else {//from w ww .j av a 2 s . c o m log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length); } final URLConnection urlConnection = ipUri.toURL().openConnection(); final HttpURLConnection connection = (HttpURLConnection) urlConnection; // We verify the TLS certificate against the original hostname since verifying against the // IP address will fail if (urlConnection instanceof HttpsURLConnection) { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); connection.setRequestProperty("Host", hostname); final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String ip, SSLSession sslSession) { final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1) : hostname; return new DefaultHostnameVerifier().verify(tHostname, sslSession); } }); if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) { final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user); httpsConnection.setSSLSocketFactory(factory); } } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS); connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS); for (Map.Entry<String, List<String>> header : headers.entrySet()) { for (final String value : header.getValue()) { connection.addRequestProperty(header.getKey(), value); } } if (entity.length > 0) { connection.setDoOutput(true); connection.getOutputStream().write(entity); } if (urlConnection instanceof HttpsURLConnection) { setRequestMethod(connection, method, true); } else { setRequestMethod(connection, method, false); } final int responseCode = connection.getResponseCode(); if (responseCode == HTTP_BAD_GATEWAY) { throw new ConnectException("502 Bad Gateway"); } return connection; }
From source file:org.searsia.engine.Resource.java
private String getCompleteWebPage(String urlString, String postString, Map<String, String> headers) throws IOException { if (rateLimitReached()) { throw new IOException("Rate limited"); }/*from www .j a va2 s . c o m*/ URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Searsia/0.4"); connection.setRequestProperty("Accept", this.mimeType); //TODO: "*/*" connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // TODO: from browser? for (Map.Entry<String, String> entry : headers.entrySet()) { String value = entry.getValue(); for (String param : this.privateParameters.keySet()) { value = value.replace("{" + param + "}", this.privateParameters.get(param)); } if (value.contains("{")) { throw new IOException("Missing header parameter"); // TODO: better error } connection.setRequestProperty(entry.getKey(), value); } connection.setReadTimeout(9000); connection.setConnectTimeout(9000); connection.setInstanceFollowRedirects(true); if (postString != null && !postString.equals("")) { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postString.getBytes().length)); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postString); wr.flush(); wr.close(); } else { connection.setRequestMethod("GET"); connection.connect(); } //int responseCode = connection.getResponseCode(); BufferedReader in = null; StringBuilder page = new StringBuilder(); in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); if (in != null) { String inputLine; while ((inputLine = in.readLine()) != null) { page.append(inputLine); } in.close(); } return page.toString(); }