Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

In this page you can find the example usage for java.io BufferedOutputStream flush.

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:com.gft.unity.android.AndroidIO.java

/**
 * //from  w  ww . j  a  va2 s  .c  o m
 * @param httpResponse
 * @param service
 * @param storePath
 * @return
 * @throws IllegalStateException
 * @throws IOException
 */
private String readWebResponseAndStore(HttpResponse httpResponse, IOService service, String storePath)
        throws IllegalStateException, IOException {

    // getting response input stream
    InputStream responseStream = httpResponse.getEntity().getContent();

    int lengthContent = -1;
    int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;

    try {
        lengthContent = (int) httpResponse.getEntity().getContentLength();
        if (lengthContent >= 0 && lengthContent <= bufferReadSize) {
            bufferReadSize = lengthContent;
        }
    } catch (Exception e) {
        LOG.LogDebug(Module.PLATFORM,
                "Error while getting Content-Length header from response: " + e.getMessage());
    }
    LOG.LogDebug(Module.PLATFORM, "reading response stream content length: " + lengthContent);
    BufferedInputStream bis = new BufferedInputStream(responseStream);

    int size;
    byte[] buffer = new byte[bufferReadSize];

    File fullStorePath = new File(this.GetDirectoryRoot(), storePath);
    LOG.LogDebug(Module.PLATFORM, "Storing file at: " + fullStorePath.getAbsolutePath());

    FileOutputStream fos = new FileOutputStream(fullStorePath);
    BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
    int totalReadLen = 0;
    while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
        bos.write(buffer, 0, size);
        // just for testing // LOG.LogDebug(Module.PLATFORM, "read length: " + size);
        totalReadLen = totalReadLen + size;
    }

    LOG.LogDebug(Module.PLATFORM, "total read length: " + totalReadLen);

    bos.flush();
    bos.close();
    fos.close();

    bis.close();

    // Close the input stream and return bytes
    responseStream.close();

    return storePath;
}

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

@Override
public void run(final CommandSender cs, String label, final String[] args) {
    //help/*from  w w w.j a va  2s.  co  m*/
    if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        cs.sendMessage(TextColors.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(TextColors.GOLD + "================================");
    } //load
    else if (args[0].equalsIgnoreCase("load")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpLoad");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile(),
                args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
            return;
        }
        if (!f.canRead()) {
            r.sendMes(cs, "pluginFileNoReadAcces");
            return;
        }
        Plugin p;
        try {
            p = pm.loadPlugin(f);
            if (p == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependency", "%Message",
                    ex.getMessage() != null ? ex.getMessage() : "");
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginLoadSucces");
        } else {
            r.sendMes(cs, "pluginLoadFailed");
        }
    } //unload
    else if (args[0].equalsIgnoreCase("unload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUnload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(TextColors.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        r.sendMes(cs, "pluginUnloadUnloading");
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        r.sendMes(cs, "pluginUnloadUnloaded");
    } //enable
    else if (args[0].equalsIgnoreCase("enable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpEnable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginAlreadyEnabled");
            return;
        }
        pm.enablePlugin(p);
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginEnableSucces");
        } else {
            r.sendMes(cs, "pluginEnableFail");
        }
    } //disable
    else if (args[0].equalsIgnoreCase("disable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDisable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(TextColors.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        pm.disablePlugin(p);
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginDisableSucces");
        } else {
            r.sendMes(cs, "pluginDisableFailed");
        }
    } //reload
    else if (args[0].equalsIgnoreCase("reload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpReload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        pm.disablePlugin(p);
        pm.enablePlugin(p);
        r.sendMes(cs, "pluginReloadMessage");
    } //reloadall
    else if (args[0].equalsIgnoreCase("reloadall")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        for (Plugin p : pm.getPlugins()) {
            pm.disablePlugin(p);
            pm.enablePlugin(p);
        }
        r.sendMes(cs, "pluginReloadallMessage");
    } //delete
    else if (args[0].equalsIgnoreCase("delete")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDelete");
            return;
        }
        String del = args[1];
        if (!del.endsWith(".jar")) {
            del = del + ".jar";
        }
        if (del.contains(File.separator)) {
            r.sendMes(cs, "pluginDeleteDontLeavePluginFolder");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del);
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", del);
            return;
        }
        if (f.delete()) {
            r.sendMes(cs, "pluginDeleteSucces");
        } else {
            r.sendMes(cs, "pluginDeleteFailed");
        }
    } //commands
    else if (args[0].equalsIgnoreCase("commands")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpCommands");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        Map<String, Map<String, Object>> cmds = p.getDescription().getCommands();
        if (cmds == null) {
            r.sendMes(cs, "pluginCommandsNoneRegistered");
            return;
        }
        String command = "plugin " + p.getName();
        String pageStr = args.length > 2 ? args[2] : null;
        UText input = new TextInput(cs);
        UText output;
        if (input.getLines().isEmpty()) {
            if ((r.isInt(pageStr)) || (pageStr == null)) {
                output = new PluginCommandsInput(cs, args[1].toLowerCase());
            } else {
                r.sendMes(cs, "pluginCommandsPageNotNumber");
                return;
            }
        } else {
            output = input;
        }
        TextPager pager = new TextPager(output);
        pager.showPage(pageStr, null, command, cs);
    } //update
    else if (args[0].equalsIgnoreCase("update")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdate");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain()
                .getCodeSource().getLocation();
        File f;
        try {
            f = new File(u.toURI());
        } catch (URISyntaxException e) {
            f = new File(u.getPath());
        }
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        try {
            Plugin p2 = pm.loadPlugin(f);
            if (p2 == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p2);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage());
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
    } //list
    else if (args[0].equalsIgnoreCase("list")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList());
    } //info
    else if (args[0].equalsIgnoreCase("info")) {
        if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpInfo");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        PluginDescriptionFile pdf = p.getDescription();
        if (pdf == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        String version = pdf.getVersion();
        List<String> authors = pdf.getAuthors();
        String site = pdf.getWebsite();
        List<String> softDep = pdf.getSoftDepend();
        List<String> dep = pdf.getDepend();
        String name = pdf.getName();
        String desc = pdf.getDescription();
        if (name != null && !name.isEmpty()) {
            r.sendMes(cs, "pluginInfoName", "%Name", name);
        }
        if (version != null && !version.isEmpty()) {
            r.sendMes(cs, "pluginInfoVersion", "%Version", version);
        }
        if (site != null && !site.isEmpty()) {
            r.sendMes(cs, "pluginInfoWebsite", "%Website", site);
        }
        if (desc != null && !desc.isEmpty()) {
            r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", ""));
        }
        if (authors != null && !authors.isEmpty()) {
            r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author",
                    StringUtil.join(TextColors.RESET + ", " + r.neutral, authors));
        }
        if (softDep != null && !softDep.isEmpty()) {
            r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps",
                    StringUtil.join(TextColors.RESET + ", " + r.neutral, softDep));
        }
        if (dep != null && !dep.isEmpty()) {
            r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(TextColors.RESET + ", " + r.neutral, dep));
        }
        r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no")));
    } //updatecheck
    else if (args[0].equalsIgnoreCase("updatecheck")) {
        if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdatecheck");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        final String tag;
        try {
            tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        if (p.getDescription() == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet")
                : p.getDescription().getVersion();
        Runnable ru = new Runnable() {
            @Override
            public void run() {
                try {
                    String n = "";
                    String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss";
                    URL url = new URL(pluginUrlString);
                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    NodeList nodes = doc.getElementsByTagName("item");
                    Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        Element firstElement = (Element) firstNode;
                        NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                        Element firstNameElement = (Element) firstElementTagName.item(0);
                        NodeList firstNodes = firstNameElement.getChildNodes();
                        n = firstNodes.item(0).getNodeValue();
                    }

                    r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + "");
                    r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + "");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    r.sendMes(cs, "pluginUpdatecheckFailed");
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } //updatecheckall
    else if (args[0].equalsIgnoreCase("updatecheckall")) {
        if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (Plugin p : pm.getPlugins()) {
                    if (p.getDescription() == null) {
                        continue;
                    }
                    String version = p.getDescription().getVersion();
                    if (version == null) {
                        continue;
                    }
                    String n = "";
                    try {
                        String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/"
                                + p.getName().toLowerCase() + "/files.rss";
                        URL url = new URL(pluginUrlString);
                        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(url.openConnection().getInputStream());
                        doc.getDocumentElement().normalize();
                        NodeList nodes = doc.getElementsByTagName("item");
                        Node firstNode = nodes.item(0);
                        if (firstNode.getNodeType() == 1) {
                            Element firstElement = (Element) firstNode;
                            NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                            Element firstNameElement = (Element) firstElementTagName.item(0);
                            NodeList firstNodes = firstNameElement.getChildNodes();
                            n = firstNodes.item(0).getNodeValue();
                            a++;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                    if (n.contains(version)) {
                        continue;
                    }
                    r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin",
                            p.getName());
                }
                r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } //download
    else if (args[0].equalsIgnoreCase("download")) {
        if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDownload");
            cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core"
                    + r.negative + "/");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                String tag = args[1];
                r.sendMes(cs, "pluginDownloadGettingtag");
                String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss";
                String file;
                try {
                    final URL url = new URL(pluginUrlString);
                    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    final NodeList nodes = doc.getElementsByTagName("item");
                    final Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        final Element firstElement = (Element) firstNode;
                        final NodeList firstElementTagName = firstElement.getElementsByTagName("link");
                        final Element firstNameElement = (Element) firstElementTagName.item(0);
                        final NodeList firstNodes = firstNameElement.getChildNodes();
                        final String link = firstNodes.item(0).getNodeValue();
                        final URL dpage = new URL(link);
                        final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream()));
                        final StringBuilder content = new StringBuilder();
                        String inputLine;
                        while ((inputLine = br.readLine()) != null) {
                            content.append(inputLine);
                        }
                        br.close();
                        file = StringUtils.substringBetween(content.toString(),
                                "<li class=\"user-action user-action-download\"><span><a href=\"",
                                "\">Download</a></span></li>");
                    } else {
                        throw new Exception();
                    }
                } catch (Exception e) {
                    r.sendMes(cs, "pluginDownloadInvalidtag");
                    cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral
                            + "ultimate_core" + r.negative + "/");
                    return;
                }
                BufferedInputStream bis;
                final HttpURLConnection huc;
                try {
                    huc = (HttpURLConnection) new URL(file).openConnection();
                    huc.setInstanceFollowRedirects(true);
                    huc.connect();
                    bis = new BufferedInputStream(huc.getInputStream());
                } catch (MalformedURLException e) {
                    r.sendMes(cs, "pluginDownloadInvaliddownloadlink");
                    return;
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                String[] urlParts = huc.getURL().toString().split("(\\\\|/)");
                final String fileName = urlParts[urlParts.length - 1];
                r.sendMes(cs, "pluginDownloadCreatingTemp");
                File f = new File(System.getProperty("java.io.tmpdir") + File.separator
                        + UUID.randomUUID().toString() + File.separator + fileName);
                while (f.getParentFile().exists()) {
                    f = new File(System.getProperty("java.io.tmpdir") + File.separator
                            + UUID.randomUUID().toString() + File.separator + fileName);
                }
                if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) {
                    r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName);
                    return;
                }
                f.getParentFile().mkdirs();
                BufferedOutputStream bos;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(f));
                } catch (FileNotFoundException e) {
                    r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir"));
                    return;
                }
                int b;
                r.sendMes(cs, "pluginDownloadDownloading");
                try {
                    try {
                        while ((b = bis.read()) != -1) {
                            bos.write(b);
                        }
                    } finally {
                        bos.flush();
                        bos.close();
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                if (fileName.endsWith(".zip")) {
                    r.sendMes(cs, "pluginDownloadDecompressing");
                    PluginUtil.decompress(f.getAbsolutePath(), f.getParent());

                }
                String name = null;
                for (File fi : PluginUtil.listFiles(f.getParentFile())) {
                    if (!fi.getName().endsWith(".jar")) {
                        continue;
                    }
                    if (name == null) {
                        name = fi.getName();
                    }
                    r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName());
                    try {
                        Files.move(fi, new File(
                                r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName()));
                    } catch (IOException e) {
                        r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage());
                    }
                }
                PluginUtil.deleteDirectory(f.getParentFile());
                r.sendMes(cs, "pluginDownloadSucces", "%File", fileName);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else if (args[0].equalsIgnoreCase("search")) {
        if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        int page = 1;
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpSearch");
            return;
        }
        Boolean b = false;
        if (r.checkArgs(args, 2)) {
            try {
                page = Integer.parseInt(args[args.length - 1]);
                b = true;
            } catch (NumberFormatException ignored) {
            }
        }
        String search = r.getFinalArg(args, 1);
        if (b) {
            search = new StringBuilder(new StringBuilder(search).reverse().toString()
                    .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString();
        }
        try {
            search = URLEncoder.encode(search, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        final URL u;
        try {
            u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page);
        } catch (MalformedURLException e) {
            r.sendMes(cs, "pluginSearchMalformedTerm");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                final BufferedReader br;
                try {
                    br = new BufferedReader(new InputStreamReader(u.openStream()));
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                String inputLine;
                StringBuilder content = new StringBuilder();
                try {
                    while ((inputLine = br.readLine()) != null) {
                        content.append(inputLine);
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                r.sendMes(cs, "pluginSearchHeader");
                for (int i = 0; i < 20; i++) {
                    final String project = StringUtils.substringBetween(content.toString(),
                            " row-joined-to-next\">", "</tr>");
                    final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">",
                            "</td>");
                    if (base == null) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final Pattern p = Pattern
                            .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>");
                    final Matcher m = p.matcher(base);
                    if (!m.find()) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final String name = m.group(2).replaceAll("</?\\w+>", "");
                    final String tag = m.group(1);
                    final int beglen = StringUtils.substringBefore(content.toString(), base).length();
                    content = new StringBuilder(content.substring(beglen + project.length()));
                    r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag);
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else {
        cs.sendMessage(TextColors.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(TextColors.GOLD + "================================");
    }

}

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

@Override
public void run(final CommandSender cs, String label, final String[] args) {
    //help// w  w  w .j  ava2 s  .co  m
    if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        cs.sendMessage(ChatColor.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(ChatColor.GOLD + "================================");
        return;
    } //load
    else if (args[0].equalsIgnoreCase("load")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpLoad");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile(),
                args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
            return;
        }
        if (!f.canRead()) {
            r.sendMes(cs, "pluginFileNoReadAcces");
            return;
        }
        Plugin p;
        try {
            p = pm.loadPlugin(f);
            if (p == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependency", "%Message",
                    ex.getMessage() != null ? ex.getMessage() : "");
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginLoadSucces");
        } else {
            r.sendMes(cs, "pluginLoadFailed");
        }
        return;
    } //unload
    else if (args[0].equalsIgnoreCase("unload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUnload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(ChatColor.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        r.sendMes(cs, "pluginUnloadUnloading");
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        r.sendMes(cs, "pluginUnloadUnloaded");
        return;
    } //enable
    else if (args[0].equalsIgnoreCase("enable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpEnable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginAlreadyEnabled");
            return;
        }
        pm.enablePlugin(p);
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginEnableSucces");
        } else {
            r.sendMes(cs, "pluginEnableFail");
        }
        return;
    } //disable
    else if (args[0].equalsIgnoreCase("disable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDisable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(ChatColor.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        pm.disablePlugin(p);
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginDisableSucces");
        } else {
            r.sendMes(cs, "pluginDisableFailed");
        }
        return;
    } //reload
    else if (args[0].equalsIgnoreCase("reload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpReload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        pm.disablePlugin(p);
        pm.enablePlugin(p);
        r.sendMes(cs, "pluginReloadMessage");
        return;
    } //reloadall
    else if (args[0].equalsIgnoreCase("reloadall")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        for (Plugin p : pm.getPlugins()) {
            pm.disablePlugin(p);
            pm.enablePlugin(p);
        }
        r.sendMes(cs, "pluginReloadallMessage");
        return;
    } //delete
    else if (args[0].equalsIgnoreCase("delete")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDelete");
            return;
        }
        String del = args[1];
        if (!del.endsWith(".jar")) {
            del = del + ".jar";
        }
        if (del.contains(File.separator)) {
            r.sendMes(cs, "pluginDeleteDontLeavePluginFolder");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del);
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", del);
            return;
        }
        if (f.delete()) {
            r.sendMes(cs, "pluginDeleteSucces");
        } else {
            r.sendMes(cs, "pluginDeleteFailed");
        }
        return;
    } //commands
    else if (args[0].equalsIgnoreCase("commands")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpCommands");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        Map<String, Map<String, Object>> cmds = p.getDescription().getCommands();
        if (cmds == null) {
            r.sendMes(cs, "pluginCommandsNoneRegistered");
            return;
        }
        String command = "plugin " + p.getName();
        String pageStr = args.length > 2 ? args[2] : null;
        UText input = new TextInput(cs);
        UText output;
        if (input.getLines().isEmpty()) {
            if ((r.isInt(pageStr)) || (pageStr == null)) {
                output = new PluginCommandsInput(cs, args[1].toLowerCase());
            } else {
                r.sendMes(cs, "pluginCommandsPageNotNumber");
                return;
            }
        } else {
            output = input;
        }
        TextPager pager = new TextPager(output);
        pager.showPage(pageStr, null, command, cs);
        return;
    } //update
    else if (args[0].equalsIgnoreCase("update")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdate");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain()
                .getCodeSource().getLocation();
        File f;
        try {
            f = new File(u.toURI());
        } catch (URISyntaxException e) {
            f = new File(u.getPath());
        }
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        try {
            Plugin p2 = pm.loadPlugin(f);
            if (p2 == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p2);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage());
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        return;
    } //list
    else if (args[0].equalsIgnoreCase("list")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList());
        return;
    } //info
    else if (args[0].equalsIgnoreCase("info")) {
        if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpInfo");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        PluginDescriptionFile pdf = p.getDescription();
        if (pdf == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        String version = pdf.getVersion();
        List<String> authors = pdf.getAuthors();
        String site = pdf.getWebsite();
        List<String> softDep = pdf.getSoftDepend();
        List<String> dep = pdf.getDepend();
        String name = pdf.getName();
        String desc = pdf.getDescription();
        if (name != null && !name.isEmpty()) {
            r.sendMes(cs, "pluginInfoName", "%Name", name);
        }
        if (version != null && !version.isEmpty()) {
            r.sendMes(cs, "pluginInfoVersion", "%Version", version);
        }
        if (site != null && !site.isEmpty()) {
            r.sendMes(cs, "pluginInfoWebsite", "%Website", site);
        }
        if (desc != null && !desc.isEmpty()) {
            r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", ""));
        }
        if (authors != null && !authors.isEmpty()) {
            r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author",
                    StringUtil.join(ChatColor.RESET + ", " + r.neutral, authors));
        }
        if (softDep != null && !softDep.isEmpty()) {
            r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps",
                    StringUtil.join(ChatColor.RESET + ", " + r.neutral, softDep));
        }
        if (dep != null && !dep.isEmpty()) {
            r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(ChatColor.RESET + ", " + r.neutral, dep));
        }
        r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no")));
        return;
    } //updatecheck
    else if (args[0].equalsIgnoreCase("updatecheck")) {
        if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdatecheck");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        final String tag;
        try {
            tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        if (p.getDescription() == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet")
                : p.getDescription().getVersion();
        Runnable ru = new Runnable() {
            @Override
            public void run() {
                try {
                    String n = "";
                    String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss";
                    URL url = new URL(pluginUrlString);
                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    NodeList nodes = doc.getElementsByTagName("item");
                    Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        Element firstElement = (Element) firstNode;
                        NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                        Element firstNameElement = (Element) firstElementTagName.item(0);
                        NodeList firstNodes = firstNameElement.getChildNodes();
                        n = firstNodes.item(0).getNodeValue();
                    }

                    r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + "");
                    r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + "");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    r.sendMes(cs, "pluginUpdatecheckFailed");
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
        return;
    } //updatecheckall
    else if (args[0].equalsIgnoreCase("updatecheckall")) {
        if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (Plugin p : pm.getPlugins()) {
                    if (p.getDescription() == null) {
                        continue;
                    }
                    String version = p.getDescription().getVersion();
                    if (version == null) {
                        continue;
                    }
                    String n = "";
                    try {
                        String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/"
                                + p.getName().toLowerCase() + "/files.rss";
                        URL url = new URL(pluginUrlString);
                        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(url.openConnection().getInputStream());
                        doc.getDocumentElement().normalize();
                        NodeList nodes = doc.getElementsByTagName("item");
                        Node firstNode = nodes.item(0);
                        if (firstNode.getNodeType() == 1) {
                            Element firstElement = (Element) firstNode;
                            NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                            Element firstNameElement = (Element) firstElementTagName.item(0);
                            NodeList firstNodes = firstNameElement.getChildNodes();
                            n = firstNodes.item(0).getNodeValue();
                            a++;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                    if (n.contains(version)) {
                        continue;
                    }
                    r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin",
                            p.getName());
                }
                r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a);
                return;
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
        return;
    } //download
    else if (args[0].equalsIgnoreCase("download")) {
        if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDownload");
            cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core"
                    + r.negative + "/");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                String tag = args[1];
                r.sendMes(cs, "pluginDownloadGettingtag");
                String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss";
                String file;
                try {
                    final URL url = new URL(pluginUrlString);
                    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    final NodeList nodes = doc.getElementsByTagName("item");
                    final Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        final Element firstElement = (Element) firstNode;
                        final NodeList firstElementTagName = firstElement.getElementsByTagName("link");
                        final Element firstNameElement = (Element) firstElementTagName.item(0);
                        final NodeList firstNodes = firstNameElement.getChildNodes();
                        final String link = firstNodes.item(0).getNodeValue();
                        final URL dpage = new URL(link);
                        final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream()));
                        final StringBuilder content = new StringBuilder();
                        String inputLine;
                        while ((inputLine = br.readLine()) != null) {
                            content.append(inputLine);
                        }
                        br.close();
                        file = StringUtils.substringBetween(content.toString(),
                                "<li class=\"user-action user-action-download\"><span><a href=\"",
                                "\">Download</a></span></li>");
                    } else {
                        throw new Exception();
                    }
                } catch (Exception e) {
                    r.sendMes(cs, "pluginDownloadInvalidtag");
                    cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral
                            + "ultimate_core" + r.negative + "/");
                    return;
                }
                BufferedInputStream bis;
                final HttpURLConnection huc;
                try {
                    huc = (HttpURLConnection) new URL(file).openConnection();
                    huc.setInstanceFollowRedirects(true);
                    huc.connect();
                    bis = new BufferedInputStream(huc.getInputStream());
                } catch (MalformedURLException e) {
                    r.sendMes(cs, "pluginDownloadInvaliddownloadlink");
                    return;
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                String[] urlParts = huc.getURL().toString().split("(\\\\|/)");
                final String fileName = urlParts[urlParts.length - 1];
                r.sendMes(cs, "pluginDownloadCreatingTemp");
                File f = new File(System.getProperty("java.io.tmpdir") + File.separator
                        + UUID.randomUUID().toString() + File.separator + fileName);
                while (f.getParentFile().exists()) {
                    f = new File(System.getProperty("java.io.tmpdir") + File.separator
                            + UUID.randomUUID().toString() + File.separator + fileName);
                }
                if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) {
                    r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName);
                    return;
                }
                f.getParentFile().mkdirs();
                BufferedOutputStream bos;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(f));
                } catch (FileNotFoundException e) {
                    r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir"));
                    return;
                }
                int b;
                r.sendMes(cs, "pluginDownloadDownloading");
                try {
                    try {
                        while ((b = bis.read()) != -1) {
                            bos.write(b);
                        }
                    } finally {
                        bos.flush();
                        bos.close();
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                if (fileName.endsWith(".zip")) {
                    r.sendMes(cs, "pluginDownloadDecompressing");
                    PluginUtil.decompress(f.getAbsolutePath(), f.getParent());

                }
                String name = null;
                for (File fi : PluginUtil.listFiles(f.getParentFile())) {
                    if (!fi.getName().endsWith(".jar")) {
                        continue;
                    }
                    if (name == null) {
                        name = fi.getName();
                    }
                    r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName());
                    try {
                        Files.move(fi, new File(
                                r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName()));
                    } catch (IOException e) {
                        r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage());
                    }
                }
                PluginUtil.deleteDirectory(f.getParentFile());
                r.sendMes(cs, "pluginDownloadSucces", "%File", fileName);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else if (args[0].equalsIgnoreCase("search")) {
        if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        int page = 1;
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpSearch");
            return;
        }
        Boolean b = false;
        if (r.checkArgs(args, 2)) {
            try {
                page = Integer.parseInt(args[args.length - 1]);
                b = true;
            } catch (NumberFormatException ignored) {
            }
        }
        String search = r.getFinalArg(args, 1);
        if (b) {
            search = new StringBuilder(new StringBuilder(search).reverse().toString()
                    .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString();
        }
        try {
            search = URLEncoder.encode(search, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        final URL u;
        try {
            u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page);
        } catch (MalformedURLException e) {
            r.sendMes(cs, "pluginSearchMalformedTerm");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                final BufferedReader br;
                try {
                    br = new BufferedReader(new InputStreamReader(u.openStream()));
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                String inputLine;
                StringBuilder content = new StringBuilder();
                try {
                    while ((inputLine = br.readLine()) != null) {
                        content.append(inputLine);
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                r.sendMes(cs, "pluginSearchHeader");
                for (int i = 0; i < 20; i++) {
                    final String project = StringUtils.substringBetween(content.toString(),
                            " row-joined-to-next\">", "</tr>");
                    final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">",
                            "</td>");
                    if (base == null) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final Pattern p = Pattern
                            .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>");
                    final Matcher m = p.matcher(base);
                    if (!m.find()) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final String name = m.group(2).replaceAll("</?\\w+>", "");
                    final String tag = m.group(1);
                    final int beglen = StringUtils.substringBefore(content.toString(), base).length();
                    content = new StringBuilder(content.substring(beglen + project.length()));
                    r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag);
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else {
        cs.sendMessage(ChatColor.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(ChatColor.GOLD + "================================");
        return;
    }

}

From source file:org.ecoinformatics.seek.datasource.EcogridDataCacheItem.java

/**
 * Gets the dataItemFromEcoGrid attribute of the DataCacheObject object
 * /*from w w w.  j a va 2 s . co  m*/
 *@param endPoint
 *@param identifier
 */
protected int getDataItemFromEcoGrid(String endPoint, String identifier) {

    // create a ecogrid client object and get the full record from the
    // client
    if (endPoint != null && identifier != null) {
        log.debug("Get " + identifier + " from " + endPoint);
        BufferedOutputStream bos = null;
        try {
            // factory
            log.debug("This is instance pattern");

            URL endPointURL = new URL(endPoint);

            log.debug("Get from EcoGrid: " + identifier);
            // log.warn("the local file name is "+getFile());
            bos = new BufferedOutputStream(new FileOutputStream(getFile()));
            // log.warn("after create output stream ");
            // get the service from the controller
            EcoGridService service = EcoGridServicesController.getInstance().getService(endPoint);
            // check if we need to authenticate for it
            if (service != null && service.getServiceType()
                    .equals(EcoGridServicesController.AUTHENTICATEDQUERYSERVICETYPE)) {
                // get a credential (hopefully)
                String sessionId = EcoGridServicesController.getInstance().authenticateForService(service);
                log.info("using authenticated ecogrid get() method");
                AuthenticatedQueryServiceGetToStreamClient authGetClient = new AuthenticatedQueryServiceGetToStreamClient(
                        endPointURL);
                authGetClient.get(identifier, sessionId, bos);
            } else {
                // just get using the public version
                // log.warn("in public version branch ");
                QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient(endPointURL);
                // log.warn("after create service client ");
                ecogridClient.get(identifier, bos);
                // log.warn("after stream data  ");
            }
            // log.warn("before fulsh and close output stream ");
            bos.flush();
            bos.close();
            // log.warn("afer fulsh and close output stream ");
            return CACHE_COMPLETE;

        } catch (Exception ee) {
            log.error("EcogridDataCacheItem - error connecting to Ecogrid ", ee);
            cleanUpCache(bos);
            // Alert user about possible permission issue (BRL:20070918)
            try {
                MessageHandler
                        .warning("There has been a problem accessing the remote data:\n" + ee.getMessage());
            } catch (CancelException e) {
                // do nothing
            }

            return CACHE_ERROR;
        }

    } else {
        // System.out.println("in else path of get data from other source");
        // this is not ecogrid source, we need download by other protocol
        return getContentFromSource(identifier);

    }
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

public void run() {
    long duration, starttime = System.currentTimeMillis();
    Socket destinationSocket = null;
    try {/*from w ww .ja v a2s .  c o m*/
        BufferedOutputStream proxyClientStream = new BufferedOutputStream(proxySocket.getOutputStream());

        // read client request
        HttpRequest request = handleRequest(proxySocket);
        this.request = request;

        // send request to server
        //logger.debug("connecting to: " + request.getHost() + ":" + request.getPort());
        if (!((System.getProperty("http.proxyHost") == null)
                || System.getProperty("http.proxyHost").trim().equals(""))) {
            String proxyHost = System.getProperty("http.proxyHost");
            String proxyPortStr = System.getProperty("http.proxyPort");
            if (proxyPortStr == null || proxyPortStr.trim().equals("")) {
                proxyPortStr = "80";
            }
            int proxyPort = Integer.parseInt(proxyPortStr);
            //logger.debug("connecting via proxy: " + proxyHost + ":" + proxyPort);
            destinationSocket = new Socket(proxyHost, proxyPort);
        } else {
            destinationSocket = new Socket(request.getHost(), request.getPort());
        }
        OutputStream destinationOutputStream = destinationSocket.getOutputStream();
        destinationOutputStream.write(request.getRequest(), 0, request.getRequest().length);
        destinationOutputStream.flush();
        //logger.debug("request sent");

        // read response from server
        HttpResponse response = handleResponse(destinationSocket, proxyClientStream);
        this.response = response;
        destinationSocket.close();
        destinationSocket = null;

        // send response to client
        proxyClientStream.flush();
        proxySocket.close();
        proxySocket = null;
        duration = System.currentTimeMillis() - starttime;
        //logger.debug("duration: " + duration);
        String path = "http://" + request.getHost()
                + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
        proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path, starttime,
                request.getRequest(), this.response.getResponse(), duration);
    } catch (Exception e) {
        //logger.error("Error occurred: " + e.toString());
        duration = System.currentTimeMillis() - starttime;
        if (request != null) {
            String path = "http://" + request.getHost()
                    + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
            if (response != null && response.getResponse() != null) {
                proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path,
                        starttime, request.getRequest(), response.getResponse(), duration);
            } else {
                proxy.setWorkerResult(request.getMethod(), "XXX", path, starttime, request.getRequest(),
                        ("no response available - " + e.toString()).getBytes(), duration);
            }
        } else {
            proxy.setWorkerResult("---", "---", "---", starttime, e.toString().getBytes(),
                    "no response available".getBytes(), duration);
        }
        try {
            if (proxySocket != null) {
                closeSocket(proxySocket);
            }
        } finally {
            if (destinationSocket != null) {
                closeSocket(destinationSocket);
            }
        }
    }
}

From source file:se.vgregion.service.barium.BariumRestClientImpl.java

private String doRequest(String method, String uri, byte[] data, int methodCallCount) throws BariumException {

    LOGGER.debug("doRequest: apiLocation: " + apiLocation + ", method: " + method + ", uri: " + uri + ", data: "
            + (data != null ? new String(data) : ""));

    URL url;/*  w w  w.j a v  a 2s.c o  m*/
    HttpURLConnection conn = null;
    String response = null;

    InputStream inputStream = null;
    BufferedInputStream bis = null;

    OutputStream outputStream = null;
    BufferedOutputStream bos = null;
    try {
        if (method.equalsIgnoreCase("POST")) {
            if (uri != null) {
                url = new URL(this.apiLocation + uri);
            } else {
                throw new RuntimeException("For POST requests a uri is expected.");
            }
        } else {
            url = new URL(this.apiLocation + uri);
        }

        //            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(8888));
        conn = (HttpURLConnection) url.openConnection(/*proxy*/);
        conn.setConnectTimeout(120000);
        conn.setReadTimeout(120000);
        if (ticket != null) {
            conn.setRequestProperty("ticket", ticket);
        } else if (!uri.contains("authenticate")) {
            this.connect();
            conn.setRequestProperty("ticket", ticket);
        }
        conn.setRequestMethod(method);
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        if (method.equalsIgnoreCase("POST")) {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            outputStream = conn.getOutputStream();
            bos = new BufferedOutputStream(outputStream);

            bos.write(data);
            bos.flush();
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
            ticket = null; // We weren't authorized, possibly due to an old ticket.
            this.connect();
            if (methodCallCount <= 3) {
                return doRequest(method, uri, data, ++methodCallCount);
            } else {
                String msg = "Error - Unable to authenticate to Barium: " + uri;
                readResponseAndThrowBariumException(conn, msg);
            }
        } else if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            if (methodCallCount <= 3) {
                return doRequest(method, uri, data, ++methodCallCount);
            } else {
                String msg = "Error - Internal Server Error - From Barium - for idea: " + uri;
                readResponseAndThrowBariumException(conn, msg);
            }
        }

        inputStream = conn.getInputStream();
        bis = new BufferedInputStream(inputStream);

        response = toString(bis);
    } catch (IOException e) {

        if (conn != null) {
            inputStream = conn.getErrorStream();
            bis = new BufferedInputStream(inputStream);
            try {
                response = toString(bis);
            } catch (Exception e2) {
                LOGGER.error(e2.getMessage(), e2);
            }
            throw new BariumException(response, e);
        }
    } finally {
        Util.closeClosables(bis, inputStream, bos, outputStream);
    }
    LOGGER.debug("Response: " + response);
    return response;
}

From source file:och.util.socket.json.server.JsonProtocolSocketHandler.java

@Override
public void process(Socket openedSocket, InputStream socketIn, OutputStream socketOut, SocketServer owner)
        throws Throwable {

    SocketAddress remoteAddress = openedSocket.getRemoteSocketAddress();

    BufferedReader reader = SocketUtil.getReaderUTF8(socketIn);
    BufferedOutputStream os = new BufferedOutputStream(socketOut);
    while (!owner.wasShutdown()) {

        String line = reader.readLine();
        if (line == null || owner.wasShutdown())
            break;

        //process req
        try {//  w  w w . j  a  v a 2  s.co  m

            try {
                line = secureProvider.decode(line);
            } catch (Throwable t) {
                throw new InvalidReqException("decode exception: " + t.getMessage());
            }

            if (!line.startsWith(PROTOCOL_PREFIX))
                throw new InvalidReqException("unknown protocol: " + line);

            String data = line.substring(PROTOCOL_PREFIX.length());
            int typeSepIndex = data.indexOf(':');
            if (typeSepIndex < 1)
                throw new InvalidReqException("no data type in req: " + line);

            String typeStr = data.substring(0, typeSepIndex);
            Class<?> type = null;
            try {
                type = Class.forName(typeStr);
            } catch (Exception e) {
                throw new InvalidReqException("not java class: " + typeStr);
            }

            ReqController<? super Object, ?> controller = controllers.get(type);
            if (controller == null)
                throw new InvalidReqException("no controller for type: " + type);

            Object req = null;
            try {

                String jsonReq = data.substring(typeSepIndex + 1);

                if (hasText(jsonReq))
                    req = defaultGson.fromJson(jsonReq, type);
            } catch (Exception e) {
                throw new InvalidReqException("invalid json data in req: " + data);
            }

            //process
            Object resp = controller.processReq(req, remoteAddress);

            //send resp
            String jsonResp = resp == null ? "" : defaultGson.toJson(resp);

            writeLine(os, OK + controller.respType + ":" + jsonResp);
            os.flush();

        } catch (Exception e) {
            //connection closed
            if (e instanceof SocketException)
                throw e;
            //validation error
            else if (e instanceof ValidationException)
                sendAndFlush(os, validationError((ValidationException) e));
            //unexpected error
            else {
                log.error("unexpected exception: ", e);
                sendAndFlush(os, UNEXPECTED_ERROR + e);
            }
        }
    }
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * Extracts a file from an archive and stores it in a temporary location.
 * The file will be deleted when the virtual machine exits.
 * //from  www . j av  a2s. c om
 * @param archive
 * @param needle
 * @return
 * @throws MojoExecutionException
 */
@SuppressWarnings("unchecked")
public static File getFileFromArchive(ArchiveFile archive, String needle) throws MojoExecutionException {

    final int BUFFER = 2048;
    BufferedOutputStream dest = null;
    BufferedInputStream is = null;
    Entry entry;

    Enumeration<? extends Entry> e;
    try {
        e = archive.getEntries();
    } catch (IOException ex) {
        throw new MojoExecutionException("Error getting entries from archive", ex);
    }

    while (e.hasMoreElements()) {
        entry = e.nextElement();
        // If the entry we are in matches the needle we will store its
        // contents to a temp file
        if (entry.getName().equals(needle)) {
            // The file will be saved in the temporary directory
            File tempDir = new File(System.getProperty("java.io.tmpdir"));

            File extractedFile;
            try {
                extractedFile = File.createTempFile("pkg-maven-plugin", "temp", tempDir);
            } catch (IOException ex) {
                throw new MojoExecutionException("Error creating temporary file found", ex);
            }

            try {
                is = new BufferedInputStream(archive.getInputStream(entry));
            } catch (IOException ex) {
                throw new MojoExecutionException("Error reading entry from archive", ex);
            }

            int count;
            byte data[] = new byte[BUFFER];
            FileOutputStream fos;

            try {
                fos = new FileOutputStream(extractedFile);
            } catch (FileNotFoundException ex) {
                throw new MojoExecutionException("Error reading entry from archive", ex);
            }

            dest = new BufferedOutputStream(fos, BUFFER);

            try {
                while ((count = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
            } catch (IOException ex) {
                throw new MojoExecutionException("Error writing to temporary file", ex);
            } finally {
                try {
                    dest.flush();
                    dest.close();
                    is.close();
                } catch (IOException ex) {
                    throw new MojoExecutionException("Error closing streams.", ex);
                }
            }
            extractedFile.deleteOnExit();
            return extractedFile;
        }
    }
    throw new MojoExecutionException("Desired file not found");
}

From source file:org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.java

/**
* unzips the payload file/*from   w ww  . j  a  v a 2s .  c  o  m*/
* 
* @param file
 * @param tempfileName 
*/
private void unzipFile(File file, String tempfileName) {

    int buffer = 2048;
    BufferedOutputStream dest = null;
    ZipInputStream zis = null;

    try {
        FileInputStream fis = new FileInputStream(file);
        zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;

        while ((entry = zis.getNextEntry()) != null) {

            log.debug("Extracting: " + entry);

            int count;
            byte data[] = new byte[buffer];
            String outputFilename = tempfileName + File.separator + entry.getName();
            createDirIfNeeded(tempfileName, entry);

            // write the files to the disk
            if (!entry.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(outputFilename);
                dest = new BufferedOutputStream(fos, buffer);
                while ((count = zis.read(data, 0, buffer)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }

    } catch (Exception e) {
        log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
        throw new AutoscalerServiceException(e.getMessage(), e);
    } finally {
        closeStream(zis);
        closeStream(dest);
    }
}

From source file:it.attocchi.jsf2.PageBase.java

protected void downloadPDF(String fileName, String rename) throws IOException {

    // Prepare./* w ww  .  j  a  va 2s .c om*/
    FacesContext facesContext = getFacesContext();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    File file = new File(fileName);
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open file.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);

        String downloadFileName = file.getName();
        if (rename != null && !rename.equals("")) {
            /*
             * controllo se rename specifica l'estensione, se non la
             * specifica la impostiamo dal nome originale
             */
            String extNuova = FilenameUtils.getExtension(rename);
            String extOrig = FilenameUtils.getExtension(fileName);
            if (StringUtils.isBlank(extNuova))
                if (StringUtils.isNotBlank(extNuova))
                    rename = rename + "." + extOrig;
            downloadFileName = rename;
            // fileName.substring(fileName.lastIndexOf("."));
        }

        // Init servlet response.
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Length", String.valueOf(file.length()));
        // response.setHeader("Content-Disposition", "inline; filename=\"" +
        // downloadFileName + "\"");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Finalize task.
        output.flush();
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }

    // Inform JSF that it doesn't need to handle response.
    // This is very important, otherwise you will get the following
    // exception in the logs:
    // java.lang.IllegalStateException: Cannot forward after response has
    // been committed.
    facesContext.responseComplete();
}