Example usage for org.apache.commons.lang StringUtils substringBefore

List of usage examples for org.apache.commons.lang StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBefore.

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:bammerbom.ultimatecore.bukkit.commands.CmdPlugin.java

@Override
public void run(final CommandSender cs, String label, final String[] args) {
    //help//from w  w w. j a  v a 2  s .  c om
    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:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

/**
 * Will parse and return the level, given a package name.
 * @param packageName/*from  w w w .ja  va 2  s .c o  m*/
 * @return
 */
public RuleLevel parseRuleLevel(String packageName) {

    String prefix = StringUtils.substringBefore(packageName, ".ORG_");

    if (StringUtils.equals(prefix, "gov.nih.nci.cabig.caaers.rules.sponsor.study"))
        return RuleLevel.SponsorDefinedStudy;
    if (StringUtils.equals(prefix, "gov.nih.nci.cabig.caaers.rules.sponsor"))
        return RuleLevel.Sponsor;
    if (StringUtils.equals(prefix, "gov.nih.nci.cabig.caaers.rules.institution.study"))
        return RuleLevel.InstitutionDefinedStudy;
    if (StringUtils.equals(prefix, "gov.nih.nci.cabig.caaers.rules.institution"))
        return RuleLevel.Institution;

    return null;
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

/**
 * Will return the organization Id (Sponsor/Institution) id
 * @param packageName/*from  w  w  w.j a v  a  2 s.  c  o m*/
 * @return
 */
public String parseOrganizationId(String packageName) {

    String s = StringUtils.substringAfter(packageName, ".ORG_");
    String orgId = StringUtils.substringBefore(s, ".");
    return orgId;

}

From source file:com.amalto.core.storage.StorageWrapper.java

public static String getPureClusterName(String clusterName) {
    return clusterName.contains("/") ? StringUtils.substringBefore(clusterName, "/") : clusterName;//$NON-NLS-1$ //$NON-NLS-2$
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

/**
 * Will return the study Id/*from   w  w  w  .  j av a 2s  . co m*/
 * @param packageName
 * @return
 */
public String parseStudyId(String packageName) {

    String s = StringUtils.substringAfter(packageName, ".STU_");
    String studyId = StringUtils.substringBefore(s, ".");
    return studyId;

}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param connectUrl/*  ww w . j  a  va  2  s .  co  m*/
 * @return
 * @throws IOException
 * @throws DAOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private HttpURLConnection openUrlConnection(String connectUrl)
        throws IOException, DAOException, SAXException, ParserConfigurationException {

    String sanitizedUrl = StringUtils.substringBefore(connectUrl, "#");
    sanitizedUrl = StringUtils.replace(sanitizedUrl, " ", "%20");

    HttpURLConnection connection = (HttpURLConnection) new URL(sanitizedUrl).openConnection();
    connection.setRequestProperty("Accept", ACCEPT_HEADER);
    connection.setRequestProperty("User-Agent", URLUtil.userAgentHeader());
    connection.setRequestProperty("Connection", "close");
    connection.setInstanceFollowRedirects(false);

    // Set the timeout both for establishing the connection, and reading from it once established.
    int httpTimeout = GeneralConfig.getIntProperty(GeneralConfig.HARVESTER_HTTP_TIMEOUT, getTimeout());
    connection.setConnectTimeout(httpTimeout);
    connection.setReadTimeout(httpTimeout);

    // Use "If-Modified-Since" header, if this is not an on-demand harvest
    if (!isOnDemandHarvest) {

        // "If-Modified-Since" will be compared to this URL's last harvest
        Date lastHarvestDate = getContextSourceDTO().getLastHarvest();
        long lastHarvest = lastHarvestDate == null ? 0L : lastHarvestDate.getTime();
        if (lastHarvest > 0) {

            // Check if this URL has a conversion stylesheet, and if the latter has been modified since last harvest.
            String conversionStylesheetUrl = getConversionStylesheetUrl(sanitizedUrl);
            boolean hasConversion = !StringUtils.isBlank(conversionStylesheetUrl);
            boolean hasModifiedConversion = hasConversion
                    && URLUtil.isModifiedSince(conversionStylesheetUrl, lastHarvest);

            // Check if post-harvest scripts are updated
            boolean scriptsModified = DAOFactory.get().getDao(PostHarvestScriptDAO.class)
                    .isScriptsModified(lastHarvestDate, getContextSourceDTO().getUrl());

            // "If-Modified-Since" should only be set if there is no modified conversion or post-harvest scripts for this URL.
            // Because if there is a conversion stylesheet or post-harvest scripts, and any of them has been modified since last
            // harvest, we surely want to get the content again and run the conversion or script on the content, regardless of
            // when the content itself was last modified.
            if (!hasModifiedConversion && !scriptsModified) {
                LOGGER.debug(loggerMsg(
                        "Using if-modified-since, compared to last harvest " + formatDate(lastHarvestDate)));
                connection.setIfModifiedSince(lastHarvest);
            }
        }
    }

    return connection;
}

From source file:edu.cornell.kfs.coa.document.validation.impl.AccountReversionGlobalRule.java

/**
 * Validates that the sub fund group code on the cash and budget accounts is valid as defined by the allowed values in
 * SELECTION_4 system parameter./*from w w w.  j av a 2 s.  co  m*/
 * 
 * @param globalAcctRev
 * @return
 */
protected boolean validateAccountSubFundGroup(AccountReversionGlobal globalAcctRev) {
    boolean valid = true;

    String subFundGroups = SpringContext.getBean(ParameterService.class)
            .getParameterValueAsString(Reversion.class, CUKFSConstants.Reversion.SELECTION_4);
    String propertyName = StringUtils.substringBefore(subFundGroups, "=");
    List<String> ruleValues = Arrays.asList(StringUtils.substringAfter(subFundGroups, "=").split(";"));

    if (ObjectUtils.isNotNull(ruleValues) && ruleValues.size() > 0) {

        if (ObjectUtils.isNotNull(globalAcctRev.getBudgetReversionAccount())) {
            String budgetAccountSubFundGroupCode = globalAcctRev.getBudgetReversionAccount()
                    .getSubFundGroupCode();

            if (ruleValues.contains(budgetAccountSubFundGroupCode)) {
                valid = false;
                GlobalVariables.getMessageMap().putError(
                        MAINTAINABLE_ERROR_PREFIX
                                + CUKFSPropertyConstants.ACCT_REVERSION_BUDGET_REVERSION_ACCT_NUMBER,
                        RiceKeyConstants.ERROR_DOCUMENT_INVALID_VALUE_DENIED_VALUES_PARAMETER,
                        new String[] {
                                getDataDictionaryService().getAttributeLabel(SubFundGroup.class,
                                        KFSPropertyConstants.SUB_FUND_GROUP_CODE),
                                budgetAccountSubFundGroupCode,
                                getParameterAsStringForMessage(CUKFSConstants.Reversion.SELECTION_4),
                                getParameterValuesForMessage(ruleValues),
                                getDataDictionaryService().getAttributeLabel(AccountReversion.class,
                                        CUKFSPropertyConstants.ACCT_REVERSION_BUDGET_REVERSION_ACCT_NUMBER) });
            }
        }

        if (ObjectUtils.isNotNull(globalAcctRev.getCashReversionAccount())) {
            String cashAccountSubFundGroupCode = globalAcctRev.getCashReversionAccount().getSubFundGroupCode();

            if (ruleValues.contains(cashAccountSubFundGroupCode)) {
                valid = false;
                GlobalVariables.getMessageMap().putError(
                        MAINTAINABLE_ERROR_PREFIX
                                + CUKFSPropertyConstants.ACCT_REVERSION_CASH_REVERSION_ACCT_NUMBER,
                        RiceKeyConstants.ERROR_DOCUMENT_INVALID_VALUE_DENIED_VALUES_PARAMETER,
                        new String[] {
                                getDataDictionaryService().getAttributeLabel(SubFundGroup.class,
                                        KFSPropertyConstants.SUB_FUND_GROUP_CODE),
                                cashAccountSubFundGroupCode,
                                getParameterAsStringForMessage(CUKFSConstants.Reversion.SELECTION_4),
                                getParameterValuesForMessage(ruleValues),
                                getDataDictionaryService().getAttributeLabel(AccountReversion.class,
                                        CUKFSPropertyConstants.ACCT_REVERSION_CASH_REVERSION_ACCT_NUMBER) });
            }
        }
    }
    return valid;
}

From source file:com.egt.core.db.xdp.RecursoCachedRowSet.java

/**
 * {@inheritDoc}/*from  w  w  w. java 2  s.  c o  m*/
 */
@Override
public void acceptChanges() throws SyncProviderException {
    try {
        this.getFilasConflictivas().clear();
        super.acceptChanges();
    } catch (SyncProviderException spe) {
        SyncResolver resolver = spe.getSyncResolver();
        if (resolver != null && resolver instanceof SyncResolverX) {
            boolean showDeleted = this.tryToGetShowDeleted();
            boolean sinDuplicados = TLC.getBitacora().isSinDuplicados();
            int conflictos = 0;
            int row;
            int status = SyncResolver.NO_ROW_CONFLICT;
            String transaction = DBUtils.getTransactionLabel(status);
            SQLException sqlException;
            int errorCode;
            String message;
            String localizedMessage;
            String sqlState;
            String heading;
            String clave = CBM2.COMMIT_CHANGES_UNKNOWN_EXCEPTION;
            int tipoError; /* OJO con la constante, 1 -> fila con un error desconocido */
            String mensaje;
            String prefijo = Global.PREFIJO_ETIQUETA_ID_RECURSO;
            try {
                this.tryToSetShowDeleted(true);
                TLC.getBitacora().setSinDuplicados(true);
                while (resolver.nextConflict()) {
                    conflictos++;
                    row = resolver.getRow();
                    status = resolver.getStatus();
                    transaction = DBUtils.getTransactionLabel(status);
                    sqlException = ((SyncResolverX) resolver).getSQLException();
                    errorCode = sqlException.getErrorCode();
                    message = sqlException.getMessage();
                    localizedMessage = StringUtils.substringBefore(sqlException.getLocalizedMessage(),
                            " Where: ");
                    sqlState = sqlException.getSQLState();
                    heading = "Row:" + row + ", Status:" + status + ", Code:" + errorCode + ", State:"
                            + sqlState;
                    Bitacora.trace(heading + message);
                    if (TLC.getInterpreteSql().isCommandIgnoredException(sqlException)) {
                        clave = CBM2.COMMIT_CHANGES_COMMAND_IGNORED_EXCEPTION;
                        tipoError = 0; /* OJO con la constante, 0 -> fila "ignorada" (no se sabe si tiene o no errores) */
                        mensaje = tipoError + Bitacora.getTextoMensaje(clave, transaction, prefijo + row);
                        TLC.getBitacora().error(CBM2.COMMIT_CHANGES_COMMAND_IGNORED);
                        if (status == SyncResolver.DELETE_ROW_CONFLICT) {
                            this.tryToSetShowDeleted(false);
                        }
                    } else {
                        String columna = TLC.getInterpreteSql()
                                .getNotNullConstraintViolationColumn(sqlException);
                        if (StringUtils.isNotBlank(columna)) {
                            clave = CBM2.DATABASE_NOT_NULL_CONSTRAINT_VIOLATION;
                            tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */
                            mensaje = tipoError
                                    + TLC.getBitacora().error(clave, transaction, prefijo + row, columna);
                        } else {
                            clave = DBUtils.getConstraintMessageKey(message, status);
                            if (clave == null) {
                                clave = CBM2.COMMIT_CHANGES_UNKNOWN_EXCEPTION;
                                tipoError = 1; /* OJO con la constante, 1 -> fila con un error desconocido */
                                mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row,
                                        localizedMessage);
                            } else {
                                tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */
                                mensaje = tipoError
                                        + TLC.getBitacora().error(clave, transaction, prefijo + row);
                            }
                        }
                    }
                    this.getFilasConflictivas().put(String.valueOf(row - 1), mensaje);
                    //                      if (status == SyncResolver.DELETE_ROW_CONFLICT)
                    //                          if (this.absolute(row))
                    //                              if (this.rowDeleted()) // RETORNA FALSO!
                    //                                  this.undoDelete();
                }
                if (conflictos == 0) { /* esto parece un BUG, y pasa cuando se elimina la ultima fila y showDeleted==false */
                    TLC.getBitacora().error(clave, transaction, "", spe.getLocalizedMessage());
                }
            } catch (SQLException ex) {
                TLC.getBitacora().fatal(ex);
            } finally {
                this.tryToSetShowDeleted(showDeleted);
                TLC.getBitacora().setSinDuplicados(sinDuplicados);
                throw new SyncProviderException(this.getSyncProviderExceptionString(spe));
            }
        }
        throw spe;
    }
}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param connection/*from  w ww .ja v  a 2s  .  c  o  m*/
 * @return
 * @throws MalformedURLException
 */
private String getRedirectUrl(HttpURLConnection connection) throws MalformedURLException {

    String location = connection.getHeaderField("Location");
    if (location != null) {
        try {
            // If location does not seem to be an absolute URI, consider it relative to the
            // URL of this URL connection.
            if (!(new URI(location).isAbsolute())) {
                location = new URL(connection.getURL(), location).toString();
            }
        } catch (URISyntaxException e) {
            // Ignoring on purpose.
        }

        // we want to avoid fragment parts in CR harvest source URLs
        location = StringUtils.substringBefore(location, "#");
    }

    return location;
}

From source file:adalid.commons.util.StrUtils.java

/**
 * Replaces all occurrences of a String within another String that are found between another two Strings.
 *
 * @param text the String to search and replace in
 * @param search the String to search for
 * @param replacement the String to replace it with
 * @param preceding the String used as lower boundary of the search; if it is null or empty, the search begins at the beginning of text
 * @param following the String used as upper boundary of the search; if it is null or empty, the search ends at the end of text
 * @return the text with any replacements processed
 */// ww  w .  j  a  va 2  s . c  o m
public static String replaceBetween(String text, String search, String replacement, String preceding,
        String following) {
    final String turbofan = "\t\r\b\f\n";
    if (text != null && search != null && replacement != null && text.length() > 0 && search.length() > 0
            && text.contains(search)) {
        boolean preceded = preceding != null && preceding.length() > 0;
        if (preceded && !text.contains(preceding)) {
            return text;
        }
        boolean followed = following != null && following.length() > 0;
        if (followed && !text.contains(following)) {
            return text;
        }
        if (preceded || followed) {
            String searchless = text.replace(search, turbofan);
            String beforePreceding = preceded ? StringUtils.substringBefore(searchless, preceding) : "";
            String afterPreceding = preceded ? StringUtils.substringAfter(searchless, preceding) : "";
            String beforeFollowing = followed
                    ? StringUtils.substringBefore(preceded ? afterPreceding : searchless, following)
                    : "";
            String afterFollowing = followed
                    ? StringUtils.substringAfter(preceded ? afterPreceding : searchless, following)
                    : "";
            String inBetween = preceded && followed
                    ? StringUtils.substringBetween(searchless, preceding, following)
                    : "";
            String substring = preceded && followed ? inBetween : preceded ? afterPreceding : beforeFollowing;
            if (StringUtils.contains(substring, turbofan)) {
                String string = substring.replace(turbofan, replacement);
                String concat = beforePreceding + (preceded ? preceding : "") + string
                        + (followed ? following : "") + afterFollowing;
                String result = concat.replace(turbofan, search);
                return result;
            }
        } else {
            return text.replace(search, replacement);
        }
    }
    return text;
}